From 6b44196c40a66b895028f7ba2e9b5e41bc715ab2 Mon Sep 17 00:00:00 2001 From: Jinkun Jang Date: Mon, 18 Mar 2013 11:21:46 +0900 Subject: [PATCH] sync with tizen_2.0 --- CMakeLists.txt | 63 + LICENSE.APLv2 | 202 ++ LICENSE.Flora | 206 ++ NOTICE | 8 + inc/FApp.h | 82 + inc/FAppApp.h | 369 ++ inc/FAppAppControl.h | 1417 ++++++++ inc/FAppAppControlProviderManager.h | 171 + inc/FAppAppManager.h | 762 ++++ inc/FAppAppRegistry.h | 354 ++ inc/FAppAppResource.h | 272 ++ inc/FAppAppSetting.h | 357 ++ inc/FAppApplication.h | 30 + inc/FAppDataControlProviderManager.h | 278 ++ inc/FAppIActiveAppEventListener.h | 108 + inc/FAppIAppCheckPointEventListener.h | 98 + inc/FAppIAppControlEventListener.h | 124 + inc/FAppIAppControlListener.h | 109 + inc/FAppIAppControlProviderEventListener.h | 112 + inc/FAppIAppControlResponseListener.h | 150 + inc/FAppIAppFrame.h | 149 + inc/FAppIAppLaunchConditionEventListener.h | 116 + inc/FAppIAppSettingEventListener.h | 95 + inc/FAppIMapDataControlProviderEventListener.h | 317 ++ inc/FAppIMapDataControlResponseListener.h | 193 ++ inc/FAppISqlDataControlProviderEventListener.h | 396 +++ inc/FAppISqlDataControlResponseListener.h | 192 ++ inc/FAppMapDataControl.h | 221 ++ inc/FAppNotificationManager.h | 650 ++++ inc/FAppPkg.h | 53 + inc/FAppPkgIPackageInstallationEventListener.h | 136 + inc/FAppPkgIPackageInstallationResponseListener.h | 130 + ...FAppPkgIPackageUninstallationResponseListener.h | 117 + inc/FAppPkgPackageAppInfo.h | 188 + inc/FAppPkgPackageInfo.h | 266 ++ inc/FAppPkgPackageManager.h | 314 ++ inc/FAppService.h | 30 + inc/FAppServiceApp.h | 151 + inc/FAppSqlDataControl.h | 259 ++ inc/FAppTypes.h | 143 + inc/FAppUiApp.h | 300 ++ inc/FBase.h | 94 + inc/FBaseBoolean.h | 279 ++ inc/FBaseBuffer.h | 830 +++++ inc/FBaseBufferBase.h | 438 +++ inc/FBaseByteBuffer.h | 1303 +++++++ inc/FBaseCharacter.h | 639 ++++ inc/FBaseCol.h | 78 + inc/FBaseColAllElementsDeleter.h | 58 + inc/FBaseColArrayList.h | 670 ++++ inc/FBaseColArrayListT.h | 1314 +++++++ inc/FBaseColHashMap.h | 499 +++ inc/FBaseColHashMapT.h | 1334 +++++++ inc/FBaseColIBidirectionalEnumerator.h | 115 + inc/FBaseColIBidirectionalEnumeratorT.h | 96 + inc/FBaseColICollection.h | 115 + inc/FBaseColICollectionT.h | 88 + inc/FBaseColIComparer.h | 96 + inc/FBaseColIComparerT.h | 78 + inc/FBaseColIEnumerator.h | 135 + inc/FBaseColIEnumeratorT.h | 108 + inc/FBaseColIHashCodeProvider.h | 91 + inc/FBaseColIHashCodeProviderT.h | 68 + inc/FBaseColIList.h | 824 +++++ inc/FBaseColIListT.h | 387 +++ inc/FBaseColIMap.h | 492 +++ inc/FBaseColIMapEnumerator.h | 120 + inc/FBaseColIMapEnumeratorT.h | 95 + inc/FBaseColIMapT.h | 230 ++ inc/FBaseColIMultiMap.h | 596 ++++ inc/FBaseColIMultiMapT.h | 280 ++ inc/FBaseColLinkedList.h | 627 ++++ inc/FBaseColLinkedListT.h | 1529 ++++++++ inc/FBaseColMapEntry.h | 160 + inc/FBaseColMapEntryT.h | 154 + inc/FBaseColMultiHashMap.h | 551 +++ inc/FBaseColMultiHashMapT.h | 1856 ++++++++++ inc/FBaseColQueue.h | 336 ++ inc/FBaseColQueueT.h | 655 ++++ inc/FBaseColStack.h | 340 ++ inc/FBaseColStackT.h | 655 ++++ inc/FBaseColTypes.h | 64 + inc/FBaseComparerT.h | 139 + inc/FBaseDataType.h | 95 + inc/FBaseDateTime.h | 602 ++++ inc/FBaseDouble.h | 412 +++ inc/FBaseDoubleComparer.h | 129 + inc/FBaseDoubleMatrix.h | 467 +++ inc/FBaseDoubleMatrix3.h | 412 +++ inc/FBaseDoubleMatrix4.h | 412 +++ inc/FBaseErrorDefine.h | 53 + inc/FBaseErrors.h | 582 ++++ inc/FBaseFloat.h | 402 +++ inc/FBaseFloatComparer.h | 129 + inc/FBaseFloatMatrix.h | 466 +++ inc/FBaseFloatMatrix3.h | 412 +++ inc/FBaseFloatMatrix4.h | 412 +++ inc/FBaseInt8.h | 350 ++ inc/FBaseInt8Comparer.h | 130 + inc/FBaseIntMatrix.h | 459 +++ inc/FBaseInteger.h | 352 ++ inc/FBaseIntegerComparer.h | 129 + inc/FBaseLog.h | 687 ++++ inc/FBaseLong.h | 349 ++ inc/FBaseLongComparer.h | 129 + inc/FBaseLongLong.h | 325 ++ inc/FBaseLongLongComparer.h | 128 + inc/FBaseNumber.h | 174 + inc/FBaseObject.h | 116 + inc/FBaseResult.h | 103 + inc/FBaseRt.h | 73 + inc/FBaseRtEvent.h | 177 + inc/FBaseRtEventDrivenThread.h | 276 ++ inc/FBaseRtIEventArg.h | 47 + inc/FBaseRtIEventListener.h | 58 + inc/FBaseRtIRunnable.h | 107 + inc/FBaseRtITimerEventListener.h | 72 + inc/FBaseRtIWaitingLoopCondition.h | 57 + inc/FBaseRtLibrary.h | 108 + inc/FBaseRtMemoryManager.h | 125 + inc/FBaseRtMonitor.h | 380 ++ inc/FBaseRtMonitorGuard.h | 132 + inc/FBaseRtMutex.h | 191 + inc/FBaseRtMutexGuard.h | 323 ++ inc/FBaseRtSemaphore.h | 193 ++ inc/FBaseRtSemaphoreGuard.h | 188 + inc/FBaseRtThread.h | 495 +++ inc/FBaseRtTimer.h | 226 ++ inc/FBaseRtTypes.h | 85 + inc/FBaseRtWaitingLoop.h | 151 + inc/FBaseShort.h | 368 ++ inc/FBaseShortComparer.h | 130 + inc/FBaseString.h | 1111 ++++++ inc/FBaseStringComparer.h | 129 + inc/FBaseSys.h | 25 + inc/FBaseSysLog.h | 685 ++++ inc/FBaseTimeSpan.h | 432 +++ inc/FBaseTypes.h | 89 + inc/FBaseUtil.h | 91 + inc/FBaseUtilDeflator.h | 162 + inc/FBaseUtilFileUnzipper.h | 287 ++ inc/FBaseUtilFileZipper.h | 201 ++ inc/FBaseUtilInflator.h | 150 + inc/FBaseUtilLinkInfo.h | 183 + inc/FBaseUtilMath.h | 402 +++ inc/FBaseUtilRegularExpression.h | 445 +++ inc/FBaseUtilStringTokenizer.h | 212 ++ inc/FBaseUtilStringUtil.h | 375 ++ inc/FBaseUtilTypes.h | 67 + inc/FBaseUtilUri.h | 963 ++++++ inc/FBaseUtilUrlDecoder.h | 116 + inc/FBaseUtilUrlEncoder.h | 118 + inc/FBaseUtilZipEntry.h | 227 ++ inc/FBaseUuId.h | 300 ++ inc/FGrpBitmapCommon.h | 85 + inc/FIo.h | 74 + inc/FIoChannel.h | 38 + inc/FIoChannelTypes.h | 45 + inc/FIoClientChannel.h | 213 ++ inc/FIoDatabase.h | 845 +++++ inc/FIoDbEnumerator.h | 469 +++ inc/FIoDbStatement.h | 303 ++ inc/FIoDbTypes.h | 56 + inc/FIoDirEntry.h | 278 ++ inc/FIoDirEnumerator.h | 226 ++ inc/FIoDirectory.h | 321 ++ inc/FIoFile.h | 908 +++++ inc/FIoFileAttributes.h | 248 ++ inc/FIoFileEventManager.h | 178 + inc/FIoIChannelRequestEventListener.h | 97 + inc/FIoIChannelResponseEventListener.h | 97 + inc/FIoIDbEnumerator.h | 409 +++ inc/FIoIFileEventListener.h | 97 + inc/FIoIMessagePortListener.h | 122 + inc/FIoIMmcStorageFormatListener.h | 92 + inc/FIoIMmcStorageMountListener.h | 106 + inc/FIoISerialPortEventListener.h | 109 + inc/FIoLocalMessagePort.h | 189 + inc/FIoMemoryMappedFile.h | 219 ++ inc/FIoMessagePortManager.h | 152 + inc/FIoMmcStorageManager.h | 205 ++ inc/FIoRegistry.h | 962 ++++++ inc/FIoRemoteMessagePort.h | 205 ++ inc/FIoSerialPort.h | 176 + inc/FIoServerChannel.h | 212 ++ inc/FIoSqlStatementBuilder.h | 202 ++ inc/FLclCalendar.h | 1145 ++++++ inc/FLclCurrency.h | 209 ++ inc/FLclDateTimeFormatter.h | 386 +++ inc/FLclDateTimeSymbols.h | 401 +++ inc/FLclGregorianCalendar.h | 649 ++++ inc/FLclLocale.h | 1176 +++++++ inc/FLclLocaleManager.h | 306 ++ inc/FLclNumberFormatter.h | 683 ++++ inc/FLclNumberSymbols.h | 192 ++ inc/FLclTimeRule.h | 335 ++ inc/FLclTimeZone.h | 567 +++ inc/FLocales.h | 64 + inc/FOspCompat.h | 259 ++ inc/FOspConfig.h | 34 + inc/FSecAccessController.h | 96 + inc/FSecAesSecureRandom.h | 108 + inc/FSecCert.h | 58 + inc/FSecCertICertificate.h | 440 +++ inc/FSecCertICertificatePath.h | 343 ++ inc/FSecCertICertificateSelector.h | 109 + inc/FSecCertICertificateStore.h | 211 ++ inc/FSecCertTypes.h | 50 + inc/FSecCertX509Certificate.h | 355 ++ inc/FSecCertX509CertificatePath.h | 185 + inc/FSecCertX509CertificateSelector.h | 98 + inc/FSecCertX509CertificateStore.h | 252 ++ inc/FSecCrypto.h | 75 + inc/FSecCryptoAesCipher.h | 281 ++ inc/FSecCryptoCastCipher.h | 269 ++ inc/FSecCryptoDesCipher.h | 269 ++ inc/FSecCryptoDesEdeCipher.h | 267 ++ inc/FSecCryptoDhKeyExchange.h | 271 ++ inc/FSecCryptoIAsymmetricCipher.h | 245 ++ inc/FSecCryptoIHash.h | 296 ++ inc/FSecCryptoIHmac.h | 404 +++ inc/FSecCryptoIKeyExchange.h | 128 + inc/FSecCryptoISignature.h | 235 ++ inc/FSecCryptoISymmetricCipher.h | 424 +++ inc/FSecCryptoKeaKeyExchange.h | 349 ++ inc/FSecCryptoMd5Hash.h | 174 + inc/FSecCryptoMd5Hmac.h | 190 + inc/FSecCryptoRc2Cipher.h | 271 ++ inc/FSecCryptoRc4Cipher.h | 269 ++ inc/FSecCryptoRsaCipher.h | 166 + inc/FSecCryptoRsaSignature.h | 165 + inc/FSecCryptoSha1Hash.h | 174 + inc/FSecCryptoSha1Hmac.h | 189 + inc/FSecCryptoSha2Hash.h | 172 + inc/FSecCryptoSha2Hmac.h | 188 + inc/FSecCryptoSkipJackCipher.h | 268 ++ inc/FSecCryptoTypes.h | 72 + inc/FSecDesEdeSecureRandom.h | 108 + inc/FSecDesSecureRandom.h | 108 + inc/FSecDhKeyParameters.h | 187 + inc/FSecIKey.h | 110 + inc/FSecIKeyPairGenerator.h | 103 + inc/FSecIKeyParameters.h | 114 + inc/FSecIPrivateKey.h | 106 + inc/FSecIPublicKey.h | 106 + inc/FSecISecretKey.h | 106 + inc/FSecISecretKeyGenerator.h | 89 + inc/FSecISecureRandom.h | 92 + inc/FSecKeaKeyParameters.h | 194 ++ inc/FSecKeyPair.h | 157 + inc/FSecKeyPairGenerator.h | 191 + inc/FSecPrivateKey.h | 132 + inc/FSecPublicKey.h | 132 + inc/FSecSecretKey.h | 130 + inc/FSecSecretKeyGenerator.h | 152 + inc/FSecurity.h | 78 + inc/FSysAlarm.h | 181 + inc/FSysBattery.h | 132 + inc/FSysDeviceManager.h | 221 ++ inc/FSysEnvironment.h | 149 + inc/FSysIAlarmEventListener.h | 94 + inc/FSysIBatteryEventListener.h | 90 + inc/FSysIChargingEventListener.h | 89 + inc/FSysIDeviceEventListener.h | 92 + inc/FSysIRuntimeInfoGetIntAsyncResultListener.h | 91 + ...SysIRuntimeInfoGetLonglongAsyncResultListener.h | 90 + inc/FSysIScreenEventListener.h | 91 + inc/FSysISettingEventListener.h | 89 + inc/FSysISettingInfoSetValueAsyncResultListener.h | 133 + inc/FSysPowerManager.h | 313 ++ inc/FSysRuntimeInfo.h | 246 ++ inc/FSysSettingInfo.h | 505 +++ inc/FSysSystemInfo.h | 303 ++ inc/FSysSystemTime.h | 158 + inc/FSysVibrator.h | 210 ++ inc/FSystem.h | 89 + inc/FText.h | 69 + inc/FTextAsciiEncoding.h | 379 ++ inc/FTextDecoder.h | 158 + inc/FTextEncoder.h | 156 + inc/FTextEncoding.h | 658 ++++ inc/FTextGsmEncoding.h | 447 +++ inc/FTextLatin1Encoding.h | 372 ++ inc/FTextUcs2Encoding.h | 477 +++ inc/FTextUtf8Decoder.h | 212 ++ inc/FTextUtf8Encoder.h | 221 ++ inc/FTextUtf8Encoding.h | 472 +++ inc/FXml.h | 164 + inc/Framework.h | 37 + inc/unique_ptr.h | 42 + inc/unique_ptr.hpp | 536 +++ osp-appfw.manifest | 16 + osp-appfw.pc.in | 13 + packaging/osp-appfw.spec | 226 ++ res/arm/usr/etc/media-capability.xml | 172 + res/arm/usr/etc/system-info.ini | 26 + res/common/etc/ld.so.conf.d/osp.conf | 1 + res/common/opt/usr/etc/system-log.ini | 55 + .../share/AppControl/ac-calendar/TestEvent.vcs | 11 + .../share/AppControl/ac-calendar/TestMemo.vnt | 6 + .../share/AppControl/ac-calendar/TestTodo.vcs | 12 + .../share/AppControl/ac-contact/TestContact.vcf | 9 + res/common/usr/etc/content-download.ini | 2 + res/x86/usr/etc/media-capability.xml | 154 + res/x86/usr/etc/system-info.ini | 26 + src/CMakeLists.txt | 51 + src/app/CMakeLists.txt | 82 + src/app/FAppApp.cpp | 192 ++ src/app/FAppAppControl.cpp | 140 + src/app/FAppAppControlProviderManager.cpp | 84 + src/app/FAppAppManager.cpp | 399 +++ src/app/FAppAppRegistry.cpp | 185 + src/app/FAppAppResource.cpp | 250 ++ src/app/FAppAppSetting.cpp | 159 + src/app/FAppDataControlProviderManager.cpp | 116 + src/app/FAppMapDataControl.cpp | 97 + src/app/FAppNotificationManager.cpp | 262 ++ src/app/FAppNotificationMessage.cpp | 229 ++ src/app/FAppServiceApp.cpp | 100 + src/app/FAppSqlDataControl.cpp | 95 + src/app/FApp_AppArg.cpp | 1321 +++++++ src/app/FApp_AppControlEvent.cpp | 77 + src/app/FApp_AppControlEventArg.cpp | 89 + src/app/FApp_AppControlEventArg.h | 167 + src/app/FApp_AppControlImpl.cpp | 885 +++++ src/app/FApp_AppControlManager.cpp | 677 ++++ src/app/FApp_AppControlProviderManagerImpl.cpp | 167 + src/app/FApp_AppControlProviderManagerImpl.h | 104 + src/app/FApp_AppControlRegistry.cpp | 694 ++++ src/app/FApp_AppControlRegistry.h | 132 + src/app/FApp_AppEntry.cpp | 489 +++ src/app/FApp_AppImpl.cpp | 1210 +++++++ src/app/FApp_AppInfo.cpp | 536 +++ src/app/FApp_AppLaunchCondition.cpp | 118 + src/app/FApp_AppLaunchConditionHandlerBase.cpp | 52 + src/app/FApp_AppManagerEvent.cpp | 130 + src/app/FApp_AppManagerImpl.cpp | 1090 ++++++ src/app/FApp_AppManagerIpcMessage.cpp | 46 + src/app/FApp_AppManagerProxy.cpp | 255 ++ src/app/FApp_AppMessageImpl.cpp | 280 ++ src/app/FApp_AppRegistryImpl.cpp | 266 ++ src/app/FApp_AppRegistryImpl.h | 240 ++ src/app/FApp_AppResourceImpl.cpp | 200 ++ src/app/FApp_AppResourceImpl.h | 184 + src/app/FApp_AppResourceString.cpp | 644 ++++ src/app/FApp_AppResourceString.h | 118 + src/app/FApp_AppSettingImpl.cpp | 1201 +++++++ src/app/FApp_AppSettingImpl.h | 129 + src/app/FApp_Aul.cpp | 579 ++++ src/app/FApp_ConditionManagerIpcMessages.cpp | 46 + src/app/FApp_ConditionManagerProxy.cpp | 123 + src/app/FApp_ConditionManagerProxy.h | 70 + src/app/FApp_DataControlProviderManagerImpl.cpp | 347 ++ src/app/FApp_DataControlProviderManagerImpl.h | 120 + src/app/FApp_ImeAppImpl.cpp | 397 +++ src/app/FApp_ImeAppImpl.h | 221 ++ src/app/FApp_LongevityManager.cpp | 60 + src/app/FApp_LongevityManager.h | 65 + src/app/FApp_MapDataControlImpl.cpp | 470 +++ src/app/FApp_MapDataControlImpl.h | 98 + src/app/FApp_NotificationManagerImpl.cpp | 582 ++++ src/app/FApp_NotificationManagerIpcMessages.cpp | 46 + src/app/FApp_NotificationManagerProxy.cpp | 88 + src/app/FApp_NotificationManagerProxy.h | 70 + src/app/FApp_NotificationMessageImpl.cpp | 366 ++ src/app/FApp_NotificationMessageImpl.h | 333 ++ src/app/FApp_PackageManagerIpcMessages.cpp | 46 + src/app/FApp_PackageManagerProxy.cpp | 92 + src/app/FApp_ServiceAppImpl.cpp | 227 ++ src/app/FApp_SqlDataControlImpl.cpp | 598 ++++ src/app/FApp_SqlDataControlImpl.h | 99 + src/app/inc/FAppNotificationMessage.h | 340 ++ src/app/inc/FAppPkg_PackageAppInfoImpl.h | 384 +++ src/app/inc/FAppPkg_PackageInfoImpl.h | 229 ++ src/app/inc/FAppPkg_PackageManagerImpl.h | 193 ++ src/app/inc/FApp_AppArg.h | 222 ++ src/app/inc/FApp_AppControlEvent.h | 53 + src/app/inc/FApp_AppControlImpl.h | 292 ++ src/app/inc/FApp_AppControlManager.h | 295 ++ src/app/inc/FApp_AppImpl.h | 466 +++ src/app/inc/FApp_AppInfo.h | 262 ++ src/app/inc/FApp_AppLaunchCondition.h | 148 + src/app/inc/FApp_AppLaunchConditionHandlerBase.h | 133 + src/app/inc/FApp_AppManagerEvent.h | 60 + src/app/inc/FApp_AppManagerEventArg.h | 67 + src/app/inc/FApp_AppManagerEventParamTraits.h | 78 + src/app/inc/FApp_AppManagerImpl.h | 387 +++ src/app/inc/FApp_AppManagerIpcMessage.h | 44 + src/app/inc/FApp_AppManagerProxy.h | 97 + src/app/inc/FApp_AppMessageImpl.h | 96 + src/app/inc/FApp_AppUserEvent.h | 68 + src/app/inc/FApp_AppUserEventArg.h | 70 + src/app/inc/FApp_Aul.h | 118 + src/app/inc/FApp_ConditionManagerIpcMessages.h | 33 + src/app/inc/FApp_IActiveWindowEventListener.h | 41 + src/app/inc/FApp_IAppControlSysEventListener.h | 57 + src/app/inc/FApp_IAppImpl.h | 124 + .../inc/FApp_IAppLaunchConditionEventListener.h | 60 + src/app/inc/FApp_IAppManager.h | 57 + src/app/inc/FApp_IAppManagerEventListener.h | 69 + src/app/inc/FApp_IAppManagerServiceEventListener.h | 53 + src/app/inc/FApp_IAppResourceBitmap.h | 52 + src/app/inc/FApp_IAppUserEventListener.h | 48 + .../inc/FApp_NotificationManagerEventParamTraits.h | 119 + src/app/inc/FApp_NotificationManagerImpl.h | 449 +++ src/app/inc/FApp_NotificationManagerIpcMessages.h | 35 + src/app/inc/FApp_PackageManagerIpcMessages.h | 31 + src/app/inc/FApp_PackageManagerProxy.h | 71 + src/app/inc/FApp_RequestManagerT.h | 166 + src/app/inc/FApp_ServiceAppImpl.h | 219 ++ src/app/inc/FApp_TemplateUtil.h | 158 + src/app/inc/FApp_Types.h | 114 + src/app/package/FAppPkgPackageAppInfo.cpp | 118 + src/app/package/FAppPkgPackageInfo.cpp | 162 + src/app/package/FAppPkgPackageManager.cpp | 219 ++ src/app/package/FAppPkg_PackageAppInfoImpl.cpp | 1240 +++++++ src/app/package/FAppPkg_PackageInfoImpl.cpp | 1193 +++++++ src/app/package/FAppPkg_PackageManagerImpl.cpp | 2553 ++++++++++++++ src/appfw/CMakeLists.txt | 116 + src/base/CMakeLists.txt | 127 + src/base/FBaseBoolean.cpp | 205 ++ src/base/FBaseBufferBase.cpp | 323 ++ src/base/FBaseByteBuffer.cpp | 871 +++++ src/base/FBaseCharacter.cpp | 292 ++ src/base/FBaseDateTime.cpp | 925 +++++ src/base/FBaseDouble.cpp | 293 ++ src/base/FBaseDoubleComparer.cpp | 57 + src/base/FBaseDoubleMatrix.cpp | 875 +++++ src/base/FBaseDoubleMatrix3.cpp | 492 +++ src/base/FBaseDoubleMatrix4.cpp | 635 ++++ src/base/FBaseErrors.cpp | 23 + src/base/FBaseFloat.cpp | 291 ++ src/base/FBaseFloatComparer.cpp | 55 + src/base/FBaseFloatMatrix.cpp | 874 +++++ src/base/FBaseFloatMatrix3.cpp | 492 +++ src/base/FBaseFloatMatrix4.cpp | 634 ++++ src/base/FBaseInit.cpp | 61 + src/base/FBaseInt8.cpp | 269 ++ src/base/FBaseInt8Comparer.cpp | 55 + src/base/FBaseIntMatrix.cpp | 873 +++++ src/base/FBaseInteger.cpp | 235 ++ src/base/FBaseIntegerComparer.cpp | 55 + src/base/FBaseLong.cpp | 233 ++ src/base/FBaseLongComparer.cpp | 55 + src/base/FBaseLongLong.cpp | 177 + src/base/FBaseLongLongComparer.cpp | 55 + src/base/FBaseObject.cpp | 68 + src/base/FBaseResult.cpp | 423 +++ src/base/FBaseShort.cpp | 273 ++ src/base/FBaseShortComparer.cpp | 54 + src/base/FBaseString.cpp | 1554 +++++++++ src/base/FBaseStringComparer.cpp | 54 + src/base/FBaseSys.cpp | 947 +++++ src/base/FBaseTimeSpan.cpp | 282 ++ src/base/FBaseTypes.cpp | 25 + src/base/FBaseUuId.cpp | 380 ++ src/base/FBase_CharacterImpl.cpp | 331 ++ src/base/FBase_CharacterImpl.h | 321 ++ src/base/FBase_Exception.cpp | 335 ++ src/base/FBase_NativeError.cpp | 439 +++ src/base/FBase_StringConverter.cpp | 59 + src/base/collection/FBaseColArrayList.cpp | 733 ++++ src/base/collection/FBaseColHashMap.cpp | 934 +++++ src/base/collection/FBaseColLinkedList.cpp | 976 ++++++ src/base/collection/FBaseColMapEntry.cpp | 102 + src/base/collection/FBaseColMultiHashMap.cpp | 1193 +++++++ src/base/collection/FBaseColQueue.cpp | 355 ++ src/base/collection/FBaseColStack.cpp | 343 ++ src/base/collection/FBaseColTypes.cpp | 66 + src/base/inc/FBaseInternalTypes.h | 65 + src/base/inc/FBaseRtIEvent.h | 170 + src/base/inc/FBaseRtIEventFilter.h | 75 + src/base/inc/FBaseRt_Event.h | 280 ++ src/base/inc/FBaseRt_EventDispatcher.h | 134 + src/base/inc/FBaseRt_IEventListener.h | 53 + src/base/inc/FBaseRt_ITask.h | 44 + src/base/inc/FBaseRt_LibraryImpl.h | 126 + src/base/inc/FBaseRt_MainLoop.h | 119 + src/base/inc/FBaseRt_Process.h | 84 + src/base/inc/FBaseUtil_IcuConverter.h | 55 + src/base/inc/FBase_Exception.h | 403 +++ src/base/inc/FBase_HandleT.h | 162 + src/base/inc/FBase_Log.h | 100 + src/base/inc/FBase_NativeError.h | 125 + src/base/inc/FBase_ObjectManagerImpl.h | 365 ++ src/base/inc/FBase_ObjectManagerT.h | 216 ++ src/base/inc/FBase_StringConverter.h | 56 + src/base/runtime/FBaseRtEvent.cpp | 65 + src/base/runtime/FBaseRtEventDrivenThread.cpp | 100 + src/base/runtime/FBaseRtIEventListener.cpp | 51 + src/base/runtime/FBaseRtIRunnable.cpp | 35 + src/base/runtime/FBaseRtLibrary.cpp | 79 + src/base/runtime/FBaseRtMemoryManager.cpp | 86 + src/base/runtime/FBaseRtMonitor.cpp | 123 + src/base/runtime/FBaseRtMutex.cpp | 99 + src/base/runtime/FBaseRtSemaphore.cpp | 97 + src/base/runtime/FBaseRtThread.cpp | 238 ++ src/base/runtime/FBaseRtTimer.cpp | 98 + src/base/runtime/FBaseRtWaitingLoop.cpp | 98 + src/base/runtime/FBaseRt_Event.cpp | 332 ++ src/base/runtime/FBaseRt_EventDispatcher.cpp | 218 ++ .../runtime/FBaseRt_EventDrivenThreadEvent.cpp | 83 + src/base/runtime/FBaseRt_EventDrivenThreadEvent.h | 61 + .../runtime/FBaseRt_EventDrivenThreadEventArg.cpp | 64 + .../runtime/FBaseRt_EventDrivenThreadEventArg.h | 64 + src/base/runtime/FBaseRt_EventDrivenThreadImpl.cpp | 182 + src/base/runtime/FBaseRt_EventDrivenThreadImpl.h | 77 + src/base/runtime/FBaseRt_EventImpl.cpp | 52 + src/base/runtime/FBaseRt_EventImpl.h | 80 + src/base/runtime/FBaseRt_EventManager.cpp | 420 +++ src/base/runtime/FBaseRt_EventManager.h | 240 ++ .../FBaseRt_EventPendingOperationManager.cpp | 103 + .../runtime/FBaseRt_EventPendingOperationManager.h | 136 + src/base/runtime/FBaseRt_FilterInfo.h | 49 + .../FBaseRt_IEventDrivenThreadEventListener.h | 51 + src/base/runtime/FBaseRt_ITask.cpp | 34 + src/base/runtime/FBaseRt_LibraryImpl.cpp | 144 + src/base/runtime/FBaseRt_ListenerInfo.h | 52 + src/base/runtime/FBaseRt_MainLoop.cpp | 256 ++ src/base/runtime/FBaseRt_MainThreadImpl.cpp | 109 + src/base/runtime/FBaseRt_MainThreadImpl.h | 61 + src/base/runtime/FBaseRt_MonitorImpl.cpp | 116 + src/base/runtime/FBaseRt_MonitorImpl.h | 149 + src/base/runtime/FBaseRt_MutexImpl.cpp | 178 + src/base/runtime/FBaseRt_MutexImpl.h | 169 + src/base/runtime/FBaseRt_Process.cpp | 37 + src/base/runtime/FBaseRt_SemaphoreImpl.cpp | 187 + src/base/runtime/FBaseRt_SemaphoreImpl.h | 146 + src/base/runtime/FBaseRt_ThreadImpl.cpp | 294 ++ src/base/runtime/FBaseRt_ThreadImpl.h | 107 + src/base/runtime/FBaseRt_ThreadManager.cpp | 70 + src/base/runtime/FBaseRt_ThreadManager.h | 58 + src/base/runtime/FBaseRt_TimerImpl.cpp | 254 ++ src/base/runtime/FBaseRt_TimerImpl.h | 150 + src/base/runtime/FBaseRt_WaitingLoopImpl.cpp | 332 ++ src/base/runtime/FBaseRt_WaitingLoopImpl.h | 206 ++ src/base/runtime/FBaseRt_WorkerThreadImpl.cpp | 60 + src/base/runtime/FBaseRt_WorkerThreadImpl.h | 55 + src/base/utility/FBaseUtilDeflator.cpp | 172 + src/base/utility/FBaseUtilFileUnzipper.cpp | 143 + src/base/utility/FBaseUtilFileZipper.cpp | 101 + src/base/utility/FBaseUtilInflator.cpp | 173 + src/base/utility/FBaseUtilLinkInfo.cpp | 129 + src/base/utility/FBaseUtilMath.cpp | 272 ++ src/base/utility/FBaseUtilRegularExpression.cpp | 183 + src/base/utility/FBaseUtilStringTokenizer.cpp | 251 ++ src/base/utility/FBaseUtilStringUtil.cpp | 466 +++ src/base/utility/FBaseUtilUri.cpp | 3648 ++++++++++++++++++++ src/base/utility/FBaseUtilUrlDecoder.cpp | 136 + src/base/utility/FBaseUtilUrlEncoder.cpp | 132 + src/base/utility/FBaseUtilZipEntry.cpp | 140 + src/base/utility/FBaseUtil_FileUnzipperImpl.cpp | 432 +++ src/base/utility/FBaseUtil_FileUnzipperImpl.h | 74 + src/base/utility/FBaseUtil_FileZipperImpl.cpp | 228 ++ src/base/utility/FBaseUtil_FileZipperImpl.h | 77 + src/base/utility/FBaseUtil_IcuConverter.cpp | 204 ++ .../utility/FBaseUtil_RegularExpressionImpl.cpp | 1017 ++++++ src/base/utility/FBaseUtil_RegularExpressionImpl.h | 98 + src/base/utility/FBaseUtil_ZipEntryInfo.h | 70 + src/io/CMakeLists.txt | 94 + src/io/FIoClientChannel.cpp | 126 + src/io/FIoDatabase.cpp | 255 ++ src/io/FIoDbEnumerator.cpp | 159 + src/io/FIoDbStatement.cpp | 125 + src/io/FIoDirEntry.cpp | 122 + src/io/FIoDirEnumerator.cpp | 73 + src/io/FIoDirectory.cpp | 102 + src/io/FIoFile.cpp | 313 ++ src/io/FIoFileAttributes.cpp | 125 + src/io/FIoFileEventManager.cpp | 104 + src/io/FIoLocalMessagePort.cpp | 68 + src/io/FIoMemoryMappedFile.cpp | 109 + src/io/FIoMessagePortManager.cpp | 81 + src/io/FIoMmcStorageManager.cpp | 154 + src/io/FIoRegistry.cpp | 550 +++ src/io/FIoRemoteMessagePort.cpp | 80 + src/io/FIoSerialPort.cpp | 74 + src/io/FIoServerChannel.cpp | 126 + src/io/FIoSqlStatementBuilder.cpp | 239 ++ src/io/FIo_Channel.cpp | 178 + src/io/FIo_ChannelCAppStub.cpp | 557 +++ src/io/FIo_ChannelManager.cpp | 185 + src/io/FIo_ChannelMessages.cpp | 26 + src/io/FIo_ChannelService.cpp | 323 ++ src/io/FIo_ChannelServiceManager.cpp | 96 + src/io/FIo_ChannelServiceProxy.cpp | 364 ++ src/io/FIo_ChannelServiceStub.cpp | 230 ++ src/io/FIo_ChannelWebAppStub.cpp | 1125 ++++++ src/io/FIo_ClientChannelImpl.cpp | 202 ++ src/io/FIo_DataControlResultSetEnumerator.cpp | 889 +++++ src/io/FIo_DataControlResultSetImpl.cpp | 409 +++ src/io/FIo_DataRouter.cpp | 195 ++ src/io/FIo_DatabaseImpl.cpp | 1716 +++++++++ src/io/FIo_DbContextImpl.cpp | 193 ++ src/io/FIo_DbEnumeratorImpl.cpp | 1209 +++++++ src/io/FIo_DbStatementImpl.cpp | 410 +++ src/io/FIo_DirEntryImpl.cpp | 197 ++ src/io/FIo_DirEnumeratorImpl.cpp | 260 ++ src/io/FIo_DirectoryImpl.cpp | 504 +++ src/io/FIo_FileAttributesImpl.cpp | 187 + src/io/FIo_FileEventManagerImpl.cpp | 336 ++ src/io/FIo_FileImpl.cpp | 1383 ++++++++ src/io/FIo_FileUtil.cpp | 851 +++++ src/io/FIo_IIpcClientEventListener.cpp | 36 + src/io/FIo_IIpcServerEventListener.cpp | 34 + src/io/FIo_IpcClient.cpp | 594 ++++ src/io/FIo_IpcServer.cpp | 788 +++++ src/io/FIo_LocalMessagePortImpl.cpp | 192 ++ src/io/FIo_MemoryMappedFileImpl.cpp | 207 ++ src/io/FIo_MemoryMappedFileImpl.h | 72 + src/io/FIo_MessagePortManagerImpl.cpp | 229 ++ src/io/FIo_MessagePortMessages.cpp | 26 + src/io/FIo_MessagePortProxy.cpp | 342 ++ src/io/FIo_MmcStorageManagerImpl.cpp | 206 ++ src/io/FIo_MmcStorageManagerIpcMessages.cpp | 46 + src/io/FIo_MmcStorageManagerProxy.cpp | 141 + src/io/FIo_NormalFile.cpp | 412 +++ src/io/FIo_NormalRegistry.cpp | 108 + src/io/FIo_RegistryCore.cpp | 1794 ++++++++++ src/io/FIo_RegistryImpl.cpp | 328 ++ src/io/FIo_RemoteMessagePortImpl.cpp | 184 + src/io/FIo_SecureFile.cpp | 703 ++++ src/io/FIo_SecureIoUtil.cpp | 1962 +++++++++++ src/io/FIo_SecureRegistry.cpp | 307 ++ src/io/FIo_SerialPortImpl.cpp | 184 + src/io/FIo_SerialPortImpl.h | 63 + src/io/FIo_ServerChannelImpl.cpp | 203 ++ src/io/FIo_ServiceMessage.cpp | 25 + src/io/inc/FIoIChannelEventListener.h | 115 + src/io/inc/FIo_AppServiceIpcMessages.h | 32 + src/io/inc/FIo_Channel.h | 90 + src/io/inc/FIo_ChannelCAppStub.h | 128 + src/io/inc/FIo_ChannelManager.h | 108 + src/io/inc/FIo_ChannelMessages.h | 38 + src/io/inc/FIo_ChannelService.h | 124 + src/io/inc/FIo_ChannelServiceManager.h | 62 + src/io/inc/FIo_ChannelServiceProxy.h | 107 + src/io/inc/FIo_ChannelServiceStub.h | 128 + src/io/inc/FIo_ChannelWebAppStub.h | 223 ++ src/io/inc/FIo_ClientChannelImpl.h | 79 + src/io/inc/FIo_DataControlResultSetEnumerator.h | 384 +++ src/io/inc/FIo_DataControlResultSetImpl.h | 139 + src/io/inc/FIo_DataRouter.h | 67 + src/io/inc/FIo_DatabaseImpl.h | 172 + src/io/inc/FIo_DbContextImpl.h | 208 ++ src/io/inc/FIo_DbEnumeratorImpl.h | 215 ++ src/io/inc/FIo_DbStatementImpl.h | 105 + src/io/inc/FIo_DirEntryImpl.h | 96 + src/io/inc/FIo_DirEnumeratorImpl.h | 82 + src/io/inc/FIo_DirectoryImpl.h | 78 + src/io/inc/FIo_FileAttributesImpl.h | 93 + src/io/inc/FIo_FileEventManagerImpl.h | 88 + src/io/inc/FIo_FileImpl.h | 207 ++ src/io/inc/FIo_FileUtil.h | 68 + src/io/inc/FIo_IChannelRequestEventListener.h | 50 + src/io/inc/FIo_IChannelResponseEventListener.h | 49 + src/io/inc/FIo_IChannelService.h | 69 + src/io/inc/FIo_IChannelServiceEventListener.h | 51 + src/io/inc/FIo_IChannelServiceStub.h | 63 + src/io/inc/FIo_IDataRouterEventListener.h | 54 + src/io/inc/FIo_IDbUserListener.h | 227 ++ src/io/inc/FIo_IFileCore.h | 83 + src/io/inc/FIo_IIpcClientEventListener.h | 67 + src/io/inc/FIo_IIpcServerEventListener.h | 127 + src/io/inc/FIo_IMessagePortListener.h | 48 + src/io/inc/FIo_IMmcStorageServiceEventListener.h | 55 + src/io/inc/FIo_IpcClient.h | 158 + src/io/inc/FIo_IpcCommonDataTypes.h | 37 + src/io/inc/FIo_IpcCommonParamTraits.h | 334 ++ src/io/inc/FIo_IpcMessageStart.h | 47 + src/io/inc/FIo_IpcServer.h | 243 ++ src/io/inc/FIo_LocalMessagePortImpl.h | 86 + src/io/inc/FIo_MessagePortManagerImpl.h | 97 + src/io/inc/FIo_MessagePortMessages.h | 40 + src/io/inc/FIo_MessagePortProxy.h | 125 + src/io/inc/FIo_MmcStorageManagerImpl.h | 101 + src/io/inc/FIo_MmcStorageManagerIpcMessages.h | 34 + src/io/inc/FIo_MmcStorageManagerProxy.h | 76 + src/io/inc/FIo_NormalFile.h | 93 + src/io/inc/FIo_NormalRegistry.h | 71 + src/io/inc/FIo_RegistryCore.h | 138 + src/io/inc/FIo_RegistryImpl.h | 162 + src/io/inc/FIo_RemoteMessagePortImpl.h | 83 + src/io/inc/FIo_SecureFile.h | 99 + src/io/inc/FIo_SecureIoUtil.h | 151 + src/io/inc/FIo_SecureRegistry.h | 57 + src/io/inc/FIo_ServerChannelImpl.h | 77 + src/locales/CMakeLists.txt | 50 + src/locales/FLclCalendar.cpp | 379 ++ src/locales/FLclCurrency.cpp | 148 + src/locales/FLclDateTimeFormatter.cpp | 182 + src/locales/FLclDateTimeSymbols.cpp | 239 ++ src/locales/FLclGregorianCalendar.cpp | 377 ++ src/locales/FLclLocale.cpp | 1072 ++++++ src/locales/FLclLocaleManager.cpp | 126 + src/locales/FLclNumberFormatter.cpp | 330 ++ src/locales/FLclNumberSymbols.cpp | 110 + src/locales/FLclTimeRule.cpp | 232 ++ src/locales/FLclTimeZone.cpp | 405 +++ src/locales/FLcl_CalendarImpl.cpp | 653 ++++ src/locales/FLcl_CalendarImpl.h | 137 + src/locales/FLcl_CurrencyImpl.cpp | 141 + src/locales/FLcl_CurrencyImpl.h | 44 + src/locales/FLcl_DateTimeFormatterImpl.cpp | 171 + src/locales/FLcl_DateTimeFormatterImpl.h | 172 + src/locales/FLcl_DateTimeSymbolsImpl.cpp | 610 ++++ src/locales/FLcl_DateTimeSymbolsImpl.h | 122 + src/locales/FLcl_FieldPosition.cpp | 110 + src/locales/FLcl_FieldPosition.h | 179 + src/locales/FLcl_IcuCalendarImpl.cpp | 977 ++++++ src/locales/FLcl_IcuCalendarImpl.h | 134 + src/locales/FLcl_LocaleData.cpp | 1358 ++++++++ src/locales/FLcl_LocaleData.h | 204 ++ src/locales/FLcl_LocaleImpl.cpp | 292 ++ src/locales/FLcl_LocaleImpl.h | 91 + src/locales/FLcl_LocaleManagerImpl.cpp | 510 +++ src/locales/FLcl_NumberFormatterImpl.cpp | 334 ++ src/locales/FLcl_NumberFormatterImpl.h | 159 + src/locales/FLcl_NumberSymbolsImpl.cpp | 123 + src/locales/FLcl_NumberSymbolsImpl.h | 66 + src/locales/FLcl_TimeZoneImpl.cpp | 495 +++ src/locales/FLcl_TimeZoneImpl.h | 115 + src/locales/inc/FLcl_LocaleManagerImpl.h | 59 + src/newlib-compat/CMakeLists.txt | 26 + src/newlib-compat/NewlibCompatMisc.cpp | 75 + src/newlib-compat/NewlibCompatStdio.cpp | 2102 +++++++++++ src/newlib-compat/NewlibCompatStdlib.cpp | 109 + src/newlib-compat/NewlibCompatString.cpp | 153 + src/osp-init/Osp.cpp | 48 + src/osp-string/CMakeLists.txt | 27 + src/osp-string/ar.po | 15 + src/osp-string/bg.po | 15 + src/osp-string/ca.po | 15 + src/osp-string/cs.po | 15 + src/osp-string/da.po | 15 + src/osp-string/de_DE.po | 15 + src/osp-string/el_GR.po | 15 + src/osp-string/en.po | 15 + src/osp-string/en_US.po | 15 + src/osp-string/es_ES.po | 15 + src/osp-string/fi.po | 15 + src/osp-string/fr_FR.po | 15 + src/osp-string/he.po | 15 + src/osp-string/hi.po | 15 + src/osp-string/hr.po | 15 + src/osp-string/hu.po | 15 + src/osp-string/id.po | 15 + src/osp-string/it_IT.po | 15 + src/osp-string/ja_JP.po | 15 + src/osp-string/ko_KR.po | 15 + src/osp-string/lt.po | 15 + src/osp-string/lv.po | 15 + src/osp-string/ms.po | 15 + src/osp-string/nl_NL.po | 15 + src/osp-string/no.po | 15 + src/osp-string/osp_string.xls | Bin 0 -> 14068 bytes src/osp-string/pl.po | 15 + src/osp-string/pt_PT.po | 15 + src/osp-string/ro.po | 15 + src/osp-string/ru_RU.po | 15 + src/osp-string/sk.po | 15 + src/osp-string/sl.po | 15 + src/osp-string/sr.po | 15 + src/osp-string/sv.po | 15 + src/osp-string/th.po | 15 + src/osp-string/tr_TR.po | 15 + src/osp-string/uk.po | 15 + src/osp-string/vi.po | 15 + src/osp-string/zh_CN.po | 15 + src/osp-string/zh_HK.po | 15 + src/osp-string/zh_TW.po | 15 + src/security/CMakeLists.txt | 93 + src/security/FSecAccessController.cpp | 189 + src/security/FSecAesSecureRandom.cpp | 67 + src/security/FSecDesEdeSecureRandom.cpp | 67 + src/security/FSecDesSecureRandom.cpp | 67 + src/security/FSecDhKeyParameters.cpp | 107 + src/security/FSecKeaKeyParameters.cpp | 108 + src/security/FSecKeyPair.cpp | 116 + src/security/FSecKeyPairGenerator.cpp | 413 +++ src/security/FSecPrivateKey.cpp | 74 + src/security/FSecPublicKey.cpp | 74 + src/security/FSecSecretKey.cpp | 74 + src/security/FSecSecretKeyGenerator.cpp | 146 + src/security/FSec_AccessController.cpp | 272 ++ src/security/FSec_DeviceKeyGenerator.cpp | 220 ++ src/security/FSec_GenerateParameters.cpp | 385 +++ src/security/FSec_GenerateParameters.h | 64 + src/security/FSec_PrivilegeCache.cpp | 204 ++ src/security/FSec_PrivilegeCache.h | 109 + src/security/FSec_PrivilegeInfo.cpp | 586 ++++ src/security/FSec_PrivilegeInfo.h | 191 + src/security/FSec_PrivilegeManager.cpp | 387 +++ src/security/FSec_PrivilegeManagerMessage.cpp | 46 + src/security/FSec_Prng.cpp | 329 ++ src/security/FSec_Prng.h | 140 + src/security/cert/CMakeLists.txt | 33 + src/security/cert/FSecCertX509Certificate.cpp | 457 +++ src/security/cert/FSecCertX509CertificatePath.cpp | 256 ++ .../cert/FSecCertX509CertificateSelector.cpp | 63 + src/security/cert/FSecCertX509CertificateStore.cpp | 169 + src/security/cert/FSecCert_Asn1Parser.cpp | 117 + src/security/cert/FSecCert_Asn1Parser.h | 64 + src/security/cert/FSecCert_Base64.cpp | 142 + src/security/cert/FSecCert_Base64.h | 64 + src/security/cert/FSecCert_CertChain.cpp | 993 ++++++ src/security/cert/FSecCert_CertChain.h | 108 + src/security/cert/FSecCert_CertDbManager.cpp | 2251 ++++++++++++ src/security/cert/FSecCert_CertDbManager.h | 127 + src/security/cert/FSecCert_CertDbStore.cpp | 1674 +++++++++ src/security/cert/FSecCert_CertDbStore.h | 205 ++ src/security/cert/FSecCert_CertExtension.cpp | 247 ++ src/security/cert/FSecCert_CertExtension.h | 67 + src/security/cert/FSecCert_CertFileStore.cpp | 234 ++ src/security/cert/FSecCert_CertFileStore.h | 79 + src/security/cert/FSecCert_CertList.cpp | 549 +++ src/security/cert/FSecCert_CertList.h | 169 + src/security/cert/FSecCert_CertManager.cpp | 1505 ++++++++ src/security/cert/FSecCert_CertManager.h | 99 + src/security/cert/FSecCert_CertMgrMessages.cpp | 46 + src/security/cert/FSecCert_CertMgrMessages.h | 307 ++ src/security/cert/FSecCert_CertOidDef.h | 91 + src/security/cert/FSecCert_CertPrivateKeyInfo.cpp | 309 ++ src/security/cert/FSecCert_CertPrivateKeyInfo.h | 69 + src/security/cert/FSecCert_CertService.cpp | 1995 +++++++++++ src/security/cert/FSecCert_CertServiceProxy.cpp | 562 +++ src/security/cert/FSecCert_CertServiceStub.cpp | 436 +++ src/security/cert/FSecCert_CertSignature.cpp | 253 ++ src/security/cert/FSecCert_CertSignature.h | 65 + src/security/cert/FSecCert_CertTime.cpp | 173 + src/security/cert/FSecCert_CertTime.h | 71 + src/security/cert/FSecCert_Certificate.cpp | 968 ++++++ src/security/cert/FSecCert_Certificate.h | 271 ++ .../cert/FSecCert_X509CertificateStoreImpl.cpp | 424 +++ .../cert/FSecCert_X509CertificateStoreImpl.h | 210 ++ src/security/crypto/FSecCryptoAesCipher.cpp | 314 ++ src/security/crypto/FSecCryptoCastCipher.cpp | 255 ++ src/security/crypto/FSecCryptoDesCipher.cpp | 261 ++ src/security/crypto/FSecCryptoDesEdeCipher.cpp | 259 ++ src/security/crypto/FSecCryptoDhKeyExchange.cpp | 155 + src/security/crypto/FSecCryptoKeaKeyExchange.cpp | 196 ++ src/security/crypto/FSecCryptoMd5Hash.cpp | 185 + src/security/crypto/FSecCryptoMd5Hmac.cpp | 228 ++ src/security/crypto/FSecCryptoRc2Cipher.cpp | 261 ++ src/security/crypto/FSecCryptoRc4Cipher.cpp | 223 ++ src/security/crypto/FSecCryptoRsaCipher.cpp | 235 ++ src/security/crypto/FSecCryptoRsaSignature.cpp | 217 ++ src/security/crypto/FSecCryptoSha1Hash.cpp | 184 + src/security/crypto/FSecCryptoSha1Hmac.cpp | 229 ++ src/security/crypto/FSecCryptoSha2Hash.cpp | 210 ++ src/security/crypto/FSecCryptoSha2Hmac.cpp | 253 ++ src/security/crypto/FSecCryptoSkipJackCipher.cpp | 262 ++ src/security/crypto/FSecCrypto_KeaCore.cpp | 297 ++ src/security/crypto/FSecCrypto_KeaCore.h | 61 + src/security/crypto/FSecCrypto_SkipJackCore.cpp | 373 ++ src/security/crypto/FSecCrypto_SkipJackCore.h | 58 + src/security/crypto/FSecCrypto_SkipJackModes.cpp | 200 ++ src/security/crypto/FSecCrypto_SkipJackModes.h | 49 + src/security/crypto/FSecCrypto_SymmetricCipher.cpp | 742 ++++ src/security/crypto/FSecCrypto_SymmetricCipher.h | 73 + src/security/inc/FSecCert_CertService.h | 1002 ++++++ src/security/inc/FSecCert_CertServiceProxy.h | 429 +++ src/security/inc/FSecCert_CertServiceStub.h | 119 + src/security/inc/FSecCert_CertTypes.h | 361 ++ src/security/inc/FSec_AccessControlTypes.h | 397 +++ src/security/inc/FSec_AccessController.h | 92 + src/security/inc/FSec_DeviceKeyGenerator.h | 77 + src/security/inc/FSec_PrivilegeManager.h | 115 + src/security/inc/FSec_PrivilegeManagerMessage.h | 30 + src/system/CMakeLists.txt | 71 + src/system/FSysAlarm.cpp | 122 + src/system/FSysBattery.cpp | 64 + src/system/FSysDeviceManager.cpp | 78 + src/system/FSysEnvironment.cpp | 65 + src/system/FSysPowerManager.cpp | 152 + src/system/FSysRuntimeInfo.cpp | 94 + src/system/FSysSettingInfo.cpp | 210 ++ src/system/FSysSystemInfo.cpp | 175 + src/system/FSysSystemTime.cpp | 77 + src/system/FSysVibrator.cpp | 118 + src/system/FSys_AlarmImpl.cpp | 485 +++ src/system/FSys_BatteryImpl.cpp | 113 + src/system/FSys_BatteryImpl.h | 50 + src/system/FSys_DeviceEventListenerContainer.cpp | 64 + src/system/FSys_DeviceEventListenerContainer.h | 56 + src/system/FSys_DeviceId.cpp | 263 ++ src/system/FSys_DeviceId.h | 73 + src/system/FSys_DeviceManagerEventProvider.cpp | 62 + src/system/FSys_DeviceManagerImpl.cpp | 1468 ++++++++ src/system/FSys_DeviceManagerImpl.h | 116 + src/system/FSys_EnvironmentImpl.cpp | 170 + src/system/FSys_PowerManagerImpl.cpp | 736 ++++ src/system/FSys_RuntimeInfoImpl.cpp | 748 ++++ src/system/FSys_SettingIcu.cpp | 118 + src/system/FSys_SettingIcu.h | 40 + src/system/FSys_SettingInfoImpl.cpp | 291 ++ src/system/FSys_SettingManager.cpp | 3488 +++++++++++++++++++ src/system/FSys_SettingManager.h | 121 + src/system/FSys_SystemInfoImpl.cpp | 1269 +++++++ src/system/FSys_SystemResource.cpp | 97 + src/system/FSys_SystemTimeImpl.cpp | 225 ++ src/system/FSys_Types.h | 23 + src/system/FSys_VibratorImpl.cpp | 399 +++ src/system/inc/FSys_AlarmImpl.h | 110 + src/system/inc/FSys_DeviceManagerEventProvider.h | 70 + src/system/inc/FSys_EnvironmentImpl.h | 62 + src/system/inc/FSys_IDeviceManagerEventListener.h | 48 + src/system/inc/FSys_IPowerManagerEventListener.h | 66 + src/system/inc/FSys_PowerManagerImpl.h | 92 + src/system/inc/FSys_RuntimeInfoImpl.h | 70 + src/system/inc/FSys_SettingInfoImpl.h | 75 + src/system/inc/FSys_SystemInfoImpl.h | 86 + src/system/inc/FSys_SystemResource.h | 90 + src/system/inc/FSys_SystemStrings.h | 63 + src/system/inc/FSys_SystemTimeImpl.h | 55 + src/system/inc/FSys_VibratorImpl.h | 139 + src/text/CMakeLists.txt | 42 + src/text/FTextAsciiEncoding.cpp | 149 + src/text/FTextEncoding.cpp | 164 + src/text/FTextGsmEncoding.cpp | 184 + src/text/FTextLatin1Encoding.cpp | 149 + src/text/FTextUcs2Encoding.cpp | 185 + src/text/FTextUtf8Decoder.cpp | 70 + src/text/FTextUtf8Encoder.cpp | 70 + src/text/FTextUtf8Encoding.cpp | 185 + src/text/FText_DecoderImpl.cpp | 232 ++ src/text/FText_DecoderImpl.h | 145 + src/text/FText_EncoderImpl.cpp | 216 ++ src/text/FText_EncoderImpl.h | 147 + src/text/FText_EncodingCore.cpp | 146 + src/text/FText_EncodingImpl.cpp | 693 ++++ src/text/FText_EncodingImpl.h | 495 +++ src/text/FText_GsmEncodingCore.cpp | 340 ++ src/text/FText_GsmEncodingCore.h | 60 + src/text/FText_IcuEncodingCore.cpp | 499 +++ src/text/FText_IcuEncodingCore.h | 81 + src/text/FText_Iso885916EncodingCore.cpp | 316 ++ src/text/FText_Iso885916EncodingCore.h | 60 + src/text/FText_Ucs2EncodingCore.cpp | 335 ++ src/text/FText_Ucs2EncodingCore.h | 79 + src/text/inc/FText_EncodingCore.h | 77 + 941 files changed, 240230 insertions(+) create mode 100755 CMakeLists.txt create mode 100644 LICENSE.APLv2 create mode 100644 LICENSE.Flora create mode 100644 NOTICE create mode 100644 inc/FApp.h create mode 100644 inc/FAppApp.h create mode 100644 inc/FAppAppControl.h create mode 100644 inc/FAppAppControlProviderManager.h create mode 100644 inc/FAppAppManager.h create mode 100644 inc/FAppAppRegistry.h create mode 100755 inc/FAppAppResource.h create mode 100755 inc/FAppAppSetting.h create mode 100644 inc/FAppApplication.h create mode 100644 inc/FAppDataControlProviderManager.h create mode 100644 inc/FAppIActiveAppEventListener.h create mode 100644 inc/FAppIAppCheckPointEventListener.h create mode 100644 inc/FAppIAppControlEventListener.h create mode 100644 inc/FAppIAppControlListener.h create mode 100644 inc/FAppIAppControlProviderEventListener.h create mode 100644 inc/FAppIAppControlResponseListener.h create mode 100644 inc/FAppIAppFrame.h create mode 100644 inc/FAppIAppLaunchConditionEventListener.h create mode 100644 inc/FAppIAppSettingEventListener.h create mode 100644 inc/FAppIMapDataControlProviderEventListener.h create mode 100644 inc/FAppIMapDataControlResponseListener.h create mode 100644 inc/FAppISqlDataControlProviderEventListener.h create mode 100644 inc/FAppISqlDataControlResponseListener.h create mode 100644 inc/FAppMapDataControl.h create mode 100755 inc/FAppNotificationManager.h create mode 100644 inc/FAppPkg.h create mode 100644 inc/FAppPkgIPackageInstallationEventListener.h create mode 100644 inc/FAppPkgIPackageInstallationResponseListener.h create mode 100644 inc/FAppPkgIPackageUninstallationResponseListener.h create mode 100755 inc/FAppPkgPackageAppInfo.h create mode 100755 inc/FAppPkgPackageInfo.h create mode 100755 inc/FAppPkgPackageManager.h create mode 100644 inc/FAppService.h create mode 100644 inc/FAppServiceApp.h create mode 100644 inc/FAppSqlDataControl.h create mode 100644 inc/FAppTypes.h create mode 100644 inc/FAppUiApp.h create mode 100644 inc/FBase.h create mode 100644 inc/FBaseBoolean.h create mode 100644 inc/FBaseBuffer.h create mode 100644 inc/FBaseBufferBase.h create mode 100644 inc/FBaseByteBuffer.h create mode 100644 inc/FBaseCharacter.h create mode 100644 inc/FBaseCol.h create mode 100644 inc/FBaseColAllElementsDeleter.h create mode 100644 inc/FBaseColArrayList.h create mode 100644 inc/FBaseColArrayListT.h create mode 100644 inc/FBaseColHashMap.h create mode 100644 inc/FBaseColHashMapT.h create mode 100644 inc/FBaseColIBidirectionalEnumerator.h create mode 100644 inc/FBaseColIBidirectionalEnumeratorT.h create mode 100644 inc/FBaseColICollection.h create mode 100644 inc/FBaseColICollectionT.h create mode 100644 inc/FBaseColIComparer.h create mode 100644 inc/FBaseColIComparerT.h create mode 100644 inc/FBaseColIEnumerator.h create mode 100644 inc/FBaseColIEnumeratorT.h create mode 100644 inc/FBaseColIHashCodeProvider.h create mode 100644 inc/FBaseColIHashCodeProviderT.h create mode 100644 inc/FBaseColIList.h create mode 100644 inc/FBaseColIListT.h create mode 100644 inc/FBaseColIMap.h create mode 100644 inc/FBaseColIMapEnumerator.h create mode 100644 inc/FBaseColIMapEnumeratorT.h create mode 100644 inc/FBaseColIMapT.h create mode 100644 inc/FBaseColIMultiMap.h create mode 100644 inc/FBaseColIMultiMapT.h create mode 100644 inc/FBaseColLinkedList.h create mode 100644 inc/FBaseColLinkedListT.h create mode 100644 inc/FBaseColMapEntry.h create mode 100644 inc/FBaseColMapEntryT.h create mode 100644 inc/FBaseColMultiHashMap.h create mode 100644 inc/FBaseColMultiHashMapT.h create mode 100644 inc/FBaseColQueue.h create mode 100644 inc/FBaseColQueueT.h create mode 100644 inc/FBaseColStack.h create mode 100644 inc/FBaseColStackT.h create mode 100644 inc/FBaseColTypes.h create mode 100644 inc/FBaseComparerT.h create mode 100644 inc/FBaseDataType.h create mode 100644 inc/FBaseDateTime.h create mode 100644 inc/FBaseDouble.h create mode 100644 inc/FBaseDoubleComparer.h create mode 100644 inc/FBaseDoubleMatrix.h create mode 100644 inc/FBaseDoubleMatrix3.h create mode 100644 inc/FBaseDoubleMatrix4.h create mode 100644 inc/FBaseErrorDefine.h create mode 100644 inc/FBaseErrors.h create mode 100644 inc/FBaseFloat.h create mode 100644 inc/FBaseFloatComparer.h create mode 100644 inc/FBaseFloatMatrix.h create mode 100644 inc/FBaseFloatMatrix3.h create mode 100644 inc/FBaseFloatMatrix4.h create mode 100644 inc/FBaseInt8.h create mode 100644 inc/FBaseInt8Comparer.h create mode 100644 inc/FBaseIntMatrix.h create mode 100644 inc/FBaseInteger.h create mode 100644 inc/FBaseIntegerComparer.h create mode 100644 inc/FBaseLog.h create mode 100644 inc/FBaseLong.h create mode 100644 inc/FBaseLongComparer.h create mode 100644 inc/FBaseLongLong.h create mode 100644 inc/FBaseLongLongComparer.h create mode 100644 inc/FBaseNumber.h create mode 100644 inc/FBaseObject.h create mode 100644 inc/FBaseResult.h create mode 100644 inc/FBaseRt.h create mode 100644 inc/FBaseRtEvent.h create mode 100644 inc/FBaseRtEventDrivenThread.h create mode 100644 inc/FBaseRtIEventArg.h create mode 100644 inc/FBaseRtIEventListener.h create mode 100644 inc/FBaseRtIRunnable.h create mode 100644 inc/FBaseRtITimerEventListener.h create mode 100755 inc/FBaseRtIWaitingLoopCondition.h create mode 100644 inc/FBaseRtLibrary.h create mode 100644 inc/FBaseRtMemoryManager.h create mode 100644 inc/FBaseRtMonitor.h create mode 100644 inc/FBaseRtMonitorGuard.h create mode 100644 inc/FBaseRtMutex.h create mode 100644 inc/FBaseRtMutexGuard.h create mode 100644 inc/FBaseRtSemaphore.h create mode 100644 inc/FBaseRtSemaphoreGuard.h create mode 100644 inc/FBaseRtThread.h create mode 100644 inc/FBaseRtTimer.h create mode 100644 inc/FBaseRtTypes.h create mode 100755 inc/FBaseRtWaitingLoop.h create mode 100644 inc/FBaseShort.h create mode 100644 inc/FBaseShortComparer.h create mode 100644 inc/FBaseString.h create mode 100644 inc/FBaseStringComparer.h create mode 100755 inc/FBaseSys.h create mode 100644 inc/FBaseSysLog.h create mode 100644 inc/FBaseTimeSpan.h create mode 100644 inc/FBaseTypes.h create mode 100644 inc/FBaseUtil.h create mode 100644 inc/FBaseUtilDeflator.h create mode 100644 inc/FBaseUtilFileUnzipper.h create mode 100644 inc/FBaseUtilFileZipper.h create mode 100644 inc/FBaseUtilInflator.h create mode 100644 inc/FBaseUtilLinkInfo.h create mode 100644 inc/FBaseUtilMath.h create mode 100644 inc/FBaseUtilRegularExpression.h create mode 100644 inc/FBaseUtilStringTokenizer.h create mode 100644 inc/FBaseUtilStringUtil.h create mode 100644 inc/FBaseUtilTypes.h create mode 100644 inc/FBaseUtilUri.h create mode 100644 inc/FBaseUtilUrlDecoder.h create mode 100644 inc/FBaseUtilUrlEncoder.h create mode 100644 inc/FBaseUtilZipEntry.h create mode 100644 inc/FBaseUuId.h create mode 100644 inc/FGrpBitmapCommon.h create mode 100644 inc/FIo.h create mode 100644 inc/FIoChannel.h create mode 100644 inc/FIoChannelTypes.h create mode 100644 inc/FIoClientChannel.h create mode 100644 inc/FIoDatabase.h create mode 100644 inc/FIoDbEnumerator.h create mode 100644 inc/FIoDbStatement.h create mode 100644 inc/FIoDbTypes.h create mode 100644 inc/FIoDirEntry.h create mode 100644 inc/FIoDirEnumerator.h create mode 100644 inc/FIoDirectory.h create mode 100644 inc/FIoFile.h create mode 100644 inc/FIoFileAttributes.h create mode 100644 inc/FIoFileEventManager.h create mode 100644 inc/FIoIChannelRequestEventListener.h create mode 100644 inc/FIoIChannelResponseEventListener.h create mode 100644 inc/FIoIDbEnumerator.h create mode 100644 inc/FIoIFileEventListener.h create mode 100644 inc/FIoIMessagePortListener.h create mode 100644 inc/FIoIMmcStorageFormatListener.h create mode 100644 inc/FIoIMmcStorageMountListener.h create mode 100644 inc/FIoISerialPortEventListener.h create mode 100644 inc/FIoLocalMessagePort.h create mode 100644 inc/FIoMemoryMappedFile.h create mode 100644 inc/FIoMessagePortManager.h create mode 100755 inc/FIoMmcStorageManager.h create mode 100644 inc/FIoRegistry.h create mode 100644 inc/FIoRemoteMessagePort.h create mode 100644 inc/FIoSerialPort.h create mode 100644 inc/FIoServerChannel.h create mode 100644 inc/FIoSqlStatementBuilder.h create mode 100644 inc/FLclCalendar.h create mode 100644 inc/FLclCurrency.h create mode 100644 inc/FLclDateTimeFormatter.h create mode 100644 inc/FLclDateTimeSymbols.h create mode 100644 inc/FLclGregorianCalendar.h create mode 100644 inc/FLclLocale.h create mode 100644 inc/FLclLocaleManager.h create mode 100644 inc/FLclNumberFormatter.h create mode 100644 inc/FLclNumberSymbols.h create mode 100644 inc/FLclTimeRule.h create mode 100644 inc/FLclTimeZone.h create mode 100644 inc/FLocales.h create mode 100644 inc/FOspCompat.h create mode 100644 inc/FOspConfig.h create mode 100644 inc/FSecAccessController.h create mode 100644 inc/FSecAesSecureRandom.h create mode 100644 inc/FSecCert.h create mode 100644 inc/FSecCertICertificate.h create mode 100644 inc/FSecCertICertificatePath.h create mode 100644 inc/FSecCertICertificateSelector.h create mode 100644 inc/FSecCertICertificateStore.h create mode 100644 inc/FSecCertTypes.h create mode 100644 inc/FSecCertX509Certificate.h create mode 100644 inc/FSecCertX509CertificatePath.h create mode 100644 inc/FSecCertX509CertificateSelector.h create mode 100755 inc/FSecCertX509CertificateStore.h create mode 100644 inc/FSecCrypto.h create mode 100644 inc/FSecCryptoAesCipher.h create mode 100644 inc/FSecCryptoCastCipher.h create mode 100644 inc/FSecCryptoDesCipher.h create mode 100644 inc/FSecCryptoDesEdeCipher.h create mode 100644 inc/FSecCryptoDhKeyExchange.h create mode 100644 inc/FSecCryptoIAsymmetricCipher.h create mode 100644 inc/FSecCryptoIHash.h create mode 100644 inc/FSecCryptoIHmac.h create mode 100644 inc/FSecCryptoIKeyExchange.h create mode 100644 inc/FSecCryptoISignature.h create mode 100644 inc/FSecCryptoISymmetricCipher.h create mode 100644 inc/FSecCryptoKeaKeyExchange.h create mode 100644 inc/FSecCryptoMd5Hash.h create mode 100644 inc/FSecCryptoMd5Hmac.h create mode 100644 inc/FSecCryptoRc2Cipher.h create mode 100644 inc/FSecCryptoRc4Cipher.h create mode 100644 inc/FSecCryptoRsaCipher.h create mode 100644 inc/FSecCryptoRsaSignature.h create mode 100644 inc/FSecCryptoSha1Hash.h create mode 100644 inc/FSecCryptoSha1Hmac.h create mode 100644 inc/FSecCryptoSha2Hash.h create mode 100644 inc/FSecCryptoSha2Hmac.h create mode 100644 inc/FSecCryptoSkipJackCipher.h create mode 100644 inc/FSecCryptoTypes.h create mode 100644 inc/FSecDesEdeSecureRandom.h create mode 100644 inc/FSecDesSecureRandom.h create mode 100644 inc/FSecDhKeyParameters.h create mode 100644 inc/FSecIKey.h create mode 100644 inc/FSecIKeyPairGenerator.h create mode 100644 inc/FSecIKeyParameters.h create mode 100644 inc/FSecIPrivateKey.h create mode 100644 inc/FSecIPublicKey.h create mode 100644 inc/FSecISecretKey.h create mode 100644 inc/FSecISecretKeyGenerator.h create mode 100644 inc/FSecISecureRandom.h create mode 100644 inc/FSecKeaKeyParameters.h create mode 100644 inc/FSecKeyPair.h create mode 100644 inc/FSecKeyPairGenerator.h create mode 100644 inc/FSecPrivateKey.h create mode 100644 inc/FSecPublicKey.h create mode 100644 inc/FSecSecretKey.h create mode 100644 inc/FSecSecretKeyGenerator.h create mode 100644 inc/FSecurity.h create mode 100755 inc/FSysAlarm.h create mode 100644 inc/FSysBattery.h create mode 100644 inc/FSysDeviceManager.h create mode 100644 inc/FSysEnvironment.h create mode 100644 inc/FSysIAlarmEventListener.h create mode 100644 inc/FSysIBatteryEventListener.h create mode 100644 inc/FSysIChargingEventListener.h create mode 100644 inc/FSysIDeviceEventListener.h create mode 100644 inc/FSysIRuntimeInfoGetIntAsyncResultListener.h create mode 100644 inc/FSysIRuntimeInfoGetLonglongAsyncResultListener.h create mode 100644 inc/FSysIScreenEventListener.h create mode 100644 inc/FSysISettingEventListener.h create mode 100644 inc/FSysISettingInfoSetValueAsyncResultListener.h create mode 100755 inc/FSysPowerManager.h create mode 100755 inc/FSysRuntimeInfo.h create mode 100755 inc/FSysSettingInfo.h create mode 100755 inc/FSysSystemInfo.h create mode 100644 inc/FSysSystemTime.h create mode 100755 inc/FSysVibrator.h create mode 100644 inc/FSystem.h create mode 100644 inc/FText.h create mode 100644 inc/FTextAsciiEncoding.h create mode 100644 inc/FTextDecoder.h create mode 100644 inc/FTextEncoder.h create mode 100644 inc/FTextEncoding.h create mode 100644 inc/FTextGsmEncoding.h create mode 100644 inc/FTextLatin1Encoding.h create mode 100644 inc/FTextUcs2Encoding.h create mode 100644 inc/FTextUtf8Decoder.h create mode 100644 inc/FTextUtf8Encoder.h create mode 100644 inc/FTextUtf8Encoding.h create mode 100755 inc/FXml.h create mode 100644 inc/Framework.h create mode 100644 inc/unique_ptr.h create mode 100644 inc/unique_ptr.hpp create mode 100644 osp-appfw.manifest create mode 100755 osp-appfw.pc.in create mode 100755 packaging/osp-appfw.spec create mode 100755 res/arm/usr/etc/media-capability.xml create mode 100644 res/arm/usr/etc/system-info.ini create mode 100755 res/common/etc/ld.so.conf.d/osp.conf create mode 100755 res/common/opt/usr/etc/system-log.ini create mode 100755 res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestEvent.vcs create mode 100755 res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestMemo.vnt create mode 100755 res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestTodo.vcs create mode 100755 res/common/opt/usr/share/.osp-compat/share/AppControl/ac-contact/TestContact.vcf create mode 100644 res/common/usr/etc/content-download.ini create mode 100755 res/x86/usr/etc/media-capability.xml create mode 100644 res/x86/usr/etc/system-info.ini create mode 100644 src/CMakeLists.txt create mode 100644 src/app/CMakeLists.txt create mode 100644 src/app/FAppApp.cpp create mode 100755 src/app/FAppAppControl.cpp create mode 100644 src/app/FAppAppControlProviderManager.cpp create mode 100644 src/app/FAppAppManager.cpp create mode 100644 src/app/FAppAppRegistry.cpp create mode 100644 src/app/FAppAppResource.cpp create mode 100644 src/app/FAppAppSetting.cpp create mode 100644 src/app/FAppDataControlProviderManager.cpp create mode 100644 src/app/FAppMapDataControl.cpp create mode 100644 src/app/FAppNotificationManager.cpp create mode 100644 src/app/FAppNotificationMessage.cpp create mode 100644 src/app/FAppServiceApp.cpp create mode 100644 src/app/FAppSqlDataControl.cpp create mode 100644 src/app/FApp_AppArg.cpp create mode 100644 src/app/FApp_AppControlEvent.cpp create mode 100644 src/app/FApp_AppControlEventArg.cpp create mode 100644 src/app/FApp_AppControlEventArg.h create mode 100755 src/app/FApp_AppControlImpl.cpp create mode 100755 src/app/FApp_AppControlManager.cpp create mode 100644 src/app/FApp_AppControlProviderManagerImpl.cpp create mode 100644 src/app/FApp_AppControlProviderManagerImpl.h create mode 100644 src/app/FApp_AppControlRegistry.cpp create mode 100644 src/app/FApp_AppControlRegistry.h create mode 100644 src/app/FApp_AppEntry.cpp create mode 100644 src/app/FApp_AppImpl.cpp create mode 100644 src/app/FApp_AppInfo.cpp create mode 100644 src/app/FApp_AppLaunchCondition.cpp create mode 100644 src/app/FApp_AppLaunchConditionHandlerBase.cpp create mode 100644 src/app/FApp_AppManagerEvent.cpp create mode 100755 src/app/FApp_AppManagerImpl.cpp create mode 100644 src/app/FApp_AppManagerIpcMessage.cpp create mode 100644 src/app/FApp_AppManagerProxy.cpp create mode 100644 src/app/FApp_AppMessageImpl.cpp create mode 100644 src/app/FApp_AppRegistryImpl.cpp create mode 100644 src/app/FApp_AppRegistryImpl.h create mode 100644 src/app/FApp_AppResourceImpl.cpp create mode 100644 src/app/FApp_AppResourceImpl.h create mode 100644 src/app/FApp_AppResourceString.cpp create mode 100644 src/app/FApp_AppResourceString.h create mode 100644 src/app/FApp_AppSettingImpl.cpp create mode 100644 src/app/FApp_AppSettingImpl.h create mode 100644 src/app/FApp_Aul.cpp create mode 100644 src/app/FApp_ConditionManagerIpcMessages.cpp create mode 100644 src/app/FApp_ConditionManagerProxy.cpp create mode 100644 src/app/FApp_ConditionManagerProxy.h create mode 100644 src/app/FApp_DataControlProviderManagerImpl.cpp create mode 100644 src/app/FApp_DataControlProviderManagerImpl.h create mode 100644 src/app/FApp_ImeAppImpl.cpp create mode 100644 src/app/FApp_ImeAppImpl.h create mode 100644 src/app/FApp_LongevityManager.cpp create mode 100644 src/app/FApp_LongevityManager.h create mode 100644 src/app/FApp_MapDataControlImpl.cpp create mode 100644 src/app/FApp_MapDataControlImpl.h create mode 100644 src/app/FApp_NotificationManagerImpl.cpp create mode 100644 src/app/FApp_NotificationManagerIpcMessages.cpp create mode 100644 src/app/FApp_NotificationManagerProxy.cpp create mode 100644 src/app/FApp_NotificationManagerProxy.h create mode 100644 src/app/FApp_NotificationMessageImpl.cpp create mode 100644 src/app/FApp_NotificationMessageImpl.h create mode 100644 src/app/FApp_PackageManagerIpcMessages.cpp create mode 100755 src/app/FApp_PackageManagerProxy.cpp create mode 100644 src/app/FApp_ServiceAppImpl.cpp create mode 100644 src/app/FApp_SqlDataControlImpl.cpp create mode 100644 src/app/FApp_SqlDataControlImpl.h create mode 100644 src/app/inc/FAppNotificationMessage.h create mode 100755 src/app/inc/FAppPkg_PackageAppInfoImpl.h create mode 100755 src/app/inc/FAppPkg_PackageInfoImpl.h create mode 100755 src/app/inc/FAppPkg_PackageManagerImpl.h create mode 100644 src/app/inc/FApp_AppArg.h create mode 100644 src/app/inc/FApp_AppControlEvent.h create mode 100755 src/app/inc/FApp_AppControlImpl.h create mode 100755 src/app/inc/FApp_AppControlManager.h create mode 100644 src/app/inc/FApp_AppImpl.h create mode 100644 src/app/inc/FApp_AppInfo.h create mode 100644 src/app/inc/FApp_AppLaunchCondition.h create mode 100644 src/app/inc/FApp_AppLaunchConditionHandlerBase.h create mode 100644 src/app/inc/FApp_AppManagerEvent.h create mode 100644 src/app/inc/FApp_AppManagerEventArg.h create mode 100644 src/app/inc/FApp_AppManagerEventParamTraits.h create mode 100644 src/app/inc/FApp_AppManagerImpl.h create mode 100644 src/app/inc/FApp_AppManagerIpcMessage.h create mode 100644 src/app/inc/FApp_AppManagerProxy.h create mode 100644 src/app/inc/FApp_AppMessageImpl.h create mode 100644 src/app/inc/FApp_AppUserEvent.h create mode 100644 src/app/inc/FApp_AppUserEventArg.h create mode 100644 src/app/inc/FApp_Aul.h create mode 100644 src/app/inc/FApp_ConditionManagerIpcMessages.h create mode 100644 src/app/inc/FApp_IActiveWindowEventListener.h create mode 100644 src/app/inc/FApp_IAppControlSysEventListener.h create mode 100644 src/app/inc/FApp_IAppImpl.h create mode 100644 src/app/inc/FApp_IAppLaunchConditionEventListener.h create mode 100644 src/app/inc/FApp_IAppManager.h create mode 100644 src/app/inc/FApp_IAppManagerEventListener.h create mode 100644 src/app/inc/FApp_IAppManagerServiceEventListener.h create mode 100644 src/app/inc/FApp_IAppResourceBitmap.h create mode 100644 src/app/inc/FApp_IAppUserEventListener.h create mode 100644 src/app/inc/FApp_NotificationManagerEventParamTraits.h create mode 100644 src/app/inc/FApp_NotificationManagerImpl.h create mode 100644 src/app/inc/FApp_NotificationManagerIpcMessages.h create mode 100755 src/app/inc/FApp_PackageManagerIpcMessages.h create mode 100755 src/app/inc/FApp_PackageManagerProxy.h create mode 100644 src/app/inc/FApp_RequestManagerT.h create mode 100644 src/app/inc/FApp_ServiceAppImpl.h create mode 100755 src/app/inc/FApp_TemplateUtil.h create mode 100644 src/app/inc/FApp_Types.h create mode 100755 src/app/package/FAppPkgPackageAppInfo.cpp create mode 100755 src/app/package/FAppPkgPackageInfo.cpp create mode 100755 src/app/package/FAppPkgPackageManager.cpp create mode 100755 src/app/package/FAppPkg_PackageAppInfoImpl.cpp create mode 100755 src/app/package/FAppPkg_PackageInfoImpl.cpp create mode 100755 src/app/package/FAppPkg_PackageManagerImpl.cpp create mode 100755 src/appfw/CMakeLists.txt create mode 100755 src/base/CMakeLists.txt create mode 100644 src/base/FBaseBoolean.cpp create mode 100644 src/base/FBaseBufferBase.cpp create mode 100644 src/base/FBaseByteBuffer.cpp create mode 100644 src/base/FBaseCharacter.cpp create mode 100644 src/base/FBaseDateTime.cpp create mode 100644 src/base/FBaseDouble.cpp create mode 100644 src/base/FBaseDoubleComparer.cpp create mode 100644 src/base/FBaseDoubleMatrix.cpp create mode 100644 src/base/FBaseDoubleMatrix3.cpp create mode 100644 src/base/FBaseDoubleMatrix4.cpp create mode 100644 src/base/FBaseErrors.cpp create mode 100644 src/base/FBaseFloat.cpp create mode 100644 src/base/FBaseFloatComparer.cpp create mode 100644 src/base/FBaseFloatMatrix.cpp create mode 100644 src/base/FBaseFloatMatrix3.cpp create mode 100644 src/base/FBaseFloatMatrix4.cpp create mode 100644 src/base/FBaseInit.cpp create mode 100644 src/base/FBaseInt8.cpp create mode 100644 src/base/FBaseInt8Comparer.cpp create mode 100644 src/base/FBaseIntMatrix.cpp create mode 100644 src/base/FBaseInteger.cpp create mode 100644 src/base/FBaseIntegerComparer.cpp create mode 100644 src/base/FBaseLong.cpp create mode 100644 src/base/FBaseLongComparer.cpp create mode 100644 src/base/FBaseLongLong.cpp create mode 100644 src/base/FBaseLongLongComparer.cpp create mode 100644 src/base/FBaseObject.cpp create mode 100644 src/base/FBaseResult.cpp create mode 100644 src/base/FBaseShort.cpp create mode 100644 src/base/FBaseShortComparer.cpp create mode 100644 src/base/FBaseString.cpp create mode 100644 src/base/FBaseStringComparer.cpp create mode 100644 src/base/FBaseSys.cpp create mode 100644 src/base/FBaseTimeSpan.cpp create mode 100644 src/base/FBaseTypes.cpp create mode 100644 src/base/FBaseUuId.cpp create mode 100644 src/base/FBase_CharacterImpl.cpp create mode 100644 src/base/FBase_CharacterImpl.h create mode 100644 src/base/FBase_Exception.cpp create mode 100644 src/base/FBase_NativeError.cpp create mode 100644 src/base/FBase_StringConverter.cpp create mode 100644 src/base/collection/FBaseColArrayList.cpp create mode 100644 src/base/collection/FBaseColHashMap.cpp create mode 100644 src/base/collection/FBaseColLinkedList.cpp create mode 100644 src/base/collection/FBaseColMapEntry.cpp create mode 100644 src/base/collection/FBaseColMultiHashMap.cpp create mode 100644 src/base/collection/FBaseColQueue.cpp create mode 100644 src/base/collection/FBaseColStack.cpp create mode 100644 src/base/collection/FBaseColTypes.cpp create mode 100644 src/base/inc/FBaseInternalTypes.h create mode 100644 src/base/inc/FBaseRtIEvent.h create mode 100644 src/base/inc/FBaseRtIEventFilter.h create mode 100644 src/base/inc/FBaseRt_Event.h create mode 100644 src/base/inc/FBaseRt_EventDispatcher.h create mode 100644 src/base/inc/FBaseRt_IEventListener.h create mode 100644 src/base/inc/FBaseRt_ITask.h create mode 100644 src/base/inc/FBaseRt_LibraryImpl.h create mode 100644 src/base/inc/FBaseRt_MainLoop.h create mode 100644 src/base/inc/FBaseRt_Process.h create mode 100644 src/base/inc/FBaseUtil_IcuConverter.h create mode 100644 src/base/inc/FBase_Exception.h create mode 100644 src/base/inc/FBase_HandleT.h create mode 100644 src/base/inc/FBase_Log.h create mode 100644 src/base/inc/FBase_NativeError.h create mode 100644 src/base/inc/FBase_ObjectManagerImpl.h create mode 100644 src/base/inc/FBase_ObjectManagerT.h create mode 100644 src/base/inc/FBase_StringConverter.h create mode 100644 src/base/runtime/FBaseRtEvent.cpp create mode 100644 src/base/runtime/FBaseRtEventDrivenThread.cpp create mode 100644 src/base/runtime/FBaseRtIEventListener.cpp create mode 100644 src/base/runtime/FBaseRtIRunnable.cpp create mode 100644 src/base/runtime/FBaseRtLibrary.cpp create mode 100644 src/base/runtime/FBaseRtMemoryManager.cpp create mode 100644 src/base/runtime/FBaseRtMonitor.cpp create mode 100644 src/base/runtime/FBaseRtMutex.cpp create mode 100644 src/base/runtime/FBaseRtSemaphore.cpp create mode 100644 src/base/runtime/FBaseRtThread.cpp create mode 100644 src/base/runtime/FBaseRtTimer.cpp create mode 100755 src/base/runtime/FBaseRtWaitingLoop.cpp create mode 100644 src/base/runtime/FBaseRt_Event.cpp create mode 100644 src/base/runtime/FBaseRt_EventDispatcher.cpp create mode 100644 src/base/runtime/FBaseRt_EventDrivenThreadEvent.cpp create mode 100644 src/base/runtime/FBaseRt_EventDrivenThreadEvent.h create mode 100644 src/base/runtime/FBaseRt_EventDrivenThreadEventArg.cpp create mode 100644 src/base/runtime/FBaseRt_EventDrivenThreadEventArg.h create mode 100644 src/base/runtime/FBaseRt_EventDrivenThreadImpl.cpp create mode 100644 src/base/runtime/FBaseRt_EventDrivenThreadImpl.h create mode 100644 src/base/runtime/FBaseRt_EventImpl.cpp create mode 100644 src/base/runtime/FBaseRt_EventImpl.h create mode 100644 src/base/runtime/FBaseRt_EventManager.cpp create mode 100644 src/base/runtime/FBaseRt_EventManager.h create mode 100644 src/base/runtime/FBaseRt_EventPendingOperationManager.cpp create mode 100644 src/base/runtime/FBaseRt_EventPendingOperationManager.h create mode 100644 src/base/runtime/FBaseRt_FilterInfo.h create mode 100644 src/base/runtime/FBaseRt_IEventDrivenThreadEventListener.h create mode 100644 src/base/runtime/FBaseRt_ITask.cpp create mode 100644 src/base/runtime/FBaseRt_LibraryImpl.cpp create mode 100644 src/base/runtime/FBaseRt_ListenerInfo.h create mode 100644 src/base/runtime/FBaseRt_MainLoop.cpp create mode 100644 src/base/runtime/FBaseRt_MainThreadImpl.cpp create mode 100644 src/base/runtime/FBaseRt_MainThreadImpl.h create mode 100644 src/base/runtime/FBaseRt_MonitorImpl.cpp create mode 100644 src/base/runtime/FBaseRt_MonitorImpl.h create mode 100644 src/base/runtime/FBaseRt_MutexImpl.cpp create mode 100644 src/base/runtime/FBaseRt_MutexImpl.h create mode 100644 src/base/runtime/FBaseRt_Process.cpp create mode 100644 src/base/runtime/FBaseRt_SemaphoreImpl.cpp create mode 100644 src/base/runtime/FBaseRt_SemaphoreImpl.h create mode 100644 src/base/runtime/FBaseRt_ThreadImpl.cpp create mode 100644 src/base/runtime/FBaseRt_ThreadImpl.h create mode 100644 src/base/runtime/FBaseRt_ThreadManager.cpp create mode 100644 src/base/runtime/FBaseRt_ThreadManager.h create mode 100644 src/base/runtime/FBaseRt_TimerImpl.cpp create mode 100644 src/base/runtime/FBaseRt_TimerImpl.h create mode 100755 src/base/runtime/FBaseRt_WaitingLoopImpl.cpp create mode 100755 src/base/runtime/FBaseRt_WaitingLoopImpl.h create mode 100644 src/base/runtime/FBaseRt_WorkerThreadImpl.cpp create mode 100644 src/base/runtime/FBaseRt_WorkerThreadImpl.h create mode 100644 src/base/utility/FBaseUtilDeflator.cpp create mode 100644 src/base/utility/FBaseUtilFileUnzipper.cpp create mode 100644 src/base/utility/FBaseUtilFileZipper.cpp create mode 100644 src/base/utility/FBaseUtilInflator.cpp create mode 100644 src/base/utility/FBaseUtilLinkInfo.cpp create mode 100644 src/base/utility/FBaseUtilMath.cpp create mode 100644 src/base/utility/FBaseUtilRegularExpression.cpp create mode 100644 src/base/utility/FBaseUtilStringTokenizer.cpp create mode 100644 src/base/utility/FBaseUtilStringUtil.cpp create mode 100644 src/base/utility/FBaseUtilUri.cpp create mode 100644 src/base/utility/FBaseUtilUrlDecoder.cpp create mode 100644 src/base/utility/FBaseUtilUrlEncoder.cpp create mode 100644 src/base/utility/FBaseUtilZipEntry.cpp create mode 100644 src/base/utility/FBaseUtil_FileUnzipperImpl.cpp create mode 100644 src/base/utility/FBaseUtil_FileUnzipperImpl.h create mode 100644 src/base/utility/FBaseUtil_FileZipperImpl.cpp create mode 100644 src/base/utility/FBaseUtil_FileZipperImpl.h create mode 100644 src/base/utility/FBaseUtil_IcuConverter.cpp create mode 100644 src/base/utility/FBaseUtil_RegularExpressionImpl.cpp create mode 100644 src/base/utility/FBaseUtil_RegularExpressionImpl.h create mode 100644 src/base/utility/FBaseUtil_ZipEntryInfo.h create mode 100755 src/io/CMakeLists.txt create mode 100644 src/io/FIoClientChannel.cpp create mode 100644 src/io/FIoDatabase.cpp create mode 100644 src/io/FIoDbEnumerator.cpp create mode 100644 src/io/FIoDbStatement.cpp create mode 100644 src/io/FIoDirEntry.cpp create mode 100644 src/io/FIoDirEnumerator.cpp create mode 100644 src/io/FIoDirectory.cpp create mode 100644 src/io/FIoFile.cpp create mode 100644 src/io/FIoFileAttributes.cpp create mode 100644 src/io/FIoFileEventManager.cpp create mode 100644 src/io/FIoLocalMessagePort.cpp create mode 100644 src/io/FIoMemoryMappedFile.cpp create mode 100644 src/io/FIoMessagePortManager.cpp create mode 100644 src/io/FIoMmcStorageManager.cpp create mode 100644 src/io/FIoRegistry.cpp create mode 100644 src/io/FIoRemoteMessagePort.cpp create mode 100644 src/io/FIoSerialPort.cpp create mode 100644 src/io/FIoServerChannel.cpp create mode 100644 src/io/FIoSqlStatementBuilder.cpp create mode 100644 src/io/FIo_Channel.cpp create mode 100644 src/io/FIo_ChannelCAppStub.cpp create mode 100644 src/io/FIo_ChannelManager.cpp create mode 100644 src/io/FIo_ChannelMessages.cpp create mode 100644 src/io/FIo_ChannelService.cpp create mode 100644 src/io/FIo_ChannelServiceManager.cpp create mode 100644 src/io/FIo_ChannelServiceProxy.cpp create mode 100644 src/io/FIo_ChannelServiceStub.cpp create mode 100644 src/io/FIo_ChannelWebAppStub.cpp create mode 100644 src/io/FIo_ClientChannelImpl.cpp create mode 100644 src/io/FIo_DataControlResultSetEnumerator.cpp create mode 100644 src/io/FIo_DataControlResultSetImpl.cpp create mode 100644 src/io/FIo_DataRouter.cpp create mode 100644 src/io/FIo_DatabaseImpl.cpp create mode 100644 src/io/FIo_DbContextImpl.cpp create mode 100644 src/io/FIo_DbEnumeratorImpl.cpp create mode 100644 src/io/FIo_DbStatementImpl.cpp create mode 100644 src/io/FIo_DirEntryImpl.cpp create mode 100644 src/io/FIo_DirEnumeratorImpl.cpp create mode 100644 src/io/FIo_DirectoryImpl.cpp create mode 100644 src/io/FIo_FileAttributesImpl.cpp create mode 100644 src/io/FIo_FileEventManagerImpl.cpp create mode 100644 src/io/FIo_FileImpl.cpp create mode 100644 src/io/FIo_FileUtil.cpp create mode 100644 src/io/FIo_IIpcClientEventListener.cpp create mode 100644 src/io/FIo_IIpcServerEventListener.cpp create mode 100644 src/io/FIo_IpcClient.cpp create mode 100644 src/io/FIo_IpcServer.cpp create mode 100644 src/io/FIo_LocalMessagePortImpl.cpp create mode 100644 src/io/FIo_MemoryMappedFileImpl.cpp create mode 100644 src/io/FIo_MemoryMappedFileImpl.h create mode 100644 src/io/FIo_MessagePortManagerImpl.cpp create mode 100644 src/io/FIo_MessagePortMessages.cpp create mode 100644 src/io/FIo_MessagePortProxy.cpp create mode 100644 src/io/FIo_MmcStorageManagerImpl.cpp create mode 100644 src/io/FIo_MmcStorageManagerIpcMessages.cpp create mode 100644 src/io/FIo_MmcStorageManagerProxy.cpp create mode 100644 src/io/FIo_NormalFile.cpp create mode 100644 src/io/FIo_NormalRegistry.cpp create mode 100644 src/io/FIo_RegistryCore.cpp create mode 100644 src/io/FIo_RegistryImpl.cpp create mode 100644 src/io/FIo_RemoteMessagePortImpl.cpp create mode 100644 src/io/FIo_SecureFile.cpp create mode 100644 src/io/FIo_SecureIoUtil.cpp create mode 100644 src/io/FIo_SecureRegistry.cpp create mode 100644 src/io/FIo_SerialPortImpl.cpp create mode 100644 src/io/FIo_SerialPortImpl.h create mode 100644 src/io/FIo_ServerChannelImpl.cpp create mode 100644 src/io/FIo_ServiceMessage.cpp create mode 100644 src/io/inc/FIoIChannelEventListener.h create mode 100644 src/io/inc/FIo_AppServiceIpcMessages.h create mode 100644 src/io/inc/FIo_Channel.h create mode 100644 src/io/inc/FIo_ChannelCAppStub.h create mode 100644 src/io/inc/FIo_ChannelManager.h create mode 100644 src/io/inc/FIo_ChannelMessages.h create mode 100644 src/io/inc/FIo_ChannelService.h create mode 100644 src/io/inc/FIo_ChannelServiceManager.h create mode 100644 src/io/inc/FIo_ChannelServiceProxy.h create mode 100644 src/io/inc/FIo_ChannelServiceStub.h create mode 100644 src/io/inc/FIo_ChannelWebAppStub.h create mode 100644 src/io/inc/FIo_ClientChannelImpl.h create mode 100644 src/io/inc/FIo_DataControlResultSetEnumerator.h create mode 100644 src/io/inc/FIo_DataControlResultSetImpl.h create mode 100644 src/io/inc/FIo_DataRouter.h create mode 100644 src/io/inc/FIo_DatabaseImpl.h create mode 100644 src/io/inc/FIo_DbContextImpl.h create mode 100644 src/io/inc/FIo_DbEnumeratorImpl.h create mode 100644 src/io/inc/FIo_DbStatementImpl.h create mode 100644 src/io/inc/FIo_DirEntryImpl.h create mode 100644 src/io/inc/FIo_DirEnumeratorImpl.h create mode 100644 src/io/inc/FIo_DirectoryImpl.h create mode 100644 src/io/inc/FIo_FileAttributesImpl.h create mode 100644 src/io/inc/FIo_FileEventManagerImpl.h create mode 100644 src/io/inc/FIo_FileImpl.h create mode 100644 src/io/inc/FIo_FileUtil.h create mode 100644 src/io/inc/FIo_IChannelRequestEventListener.h create mode 100644 src/io/inc/FIo_IChannelResponseEventListener.h create mode 100644 src/io/inc/FIo_IChannelService.h create mode 100644 src/io/inc/FIo_IChannelServiceEventListener.h create mode 100644 src/io/inc/FIo_IChannelServiceStub.h create mode 100644 src/io/inc/FIo_IDataRouterEventListener.h create mode 100644 src/io/inc/FIo_IDbUserListener.h create mode 100644 src/io/inc/FIo_IFileCore.h create mode 100644 src/io/inc/FIo_IIpcClientEventListener.h create mode 100644 src/io/inc/FIo_IIpcServerEventListener.h create mode 100644 src/io/inc/FIo_IMessagePortListener.h create mode 100644 src/io/inc/FIo_IMmcStorageServiceEventListener.h create mode 100644 src/io/inc/FIo_IpcClient.h create mode 100644 src/io/inc/FIo_IpcCommonDataTypes.h create mode 100644 src/io/inc/FIo_IpcCommonParamTraits.h create mode 100644 src/io/inc/FIo_IpcMessageStart.h create mode 100644 src/io/inc/FIo_IpcServer.h create mode 100644 src/io/inc/FIo_LocalMessagePortImpl.h create mode 100644 src/io/inc/FIo_MessagePortManagerImpl.h create mode 100644 src/io/inc/FIo_MessagePortMessages.h create mode 100644 src/io/inc/FIo_MessagePortProxy.h create mode 100644 src/io/inc/FIo_MmcStorageManagerImpl.h create mode 100644 src/io/inc/FIo_MmcStorageManagerIpcMessages.h create mode 100644 src/io/inc/FIo_MmcStorageManagerProxy.h create mode 100644 src/io/inc/FIo_NormalFile.h create mode 100644 src/io/inc/FIo_NormalRegistry.h create mode 100644 src/io/inc/FIo_RegistryCore.h create mode 100644 src/io/inc/FIo_RegistryImpl.h create mode 100644 src/io/inc/FIo_RemoteMessagePortImpl.h create mode 100644 src/io/inc/FIo_SecureFile.h create mode 100644 src/io/inc/FIo_SecureIoUtil.h create mode 100644 src/io/inc/FIo_SecureRegistry.h create mode 100644 src/io/inc/FIo_ServerChannelImpl.h create mode 100755 src/locales/CMakeLists.txt create mode 100644 src/locales/FLclCalendar.cpp create mode 100644 src/locales/FLclCurrency.cpp create mode 100644 src/locales/FLclDateTimeFormatter.cpp create mode 100644 src/locales/FLclDateTimeSymbols.cpp create mode 100644 src/locales/FLclGregorianCalendar.cpp create mode 100644 src/locales/FLclLocale.cpp create mode 100644 src/locales/FLclLocaleManager.cpp create mode 100644 src/locales/FLclNumberFormatter.cpp create mode 100644 src/locales/FLclNumberSymbols.cpp create mode 100644 src/locales/FLclTimeRule.cpp create mode 100644 src/locales/FLclTimeZone.cpp create mode 100644 src/locales/FLcl_CalendarImpl.cpp create mode 100644 src/locales/FLcl_CalendarImpl.h create mode 100644 src/locales/FLcl_CurrencyImpl.cpp create mode 100644 src/locales/FLcl_CurrencyImpl.h create mode 100644 src/locales/FLcl_DateTimeFormatterImpl.cpp create mode 100644 src/locales/FLcl_DateTimeFormatterImpl.h create mode 100644 src/locales/FLcl_DateTimeSymbolsImpl.cpp create mode 100644 src/locales/FLcl_DateTimeSymbolsImpl.h create mode 100644 src/locales/FLcl_FieldPosition.cpp create mode 100644 src/locales/FLcl_FieldPosition.h create mode 100644 src/locales/FLcl_IcuCalendarImpl.cpp create mode 100644 src/locales/FLcl_IcuCalendarImpl.h create mode 100644 src/locales/FLcl_LocaleData.cpp create mode 100644 src/locales/FLcl_LocaleData.h create mode 100644 src/locales/FLcl_LocaleImpl.cpp create mode 100644 src/locales/FLcl_LocaleImpl.h create mode 100644 src/locales/FLcl_LocaleManagerImpl.cpp create mode 100644 src/locales/FLcl_NumberFormatterImpl.cpp create mode 100644 src/locales/FLcl_NumberFormatterImpl.h create mode 100644 src/locales/FLcl_NumberSymbolsImpl.cpp create mode 100644 src/locales/FLcl_NumberSymbolsImpl.h create mode 100644 src/locales/FLcl_TimeZoneImpl.cpp create mode 100644 src/locales/FLcl_TimeZoneImpl.h create mode 100644 src/locales/inc/FLcl_LocaleManagerImpl.h create mode 100755 src/newlib-compat/CMakeLists.txt create mode 100644 src/newlib-compat/NewlibCompatMisc.cpp create mode 100644 src/newlib-compat/NewlibCompatStdio.cpp create mode 100644 src/newlib-compat/NewlibCompatStdlib.cpp create mode 100644 src/newlib-compat/NewlibCompatString.cpp create mode 100644 src/osp-init/Osp.cpp create mode 100755 src/osp-string/CMakeLists.txt create mode 100755 src/osp-string/ar.po create mode 100755 src/osp-string/bg.po create mode 100755 src/osp-string/ca.po create mode 100755 src/osp-string/cs.po create mode 100755 src/osp-string/da.po create mode 100755 src/osp-string/de_DE.po create mode 100755 src/osp-string/el_GR.po create mode 100755 src/osp-string/en.po create mode 100755 src/osp-string/en_US.po create mode 100755 src/osp-string/es_ES.po create mode 100755 src/osp-string/fi.po create mode 100755 src/osp-string/fr_FR.po create mode 100755 src/osp-string/he.po create mode 100755 src/osp-string/hi.po create mode 100755 src/osp-string/hr.po create mode 100755 src/osp-string/hu.po create mode 100755 src/osp-string/id.po create mode 100755 src/osp-string/it_IT.po create mode 100755 src/osp-string/ja_JP.po create mode 100755 src/osp-string/ko_KR.po create mode 100755 src/osp-string/lt.po create mode 100755 src/osp-string/lv.po create mode 100755 src/osp-string/ms.po create mode 100755 src/osp-string/nl_NL.po create mode 100755 src/osp-string/no.po create mode 100755 src/osp-string/osp_string.xls create mode 100755 src/osp-string/pl.po create mode 100755 src/osp-string/pt_PT.po create mode 100755 src/osp-string/ro.po create mode 100755 src/osp-string/ru_RU.po create mode 100755 src/osp-string/sk.po create mode 100755 src/osp-string/sl.po create mode 100755 src/osp-string/sr.po create mode 100755 src/osp-string/sv.po create mode 100755 src/osp-string/th.po create mode 100755 src/osp-string/tr_TR.po create mode 100755 src/osp-string/uk.po create mode 100755 src/osp-string/vi.po create mode 100755 src/osp-string/zh_CN.po create mode 100755 src/osp-string/zh_HK.po create mode 100755 src/osp-string/zh_TW.po create mode 100755 src/security/CMakeLists.txt create mode 100644 src/security/FSecAccessController.cpp create mode 100644 src/security/FSecAesSecureRandom.cpp create mode 100644 src/security/FSecDesEdeSecureRandom.cpp create mode 100644 src/security/FSecDesSecureRandom.cpp create mode 100644 src/security/FSecDhKeyParameters.cpp create mode 100644 src/security/FSecKeaKeyParameters.cpp create mode 100644 src/security/FSecKeyPair.cpp create mode 100644 src/security/FSecKeyPairGenerator.cpp create mode 100644 src/security/FSecPrivateKey.cpp create mode 100644 src/security/FSecPublicKey.cpp create mode 100644 src/security/FSecSecretKey.cpp create mode 100644 src/security/FSecSecretKeyGenerator.cpp create mode 100644 src/security/FSec_AccessController.cpp create mode 100644 src/security/FSec_DeviceKeyGenerator.cpp create mode 100644 src/security/FSec_GenerateParameters.cpp create mode 100644 src/security/FSec_GenerateParameters.h create mode 100644 src/security/FSec_PrivilegeCache.cpp create mode 100644 src/security/FSec_PrivilegeCache.h create mode 100644 src/security/FSec_PrivilegeInfo.cpp create mode 100644 src/security/FSec_PrivilegeInfo.h create mode 100644 src/security/FSec_PrivilegeManager.cpp create mode 100644 src/security/FSec_PrivilegeManagerMessage.cpp create mode 100644 src/security/FSec_Prng.cpp create mode 100644 src/security/FSec_Prng.h create mode 100755 src/security/cert/CMakeLists.txt create mode 100755 src/security/cert/FSecCertX509Certificate.cpp create mode 100755 src/security/cert/FSecCertX509CertificatePath.cpp create mode 100644 src/security/cert/FSecCertX509CertificateSelector.cpp create mode 100644 src/security/cert/FSecCertX509CertificateStore.cpp create mode 100644 src/security/cert/FSecCert_Asn1Parser.cpp create mode 100755 src/security/cert/FSecCert_Asn1Parser.h create mode 100755 src/security/cert/FSecCert_Base64.cpp create mode 100755 src/security/cert/FSecCert_Base64.h create mode 100644 src/security/cert/FSecCert_CertChain.cpp create mode 100755 src/security/cert/FSecCert_CertChain.h create mode 100755 src/security/cert/FSecCert_CertDbManager.cpp create mode 100755 src/security/cert/FSecCert_CertDbManager.h create mode 100755 src/security/cert/FSecCert_CertDbStore.cpp create mode 100755 src/security/cert/FSecCert_CertDbStore.h create mode 100644 src/security/cert/FSecCert_CertExtension.cpp create mode 100755 src/security/cert/FSecCert_CertExtension.h create mode 100644 src/security/cert/FSecCert_CertFileStore.cpp create mode 100755 src/security/cert/FSecCert_CertFileStore.h create mode 100755 src/security/cert/FSecCert_CertList.cpp create mode 100755 src/security/cert/FSecCert_CertList.h create mode 100644 src/security/cert/FSecCert_CertManager.cpp create mode 100755 src/security/cert/FSecCert_CertManager.h create mode 100755 src/security/cert/FSecCert_CertMgrMessages.cpp create mode 100755 src/security/cert/FSecCert_CertMgrMessages.h create mode 100755 src/security/cert/FSecCert_CertOidDef.h create mode 100644 src/security/cert/FSecCert_CertPrivateKeyInfo.cpp create mode 100755 src/security/cert/FSecCert_CertPrivateKeyInfo.h create mode 100644 src/security/cert/FSecCert_CertService.cpp create mode 100755 src/security/cert/FSecCert_CertServiceProxy.cpp create mode 100755 src/security/cert/FSecCert_CertServiceStub.cpp create mode 100755 src/security/cert/FSecCert_CertSignature.cpp create mode 100755 src/security/cert/FSecCert_CertSignature.h create mode 100755 src/security/cert/FSecCert_CertTime.cpp create mode 100755 src/security/cert/FSecCert_CertTime.h create mode 100644 src/security/cert/FSecCert_Certificate.cpp create mode 100755 src/security/cert/FSecCert_Certificate.h create mode 100755 src/security/cert/FSecCert_X509CertificateStoreImpl.cpp create mode 100755 src/security/cert/FSecCert_X509CertificateStoreImpl.h create mode 100644 src/security/crypto/FSecCryptoAesCipher.cpp create mode 100644 src/security/crypto/FSecCryptoCastCipher.cpp create mode 100644 src/security/crypto/FSecCryptoDesCipher.cpp create mode 100644 src/security/crypto/FSecCryptoDesEdeCipher.cpp create mode 100644 src/security/crypto/FSecCryptoDhKeyExchange.cpp create mode 100644 src/security/crypto/FSecCryptoKeaKeyExchange.cpp create mode 100644 src/security/crypto/FSecCryptoMd5Hash.cpp create mode 100644 src/security/crypto/FSecCryptoMd5Hmac.cpp create mode 100644 src/security/crypto/FSecCryptoRc2Cipher.cpp create mode 100644 src/security/crypto/FSecCryptoRc4Cipher.cpp create mode 100644 src/security/crypto/FSecCryptoRsaCipher.cpp create mode 100644 src/security/crypto/FSecCryptoRsaSignature.cpp create mode 100644 src/security/crypto/FSecCryptoSha1Hash.cpp create mode 100644 src/security/crypto/FSecCryptoSha1Hmac.cpp create mode 100644 src/security/crypto/FSecCryptoSha2Hash.cpp create mode 100644 src/security/crypto/FSecCryptoSha2Hmac.cpp create mode 100644 src/security/crypto/FSecCryptoSkipJackCipher.cpp create mode 100644 src/security/crypto/FSecCrypto_KeaCore.cpp create mode 100644 src/security/crypto/FSecCrypto_KeaCore.h create mode 100644 src/security/crypto/FSecCrypto_SkipJackCore.cpp create mode 100644 src/security/crypto/FSecCrypto_SkipJackCore.h create mode 100644 src/security/crypto/FSecCrypto_SkipJackModes.cpp create mode 100644 src/security/crypto/FSecCrypto_SkipJackModes.h create mode 100644 src/security/crypto/FSecCrypto_SymmetricCipher.cpp create mode 100644 src/security/crypto/FSecCrypto_SymmetricCipher.h create mode 100644 src/security/inc/FSecCert_CertService.h create mode 100644 src/security/inc/FSecCert_CertServiceProxy.h create mode 100644 src/security/inc/FSecCert_CertServiceStub.h create mode 100755 src/security/inc/FSecCert_CertTypes.h create mode 100644 src/security/inc/FSec_AccessControlTypes.h create mode 100644 src/security/inc/FSec_AccessController.h create mode 100644 src/security/inc/FSec_DeviceKeyGenerator.h create mode 100644 src/security/inc/FSec_PrivilegeManager.h create mode 100644 src/security/inc/FSec_PrivilegeManagerMessage.h create mode 100755 src/system/CMakeLists.txt create mode 100644 src/system/FSysAlarm.cpp create mode 100644 src/system/FSysBattery.cpp create mode 100644 src/system/FSysDeviceManager.cpp create mode 100644 src/system/FSysEnvironment.cpp create mode 100644 src/system/FSysPowerManager.cpp create mode 100644 src/system/FSysRuntimeInfo.cpp create mode 100644 src/system/FSysSettingInfo.cpp create mode 100644 src/system/FSysSystemInfo.cpp create mode 100644 src/system/FSysSystemTime.cpp create mode 100644 src/system/FSysVibrator.cpp create mode 100644 src/system/FSys_AlarmImpl.cpp create mode 100644 src/system/FSys_BatteryImpl.cpp create mode 100644 src/system/FSys_BatteryImpl.h create mode 100644 src/system/FSys_DeviceEventListenerContainer.cpp create mode 100644 src/system/FSys_DeviceEventListenerContainer.h create mode 100644 src/system/FSys_DeviceId.cpp create mode 100644 src/system/FSys_DeviceId.h create mode 100644 src/system/FSys_DeviceManagerEventProvider.cpp create mode 100644 src/system/FSys_DeviceManagerImpl.cpp create mode 100644 src/system/FSys_DeviceManagerImpl.h create mode 100644 src/system/FSys_EnvironmentImpl.cpp create mode 100644 src/system/FSys_PowerManagerImpl.cpp create mode 100644 src/system/FSys_RuntimeInfoImpl.cpp create mode 100644 src/system/FSys_SettingIcu.cpp create mode 100644 src/system/FSys_SettingIcu.h create mode 100644 src/system/FSys_SettingInfoImpl.cpp create mode 100644 src/system/FSys_SettingManager.cpp create mode 100644 src/system/FSys_SettingManager.h create mode 100644 src/system/FSys_SystemInfoImpl.cpp create mode 100644 src/system/FSys_SystemResource.cpp create mode 100644 src/system/FSys_SystemTimeImpl.cpp create mode 100644 src/system/FSys_Types.h create mode 100644 src/system/FSys_VibratorImpl.cpp create mode 100644 src/system/inc/FSys_AlarmImpl.h create mode 100644 src/system/inc/FSys_DeviceManagerEventProvider.h create mode 100644 src/system/inc/FSys_EnvironmentImpl.h create mode 100644 src/system/inc/FSys_IDeviceManagerEventListener.h create mode 100644 src/system/inc/FSys_IPowerManagerEventListener.h create mode 100644 src/system/inc/FSys_PowerManagerImpl.h create mode 100644 src/system/inc/FSys_RuntimeInfoImpl.h create mode 100644 src/system/inc/FSys_SettingInfoImpl.h create mode 100644 src/system/inc/FSys_SystemInfoImpl.h create mode 100644 src/system/inc/FSys_SystemResource.h create mode 100644 src/system/inc/FSys_SystemStrings.h create mode 100644 src/system/inc/FSys_SystemTimeImpl.h create mode 100644 src/system/inc/FSys_VibratorImpl.h create mode 100755 src/text/CMakeLists.txt create mode 100644 src/text/FTextAsciiEncoding.cpp create mode 100644 src/text/FTextEncoding.cpp create mode 100644 src/text/FTextGsmEncoding.cpp create mode 100644 src/text/FTextLatin1Encoding.cpp create mode 100644 src/text/FTextUcs2Encoding.cpp create mode 100644 src/text/FTextUtf8Decoder.cpp create mode 100644 src/text/FTextUtf8Encoder.cpp create mode 100644 src/text/FTextUtf8Encoding.cpp create mode 100644 src/text/FText_DecoderImpl.cpp create mode 100644 src/text/FText_DecoderImpl.h create mode 100644 src/text/FText_EncoderImpl.cpp create mode 100644 src/text/FText_EncoderImpl.h create mode 100644 src/text/FText_EncodingCore.cpp create mode 100644 src/text/FText_EncodingImpl.cpp create mode 100644 src/text/FText_EncodingImpl.h create mode 100644 src/text/FText_GsmEncodingCore.cpp create mode 100644 src/text/FText_GsmEncodingCore.h create mode 100644 src/text/FText_IcuEncodingCore.cpp create mode 100644 src/text/FText_IcuEncodingCore.h create mode 100644 src/text/FText_Iso885916EncodingCore.cpp create mode 100644 src/text/FText_Iso885916EncodingCore.h create mode 100644 src/text/FText_Ucs2EncodingCore.cpp create mode 100644 src/text/FText_Ucs2EncodingCore.h create mode 100644 src/text/inc/FText_EncodingCore.h diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100755 index 0000000..c6a3b26 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,63 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) + +SET(CMAKE_INSTALL_PREFIX /usr) +SET(PREFIX ${CMAKE_INSTALL_PREFIX}) + +## OUTPUT PATHS +SET(LIBRARY_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/cmake_build_tmp/output/osp) +SET(ROOT_DIR ${CMAKE_SOURCE_DIR}/cmake_build_tmp/output) + +## Disable build rpath +SET(CMAKE_SKIP_BUILD_RPATH TRUE) + +IF(SBS OR OBS) +ADD_DEFINITIONS("-D_EXCEPT_DEPENDENCY_") +ENDIF(SBS OR OBS) + +IF(SBS) +ADD_DEFINITIONS("-D_SBS_") +ENDIF(SBS) + +## Set Assembly Compiler +#SET(CMAKE_ASM_COMPILER "${CMAKE_C_COMPILER}") + +SET(CMAKE_ASM_COMPILER_ARG1 "${CPPFLAGS} -c") +ENABLE_LANGUAGE(ASM) + +## LIBRARY PATH +LINK_DIRECTORIES (${LIBRARY_OUTPUT_PATH}) + +ADD_SUBDIRECTORY(src) + +INSTALL(FILES ${CMAKE_SOURCE_DIR}/osp-appfw.pc DESTINATION lib/pkgconfig) +INSTALL(FILES ${CMAKE_SOURCE_DIR}/res/common/etc/ld.so.conf.d/osp.conf DESTINATION ../etc/ld.so.conf.d) + +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/cmake_build_tmp/output/target/generic/root/usr/share/locale DESTINATION share) +INSTALL(DIRECTORY ${LIBRARY_OUTPUT_PATH}/ DESTINATION lib/osp + FILES_MATCHING PATTERN "*.so*" + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ + GROUP_EXECUTE GROUP_READ + WORLD_EXECUTE WORLD_READ) +INSTALL(DIRECTORY ${LIBRARY_OUTPUT_PATH}/debug/ DESTINATION lib/osp/debug + FILES_MATCHING PATTERN "*" + PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ + GROUP_EXECUTE GROUP_READ + WORLD_EXECUTE WORLD_READ) + +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/res/common/opt/usr/share/.osp-compat/share DESTINATION ../opt/usr/share/.osp-compat) +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/res/common/opt/usr/etc DESTINATION ../opt/usr) +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/res/common/usr/etc DESTINATION ../usr) +IF("${ARCH}" MATCHES "arm") + INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/res/arm/usr/etc DESTINATION ../usr) +ELSEIF("${ARCH}" MATCHES "x86") + INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/res/x86/usr/etc DESTINATION ../usr) +ENDIF("${ARCH}" MATCHES "arm") + +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/inc/ DESTINATION include/osp FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp") +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/src/app/inc/ DESTINATION include/osp/app FILES_MATCHING PATTERN "*.h") +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/src/base/inc/ DESTINATION include/osp/base FILES_MATCHING PATTERN "*.h") +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/src/io/inc/ DESTINATION include/osp/io FILES_MATCHING PATTERN "*.h") +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/src/locales/inc/ DESTINATION include/osp/locales FILES_MATCHING PATTERN "*.h") +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/src/security/inc/ DESTINATION include/osp/security FILES_MATCHING PATTERN "*.h") +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/src/system/inc/ DESTINATION include/osp/system FILES_MATCHING PATTERN "*.h") +INSTALL(DIRECTORY ${CMAKE_SOURCE_DIR}/src/text/inc/ DESTINATION include/osp/text FILES_MATCHING PATTERN "*.h") diff --git a/LICENSE.APLv2 b/LICENSE.APLv2 new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE.APLv2 @@ -0,0 +1,202 @@ + + 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/LICENSE.Flora b/LICENSE.Flora new file mode 100644 index 0000000..9c95663 --- /dev/null +++ b/LICENSE.Flora @@ -0,0 +1,206 @@ +Flora License + +Version 1.0, May, 2012 + +http://floralicense.org/license/ + +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. + +"Tizen Certified Platform" shall mean a software platform that complies +with the standards set forth in the Compatibility Definition Document +and passes the Compatibility Test Suite as defined from time to time +by the Tizen Technical Steering Group and certified by the Tizen +Association or its designated agent. + +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 +solely as incorporated into a Tizen Certified Platform, 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 solely +as incorporated into a Tizen Certified Platform 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 pursuant to the copyright license +above, in any medium, with or without modifications, and in Source or +Object form, provided that You meet the following conditions: + + 1. You must give any other recipients of the Work or Derivative Works + a copy of this License; and + 2. You must cause any modified files to carry prominent notices stating + that You changed the files; and + 3. 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 + 4. 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 Flora License to your work + +To apply the Flora 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 Flora License, Version 1.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://floralicense.org/license/ + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT 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..b4d987f --- /dev/null +++ b/NOTICE @@ -0,0 +1,8 @@ +Copyright (c) 2012 Samsung Electronics Co., Ltd. All rights reserved. +Except as noted, this software is licensed under Apache License, Version 2. +Please, see the LICENSE.APLv2 file for Apache License, Version 2 terms and conditions. + +Several source codes may have its original copyright owner and/or +be licensed under other than Apache License, Version 2, say, Flora License, Version 1. +Please, see copyright and license comments section in the header of each file, +and the LICENSE.Flora for Flora License, Version 1 terms and conditions diff --git a/inc/FApp.h b/inc/FApp.h new file mode 100644 index 0000000..a984aea --- /dev/null +++ b/inc/FApp.h @@ -0,0 +1,82 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp.h + * @brief This is the header file for the %App namespace. + * + * This header file contains the declarations of the %App namespace. + */ + +#ifndef _FAPP_H_ +#define _FAPP_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +/** + * @namespace Tizen::App + * @brief This namespace contains classes for application development. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %App namespace contains the classes for application development, including application life-cycle management, usage of + * functionality exported by other applications through AppControl, and access to application registry and resources. Tizen + * also provides various macros for debugging purposes. + * @n + * For more information on the %App namespace features and the macros, see App Guide and Debugging Macros. + * + * The following diagram illustrates the relationships between the classes belonging to the %App namespace. + * + * @image html app_namespace_classdiagram.png + */ + +namespace Tizen { namespace App +{ + +} } // Tizen::App + +#endif // _FAPP_H_ diff --git a/inc/FAppApp.h b/inc/FAppApp.h new file mode 100644 index 0000000..2012245 --- /dev/null +++ b/inc/FAppApp.h @@ -0,0 +1,369 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppApp.h + * @brief This is the header file for the %App class. + * + * This header file contains the declarations of the %App class. + */ + +#ifndef _FAPP_APP_H_ +#define _FAPP_APP_H_ + +#include +#include + +extern "C" { +int _OSP_EXPORT_ main(int argc, char* pArgv[]); +}; + +namespace Tizen { namespace Base { namespace Collection { class IList; } } } + +namespace Tizen { namespace App +{ + +class AppRegistry; +class AppResource; + +/** + * @class App + * @brief This class is the base class of a Tizen native application. + * + * @since 2.0 + * + * The %App class is the base class of a %Tizen native application. + * A %Tizen native application must be inherited from the UiApp or ServiceApp class. These classes are inherited from the %App class. This class provides the basic features necessary to define an application. + * @n + * For more information on the class features, see App Guide, Application Life-cycle, and System Events. + * + */ +class _OSP_EXPORT_ App + : public Tizen::Base::Object +{ +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~App(void); + + /** + * Gets an instance of AppRegistry that manages the application's states and preferences. + * + * @since 2.0 + * + * @return A pointer to the AppRegistry instance, @n + * else @c null if it fails + */ + AppRegistry* GetAppRegistry(void) const; + + /** + * Gets an instance of AppResource that manages the application's resources. + * + * @since 2.0 + * + * @return A pointer to the AppResource instance, @n + * else @c null if it fails + */ + AppResource* GetAppResource(void) const; + + /** + * @if OSPDEPREC + * Gets the list of the launch arguments. @n + * For more information on the launch arguments, see Launching Other Applications. + * + * @brief [Deprecated] + * @deprecated This method is deprecated. Instead of using this method, it is recommended to use IAppControlProviderEventListener + * to acquire delivered arguments list. + * @since 2.0 + * + * @return A pointer to the list that contains the Tizen::Base::String instances of the launch arguments + * @see AppManager::LaunchApplication() + * @see AppManager::RegisterAppLaunch() + * @see AppManager::StartAppControl() + * @see AppControl::Start() + * @endif + */ + Tizen::Base::Collection::IList* GetAppArgumentListN(void) const; + + /** + * Gets the current state of the application. + * + * @since 2.0 + * + * @return The current state of the application + */ + AppState GetAppState(void) const; + + /** + * Gets the locale-independent name of the application. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompGetAppNamePage "here". + * @endif + * @return The name of the application + */ + Tizen::Base::String GetAppName(void) const; + + /** + * @page CompGetAppNamePage Compatibility for GetAppName() + * @section CompGetAppNamePageIssue Issues + * Implementing this method in OSP compatible applications has the following issues: @n + * + * -# GetAppName() returns the localized name of the application while the meaning of the application name is ambiguous. + * There are different use cases for locale-dependent name and localized name and the platform does not provide + * a method for obtaining language-neutral name. + * + * @section CompGetAppNamePageResolution Resolutions + * This issue has been resolved in Tizen. @n + * + * -# GetAppDisplayName() is introduced to acquire localized name and GetAppName() returns locale-independent application name. + */ + + /** + * Gets the display name of the application. @n + * If the system language setting is changed, the %GetAppDisplayName() method returns the localized application name. + * The display name is displayed in applications like Launcher, Setting, Task Manager, and so on. + * + * @since 2.0 + * + * @return The display name of the application + */ + Tizen::Base::String GetAppDisplayName(void) const; + + /** + * Gets the version of the application. + * + * @since 2.0 + * + * @return The version of the application + */ + Tizen::Base::String GetAppVersion(void) const; + + /** + * Gets the application ID. + * + * @since 2.0 + * + * @return The application ID + */ + AppId GetAppId(void) const; + + /** + * Gets the path of the application's root directory where the application is installed. + * + * @since 2.0 + * + * @return The application's root directory path + */ + Tizen::Base::String GetAppRootPath(void) const; + + /** + * Gets the path of the application's data directory used to store its own private data. + * + * @since 2.0 + * + * @return The application's data directory path + */ + Tizen::Base::String GetAppDataPath(void) const; + + /** + * Gets the path of the application's resource directory that ships resource files delivered with the application + * package. + * + * @since 2.0 + * + * @return The application's resource directory path + */ + Tizen::Base::String GetAppResourcePath(void) const; + + /** + * Terminates the application while it is running. @n + * The OnAppTerminating() method is called after the %Terminate() method is executed successfully. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance is in an invalid state. + */ + result Terminate(void); + + /** + * Called when the application's state changes to App::INITIALIZING. @n + * In general, most of the activities involved in initializing the application, + * including restoring the application's states, must be done in the %OnAppInitializing() method. + * If this method fails, the application's state changes to App::TERMINATED. + * + * @since 2.0 + * + * @return @c true if the method is successful, @n + * else @c false + * @param[in] appRegistry The instance of AppRegistry that manages the application's states + * @remarks Introducing the modal dialogs (for example, MessageBox) in this method is not allowed, + * because it blocks the initialization procedure. + */ + virtual bool OnAppInitializing(AppRegistry& appRegistry) = 0; + + /** + * Called when the application's initialization is finished. @n + * After the %OnAppInitialized() method succeeds, the application's state changes to App::RUNNING. + * If this method fails, the application's state changes to App::TERMINATING and the App::OnAppTerminating() method is called. + * + * @since 2.0 + * + * @return @c true if the method is successful, @n + * else @c false + */ + virtual bool OnAppInitialized(void); + + /** + * Called when the application is requested to terminate. @n + * The %OnAppWillTerminate() method returns @c false to prevent the application from getting terminated. + * If this method returns @c true, the application's state changes to App::TERMINATING and the App::OnAppTerminating() method is called. + * + * @since 2.0 + * + * @return @c true if the method is successful, @n + * else @c false + */ + virtual bool OnAppWillTerminate(void); + + /** + * Called when the application's state changes to App::TERMINATING. @n + * All the activities involved in terminating the application, including saving the application's states, must be done in the %OnAppTerminating() method. + * After this method, the application code cannot be executed. The application is destroyed subsequently. + * + * @since 2.0 + * + * @return @c true if the method is successful, @n + * else @c false + * @param[in] appRegistry The instance that manages the application's states + * @param[in] forcedTermination Set to @c true if the application is terminated by the system or another application, @n + * else @c false + */ + virtual bool OnAppTerminating(AppRegistry& appRegistry, bool forcedTermination = false) = 0; + + /** + * Called when the system detects that the system wide memory or application heap memory is insufficient to run the application any further. @n + * Resources that are not in use currently can be released using the %OnLowMemory() method. + * + * @since 2.0 + */ + virtual void OnLowMemory(void); + + /** + * Called when the battery level changes. @n + * It is recommended that the application consuming more battery power must be terminated if the battery level is Tizen::System::BATTERY_LEVEL_CRITICAL. + * + * @since 2.0 + * + * @param[in] batteryLevel The device's current battery level + */ + virtual void OnBatteryLevelChanged(Tizen::System::BatteryLevel batteryLevel); + + /** + * Sends the user event to the application itself and not to another application. + * + * @since 2.0 + * + * @return An error code + * @param[in] requestId The user defined event ID + * @param[in] pArgs A pointer to an argument list of type Tizen::Base::String + * @exception E_SUCCESS The method is successful. + * @see OnUserEventReceivedN() + */ + result SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs); + + /** + * Called asynchronously when the user event is sent by the SendUserEvent() method. @n + * The request ID and argument format for the user event can be defined as per the requirement. + * + * @since 2.0 + * + * @param[in] requestId The user defined event ID + * @param[in] pArgs A pointer to an argument list of type Tizen::Base::String + */ + virtual void OnUserEventReceivedN(RequestId requestId, Tizen::Base::Collection::IList* pArgs); + + /** + * Gets the %App instance's pointer. + * + * @since 2.0 + * + * @return A pointer to the %App instance, @n + * else @c null if it fails + */ + static App* GetInstance(void); + +protected: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + App(void); + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void App_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void App_Reserved2(void) {} + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + App(const App& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + App& operator =(const App& rhs); + +private: + class _AppImpl* __pAppImpl; +}; // App + +}} // Tizen::App + +#endif // _FAPP_APP_H_ diff --git a/inc/FAppAppControl.h b/inc/FAppAppControl.h new file mode 100644 index 0000000..a33ef3e --- /dev/null +++ b/inc/FAppAppControl.h @@ -0,0 +1,1417 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppControl.h + * @brief This is the header file for the %AppControl class. + * + * This header file contains the declarations of the %AppControl class. + */ + +#ifndef _FAPP_APPCONTROL_H_ +#define _FAPP_APPCONTROL_H_ + +#include +#include +#include + +namespace Tizen { namespace Base { namespace Collection { +class IList; +class IMap; +}}} + +namespace Tizen { namespace App +{ + +class IAppControlEventListener; +class IAppControlResponseListener; + +/** +* @if OSPDEPREC +* The Contact %AppControl ID. @n +* +* For more information, see Contact Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.contacts". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CONTACT; + +/** +* @if OSPDEPREC +* The Calendar %AppControl ID. @n +* +* For more information, see Calendar Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.calendar" or L"tizen.events". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CALENDAR; + +/** +* @if OSPDEPREC +* The Todo %AppControl ID. +* +* @brief [Deprecated] +* @deprecated This application control provider name is deprecated. +* @b OPERATION_PICK: +* @since 2.0 +* +* @remarks This constant is currently not available. +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_TODO; + +/** +* @if OSPDEPREC +* The Dial %AppControl ID. @n +* +* For more information, see Call Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.phone" with operation L"http://tizen.org/appcontrol/operation/dial". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_DIAL; + +/** +* @if OSPDEPREC +* The Call %AppControl ID. @n +* Makes a phone call. @n +* +* For more information, see Call Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.phone" with operation L"http://tizen.org/appcontrol/operation/call". +* @since 2.0 +* @privilege %http://tizen.org/privilege/systeminfo +* +* @remarks Privilege is required to use this application control. +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CALL; + + +/** +* @if OSPDEPREC +* The Message %AppControl ID. @n +* +* For more information, see Message Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.messages". +* @since 2.0 +* +* @remarks An MMS attachment may contain either an image, audio, video, vCard, vCalendar or a combination of an image, audio, vCard, and vCalendar files. @n +* MMS attachments cannot contain a video in combination with an image or an audio file. +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_MESSAGE; + +/** +* @if OSPDEPREC +* The Email %AppControl ID. @n +* +* For more information, see Email Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.email". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_EMAIL; + +/** +* @if OSPDEPREC +* The Media %AppControl ID. @n +* +* For more information, see Media Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.filemanager" or L"tizen.gallery". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_MEDIA; + +/** +* @if OSPDEPREC +* The Image %AppControl ID. @n +* +* For more information, see Image Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.imageviewer". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_IMAGE; + +/** +* @if OSPDEPREC +* The Video %AppControl ID. @n +* +* For more information, see Video Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.videoplayer". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_VIDEO; + +/** +* @if OSPDEPREC +* The Audio %AppControl ID. @n +* +* For more information, see Audio Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.musicplayer". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_AUDIO; + +/** +* @if OSPDEPREC +* The Browser %AppControl ID. @n +* +* For more information, see Browser Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.internet". +* @since 2.0 +* @privilege %http://tizen.org/privilege/web.service +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_BROWSER; + +/** +* @if OSPDEPREC +* The Camera %AppControl ID. @n +* +* For more information, see Camera Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.camera". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CAMERA; + +/** +* @if OSPDEPREC +* The Bluetooth %AppControl ID. @n +* +* For more information, see Bluetooth Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.bluetooth". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_BT; + +/** +* @if OSPDEPREC +* The Setting %AppControl ID. @n +* +* For more information, see Settings Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.settings". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_SETTINGS; + +/** +* @if OSPDEPREC +* The Contact %AppControl provider ID. @n +* +* For more information, see Contact Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.contacts". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_CONTACT; + +/** +* @if OSPDEPREC +* The Certificate Manager %AppControl provider ID. @n +* +* For more information, see Certificate Manager Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.certificatemanager". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_CERTIFICATE_MANAGER; + +/** +* @if OSPDEPREC +* The Calendar %AppControl provider ID. @n +* +* For more information, see Calendar Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.calendar" or L"tizen.events". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_CALENDAR; + +/** +* @if OSPDEPREC +* The Call %AppControl provider ID. @n +* Makes a phone call. @n +* +* For more information, see Call Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.phone". +* @since 2.0 +* @privilege %http://tizen.org/privilege/systeminfo +* +* @remarks Privilege is required to use this application control. +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_CALL; + +/** +* @if OSPDEPREC +* The Message %AppControl provider ID. @n +* +* For more information, see Message Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.messages". +* @since 2.0 +* +* @remarks An MMS attachment may contain either an image, audio, video, vCard, vCalendar or a combination of an image, audio, vCard, and vCalendar files. @n +* MMS attachments cannot contain a video in combination with an image or an audio file. @n +* From Tizen 2.0, the CC and BCC recipients are merged with the TO recipients when launching the MMS app control. +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_MESSAGE; + +/** +* @if OSPDEPREC +* The Email %AppControl provider ID. @n +* +* For more information, see Email Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.email". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_EMAIL; + +/** +* @if OSPDEPREC +* The Media %AppControl provider ID. @n +* +* For more information, see Media Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.filemanager" or L"tizen.gallery". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_MEDIA; + +/** +* @if OSPDEPREC +* The Image %AppControl provider ID. @n +* +* For more information, see Image Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.imageviewer". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_IMAGE; + +/* +* @if OSPDEPREC +* The ImageCrop application control provider ID @n +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in a future release. +* use the literal, L"tizen.imageeditor", instead of this variable. +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_IMAGE_EDITOR; + +/** +* @if OSPDEPREC +* The Video %AppControl provider ID. @n +* +* For more information, see Video Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.videoplayer". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_VIDEO; + +/** +* @if OSPDEPREC +* The Audio %AppControl provider ID. @n +* +* For more information, see Audio Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.musicplayer". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_AUDIO; + +/** +* @if OSPDEPREC +* The Browser %AppControl provider ID. @n +* +* For more information, see Browser Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.internet". +* @since 2.0 +* @privilege %http://tizen.org/privilege/web.service +* +* @remarks Privilege is required to use this application control. +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_BROWSER; + +/** +* @if OSPDEPREC +* The Camera %AppControl provider ID. @n +* +* For more information, see Camera Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.camera". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_CAMERA; + +/** +* @if OSPDEPREC +* The Bluetooth %AppControl provider ID. @n +* +* For more information, see Bluetooth Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.bluetooth". +* @since 2.0 +* +* @remarks Bluetooth functionality cannot be tested on the Emulator. +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_BLUETOOTH; + +/** +* @if OSPDEPREC +* The Setting %AppControl provider ID. @n +* +* For more information, see Settings Application Control. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"tizen.settings". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_SETTINGS; + +// +// The AllShare application control provider ID. @n +// +// @since 2.0 +// @visibility internal +// @privlevel user +// @privilege ALLSHARE +// +// @remarks Privilege is required to use this application control. @n +// 'path' is the main key of the all keys. Other keys' value are the extra information for the main key's value. @n +// 'path' and 'type' values must be filled mandatorily and the others are optional. @n +// More than one content can be added if the 'path' key and value item is added in the input list. +// +// @li Input dataList : @n +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +//
Keyvaluedescription
pathPath, such as /Media/Images/sampleImage.jpg or http://localhost:8080/sampleVideo.mp4 or http://mycompany.com/sampleImage.jpg"This is the main key. @n Path to the media file to be shared.
typeimage|audio|videoType of the media file.
titleTitle, such as MyTitleTitle of the media file.
durationDuration in milliseconds, such as 60000 (60secs)Duration of the media file.
bitrateBit rate in kilo-bits per second, such as 192Bit rate of the media file.
widthWidth in pixel, such as 640Width of the media file
heightHeight in pixel, such as 480Height of the media file
sizeSize in bytes, such as 512000 (500KB)Size of the media file.
mimeTypeMime type, such as audio/mp3Mime type of the media file.
artistArtist, such as TizenSingerArtist of media file.
albumTitleAlbum title, such as TizenAlbumAlbum title of media file.
+// +// @n +// @li Example code for AllShare: @n +// @code +// void +// MyAppClass::AllShareAppControlSample(void) +// { +// ArrayList* pDataList = new ArrayList(); +// +// pDataList->Construct(); +// pDataList->Add(*new String(L"path:/mycompany.com/sampleImage.jpg")); +// pDataList->Add(*new String(L"type:image")); +// pDataList->Add(*new String(L"title:MyImage")); +// pDataList->Add(*new String(L"width:640")); +// pDataList->Add(*new String(L"height:480")); +// pDataList->Add(*new String(L"size:51200")); +// pDataList->Add(*new String(L"mimeType:image/jpg")); +// pDataList->Add(*new String(L"path:http://mycompany.com/sampleVideo.mp4")); +// pDataList->Add(*new String(L"type:video")); +// pDataList->Add(*new String(L"title:MyVideo")); +// pDataList->Add(*new String(L"duration:600000")); +// pDataList->Add(*new String(L"width:320")); +// pDataList->Add(*new String(L"height:240")); +// pDataList->Add(*new String(L"size:2097152")); +// pDataList->Add(*new String(L"mimeType:video/mp4")); +// pDataList->Add(*new String(L"path:http://mycompany.com/sampleAudio.mp3")); +// pDataList->Add(*new String(L"type:audio")); +// pDataList->Add(*new String(L"title:MyAudio")); +// pDataList->Add(*new String(L"duration:200000")); +// pDataList->Add(*new String(L"size:3565158")); +// pDataList->Add(*new String(L"mimeType:audio/mp3")); +// pDataList->Add(*new String(L"artist:TizenSinger")); +// pDataList->Add(*new String(L"albumTitle:TizenAlbum")); +// +// AppControl* pAc = AppManager::FindAppControlN(APPCONTROL_PROVIDER_ALLSHARE, APPCONTROL_OPERATION_SHARE); +// if (pAc) +// { +// pAc->Start(pDataList, null); +// delete pAc; +// } +// +// pDataList->RemoveAll(true); +// delete pDataList; +// } +// +// @endcode +// +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_PROVIDER_ALLSHARE; + +/** +* @if OSPDEPREC +* Operation Add. @n +* Adds an application item. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/add". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String OPERATION_ADD; + +/** +* @if OSPDEPREC +* Operation Pick. @n +* Picks some application item(s). +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/pick". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String OPERATION_PICK; + +/** +* @if OSPDEPREC +* Operation Edit. @n +* Edits an application item. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/edit". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String OPERATION_EDIT; + +/** +* @if OSPDEPREC +* Operation View. @n +* Shows the application content. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/view". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String OPERATION_VIEW; + +/** +* @if OSPDEPREC +* Operation Play. @n +* Plays the application content. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/view". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String OPERATION_PLAY; + +/** +* @if OSPDEPREC +* Operation Default. @n +* +* Uses the default operation specific to the application control. +* An application control can export its functionality using an operation. If the application control exports only one operation, OPERATION_DEFAULT can act as an alias for the operation. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/main". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String OPERATION_DEFAULT; + +/** +* @if OSPDEPREC +* Operation Capture. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/createcontent". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String OPERATION_CAPTURE; + + +/** +* @if OSPDEPREC +* Operation Add. @n +* Adds an application item. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/add". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_ADD; + +/** +* @if OSPDEPREC +* Operation Call. @n +* Makes a call to the specified phone number. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/call". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_CALL; + +/** +* @if OSPDEPREC +* Operation Capture. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/createcontent". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_CAPTURE; + +/** +* @if OSPDEPREC +* Operation Compose. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/compose". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_COMPOSE; + +/** +* @if OSPDEPREC +* Operation Configure Settings. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/configure". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_CONFIGURE; + +/** +* @if OSPDEPREC +* Operation Default. @n +* +* Uses the default operation specific to the application control. +* An application control can export its functionality using an operation. If the application control exports only one operation, OPERATION_DEFAULT can act as an alias for the operation. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/main". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_DEFAULT; + +/** +* @if OSPDEPREC +* Operation Dial. @n +* Launches the dial screen for making a call. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/dial". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_DIAL; + +/** +* @if OSPDEPREC +* Operation Edit. @n +* Edits an application item. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/edit". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_EDIT; + +/** +* @if OSPDEPREC +* Operation Main. @n +* +* All the application exports the implicit %AppControl with %APPCONTROL_OPERATION_MAIN operation. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/main". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_MAIN; + +/** +* @if OSPDEPREC +* Operation Pick. @n +* Picks some application item(s). +* +* @brief [Deprecated] +* @deprecated This variable is providyed only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/pick". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_PICK; + +/** +* @if OSPDEPREC +* Operation Play. @n +* Plays the application content. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/view". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_PLAY; + +/** +* @if OSPDEPREC +* Operation Record. @n +* Records the content. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/createcontent". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_RECORD; + +/** +* @if OSPDEPREC +* Operation Share. @n +* Shares the contents. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/share". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_SHARE; + +/** +* @if OSPDEPREC +* Operation View. @n +* Shows the application content. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/view". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_VIEW; + +/** +* @if OSPDEPREC +* Operation Crop. @n +* Shows image with the crop rectangle. +* +* @brief [Deprecated] +* @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. +* Instead of this variable, use the literal, L"http://tizen.org/appcontrol/operation/crop". +* @since 2.0 +* @endif +*/ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_OPERATION_CROP; + +/** + * @if OSPDEPREC + * Not specified category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_NONE; + +/** + * @if OSPDEPREC + * The audio category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_AUDIO; + +/** + * @if OSPDEPREC + * The browser category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_BROWSER; + +/** + * @if OSPDEPREC + * The Bluetooth device category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_BLUETOOTH; + +/** + * @if OSPDEPREC + * The calendar category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_CALENDAR; + +/** + * @if OSPDEPREC + * The certificate category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_CERTIFICATE; + +/** + * @if OSPDEPREC + * The contact category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_CONTACT; + +/** + * @if OSPDEPREC + * The document category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_DOCUMENT; + +/** + * @if OSPDEPREC + * The email category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_EMAIL; + +/** + * @if OSPDEPREC + * The media category. @n + * Specifying App::APPCONTROL_CATEGORY_MEDIA is equivalent to specifying all the App::APPCONTROL_CATEGORY_AUDIO, + * App::APPCONTROL_CATEGORY_IMAGE, and App::APPCONTROL_CATEGORY_VIDEO categories. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_MEDIA; + +/** + * @if OSPDEPREC + * The MMS category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_MMS; + +/** + * @if OSPDEPREC + * The image category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_IMAGE; + +/** + * @if OSPDEPREC + * The security category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_SECURITY; + +/** + * @if OSPDEPREC + * The SMS category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_SMS; + +/** + * @if OSPDEPREC + * The settings category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_SETTINGS; + +/** + * @if OSPDEPREC + * The video call category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_VIDEO_CALL; + +/** + * @if OSPDEPREC + * The voice call category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_VOICE_CALL; + +/** + * @if OSPDEPREC + * The video category. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_VIDEO; + +/** + * @if OSPDEPREC + * The complete URI handling category corresponding to AppManager::StartAppControl(). + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_CATEGORY_URI; + +/** + * @if OSPDEPREC + * The %AppControl operation is successful. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_RESULT_SUCCEEDED; + +/** + * @if OSPDEPREC + * The %AppControl operation has failed. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_RESULT_FAILED; + +/** + * @if OSPDEPREC + * The %AppControl operation is canceled. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_RESULT_CANCELED; + +/** + * @if OSPDEPREC + * The %AppControl is terminated without sending the result. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APPCONTROL_RESULT_TERMINATED; + +/** +* @class AppControl +* @brief This class represents the application control behavior. +* @since 2.0 +* +* @final This class is not intended for extension. +* +* The %AppControl class represents the application control behavior that provides a standard mechanism for using specific operations exported by other applications. +* +* For more information on the class features, see Application Controls. +* +* @see Tizen::App::AppManager +* +* The following example demonstrates how to use the %AppControl class. +* +* +* @code +* +* using namespace Tizen::Base::Collection; +* using namespace Tizen::App; +* +* void +* MyAppClass::AppControlCallSample(void) +* { +* HashMap extraData; +* String telKey = L"tel"; +* String telVal = L"1234567890"; +* String typeKey = L"type"; +* String typeVal = L"voice"; +* +* extraData.Construct(); +* extraData.Add(&telKey, &telVal); +* extraData.Add(&typeKey, &typeVal); +* +* AppControl* pAc = AppManager::FindAppControlN(L"tizen.phone", L"http://tizen.org/appcontrol/operation/call"); +* if(pAc) +* { +* pAc->Start(null, null, &extraData, null); +* delete pAc; +* } +* } +* +* @endcode +*/ +class _OSP_EXPORT_ AppControl + : public Tizen::Base::Object +{ +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~AppControl(void); + + /** + * @if OSPDEPREC + * Starts the resolved application control. @n + * Once the application starts, it goes to the background and the target + * application control is displayed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because IAppControlEventListener method is deprecated and replaced by + * IAppControlResponseListener due to lack of argument capability. @n + * Instead of using this method, use Start(). + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] pDataList The data list to deliver to the resolved application control @n + * The maximum size of the list is 4096 bytes. + * @param[in] pListener The application control callback listener @n + * Some application controls need to get the callback result by implementing the IAppControlEventListener interface. + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The size of @c pDataList has exceeded the maximum limit. + * @exception E_OBJ_NOT_FOUND The target application control resource is not found. + * @exception E_IN_PROGRESS The application control is in progress: @n + * - The application has already started an %AppControl. @n + * - The target application has already started. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks If the IAppControlEventListener instance (@c pListener) needs to get the + * callback result for an application control, it must be valid till + * IAppControlEventListener::OnAppControlCompleted() is invoked. + * For example, a form object listener must not be deleted before the + * system invokes %IAppControlEventListener::OnAppControlCompleted(). + * @see AppManager::FindAppControlN() + * @see AppManager::FindAppControlsN() + * @endif + */ + result Start(const Tizen::Base::Collection::IList* pDataList, IAppControlEventListener* pListener); + + /** + * Starts the found application control. @n + * Once the found application starts, the calling application goes to the background and the found + * application is displayed. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] pUriData A pointer to the URI data + * @param[in] pDataType A pointer to the MIME type (RFC 2046) data + * @param[in] pExtraData A pointer to an argument map of key and value pair where the key is of type String and the value is of type String to deliver to the resolved application @n + * The maximum size is 16 kilo bytes. + * @param[in] pListener The application control callback listener @n + * Some application need to get the result by implementing the IAppControlResponseListener interface. + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The size of @c pExtraData has exceeded the maximum limit. + * @exception E_OBJ_NOT_FOUND The target application control is not found. + * @exception E_IN_PROGRESS The application control is in progress: @n + * - The application has already started an %AppControl. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks If the calling application needs to get some result for application control, + * it must be valid till IAppControlResponseListener::OnAppControlCompleteResponseReceived() is invoked. + * For example, a form object listener must not be deleted before the + * system invokes %IAppControlResponseListener::OnAppControlCompleteResponseReceived(). + * @see AppManager::FindAppControlN() + * @see AppManager::FindAppControlsN() + */ + result Start(const Tizen::Base::String* pUriData, const Tizen::Base::String* pDataType, const Tizen::Base::Collection::IMap* pExtraData, IAppControlResponseListener* pListener); + + /** + * Finds the matching application control with given operation ID, URI pattern, data type, and category and + * starts the found one. @n + * If there are more than one application controls found, then the selection is shown for user and the one that the user selects is started. + * When the found application control is started, the URI pattern, MIME type, and extra data is delivered using IAppControlProviderEventListener. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] operationId The operation ID + * @param[in] pUriPattern A URI pattern which is used for application control resolution and is delivered as the argument + * @param[in] pDataType The MIME type (RFC 2046) or file extension @n + * The '.' prefix must be used when specifying the file extension. + * @param[in] pCategory The application control category + * @param[in] pExtraData A pointer to an argument map of key and value pair where the key is of type String and the value is of type String to deliver to the resolved application @n + * The maximum size is 16 kilo bytes. + * @param[in] pListener A listener that gets notified + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The size of @c pDataList has exceeded the maximum limit. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see IAppControlResponseListener + */ + static result FindAndStart(const Tizen::Base::String& operationId, const Tizen::Base::String* pUriPattern, const Tizen::Base::String* pDataType, const Tizen::Base::String* pCategory, const Tizen::Base::Collection::IMap* pExtraData, IAppControlResponseListener* pListener); + + /** + * Stops the event listener from receiving the application control result. + * + * @since 2.0 + * + * @param[in] pListener The listener to stop receiving the application control result + */ + static void StopAppControlResponseListener(IAppControlResponseListener* pListener); + + /** + * Gets the name of the application that provides the features represented by this %AppControl instance. + * + * @since 2.0 + * + * @return The name of the application providing this %AppControl instance + */ + Tizen::Base::String GetAppName(void) const; + + /** + * Gets the associated application ID. + * + * @since 2.0 + * + * @return The application ID + */ + AppId GetAppId(void) const; + + /** + * @if OSPDEPREC + * Gets the associated application control provider ID. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because application ID replaced the role of provider ID. @n + * Instead of using this method, use GetAppId(). + * @since 2.0 + * + * @return The application control provider ID + * @endif + */ + Tizen::Base::String GetAppControlProviderId(void) const; + + /** + * Gets the associated operation ID. + * + * @since 2.0 + * + * @return The operation ID + */ + Tizen::Base::String GetOperationId(void) const; + + /** + * Gets the associated application control categories. + * + * @since 2.0 + * + * @return A pointer to the list of application control categories, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetCategoryListN(void) const; + + + /** + * Stops the activated application control. @n + * The %Stop() method works only with the following %AppControls provided by the platform: + * App::APPCONTROL_PROVIDER_AUDIO, App::APPCONTROL_PROVIDER_BLUETOOTH, @n + * App::APPCONTROL_PROVIDER_CALENDAR, App::APPCONTROL_PROVIDER_CAMERA, @n + * App::APPCONTROL_PROVIDER_CERTIFICATE_MANAGER, App::APPCONTROL_PROVIDER_CONTACT, @n + * App::APPCONTROL_PROVIDER_EMAIL, App::APPCONTROL_PROVIDER_IMAGE, @n + * App::APPCONTROL_PROVIDER_MEDIA, App::APPCONTROL_PROVIDER_MESSAGE, @n + * and App::APPCONTROL_PROVIDER_VIDEO. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The application control is not permitted to call this method. + * @remarks This method is asynchronous. + */ + result Stop(void); + +private: + /** + * This constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + AppControl(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppControl(const AppControl& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppControl& operator =(const AppControl& rhs); + + +private: + class _AppControlImpl * __pAppControlImpl; + + friend class _AppControlImpl; +}; // AppControl + +} } // Tizen::App + +#endif // _FAPP_APPCONTROL_H_ diff --git a/inc/FAppAppControlProviderManager.h b/inc/FAppAppControlProviderManager.h new file mode 100644 index 0000000..2b90dc8 --- /dev/null +++ b/inc/FAppAppControlProviderManager.h @@ -0,0 +1,171 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppControlProviderManager.h + * @brief This is the header file for the %AppControlProviderManager class. + * + * This header file contains the declarations of the %AppControlProviderManager class. + */ + +#ifndef _FAPP_APPCONTROL_PROVIDER_MANAGER_H_ +#define _FAPP_APPCONTROL_PROVIDER_MANAGER_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection { +class IList; +class IMap; +}}} + +namespace Tizen { namespace App +{ + +class IAppControlProviderEventListener; + +/** + * @class AppControlProviderManager + * @brief This class manages the AppControl provider. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %AppControlProviderManager class manages the AppControl provider. @n + * The %AppControl provider registers or unregisters the IAppControlProviderEventListener listener + * for providing the %AppControl functionality, looks up for the delivered %AppControl request information, + * and sends the %AppControl result back to the calling application. @n + * + * The request ID is used to identify each %AppControl request and can be acquired using + * IAppControlProviderEventListener::OnAppControlRequestReceived(). + * + */ +class _OSP_EXPORT_ AppControlProviderManager + : public Tizen::Base::Object +{ +public: + /** + * Gets the application control provider manager instance. + * + * @since 2.0 + * + * @return A pointer to the %AppControlProviderManager instance if it succeeds, @n + * else @c null + */ + static AppControlProviderManager* GetInstance(void); + + /** + * Sets the application control provider listener to the application control provider manager. @n + * The listener gets notified when the application control request is received from other applications. + * To unset the listener, pass a @c null value to the listener parameter. @n + * + * If the application does not set the listener using %SetAppControlProviderEventListener(), + * then the application is launched or moves to the foreground without invoking any listener + * for the application request from another application. + * + * @since 2.0 + * + * @return An error code + * @param[in] pListener The application control provider listener + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_INVALID_OPERATION The listener must be set for the valid %App class. + * @exception E_SYSTEM A system error has occurred. + * @remarks If the application is newly launched with the AppControl request, then %SetAppControlProviderEventListener() must + * be set before invoking IAppControlProviderEventListener::OnAppControlRequestReceived(). + * For valid %AppControl request handling, %SetAppControlProviderEventListener() must be called within + * App::OnAppInitializing(). + */ + result SetAppControlProviderEventListener(IAppControlProviderEventListener* pListener); + + /** + * Gets the application ID for the application control request. + * + * @since 2.0 + * + * @return The application ID @n + * If an error occurs, an empty string is returned. + * @param[in] reqId The requestID + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The application control request is not found. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + AppId GetClientAppId(RequestId reqId) const; + + /** + * Sends the result list for the application control request. @n + * The client receives the result by implementing IAppControlResponseListener::OnAppControlCompleteResponseReceived(). + * + * @since 2.0 + * + * @return An error code + * @param[in] reqId The application control request ID + * @param[in] appControlResult The application control result + * @param[in] pExtraData A pointer to an extra argument map of key and value pair where the key is of type String and the value is of type String + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The application control request is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result SendAppControlResult(RequestId reqId, AppCtrlResult appControlResult, const Tizen::Base::Collection::IMap* pExtraData); + +private: + /** + * This default constructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + AppControlProviderManager(void); + + /** + * This destructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + virtual ~AppControlProviderManager(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppControlProviderManager(const AppControlProviderManager& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppControlProviderManager& operator=(const AppControlProviderManager& rhs); + + +private: + class _AppControlProviderManagerImpl* __pAppControlProviderManagerImpl; + + friend class _AppControlProviderManagerImpl; +}; + +}; +}; // Tizen::App + +#endif //_FAPP_APPCONTROL_PROVIDER_MANAGER_H_ + diff --git a/inc/FAppAppManager.h b/inc/FAppAppManager.h new file mode 100644 index 0000000..f5b1509 --- /dev/null +++ b/inc/FAppAppManager.h @@ -0,0 +1,762 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppManager.h + * @brief This is the header file for the %AppManager class. + * + * This header file contains the declarations of the %AppManager class. + */ + +#ifndef _FAPP_APP_MANAGER_H_ +#define _FAPP_APP_MANAGER_H_ + +#include +#include + +namespace Tizen { namespace Base { +class ByteBuffer; +namespace Collection { +class IList; +class IMap; +} +}} + +namespace Tizen { namespace App +{ + +class IAppControlEventListener; +class IAppControlListener; +class IAppControlResponseListener; +class IAppCheckpointEventListener; +class IAppLaunchConditionEventListener; +class IActiveAppEventListener; +class AppControl; +class SqlDataControl; +class MapDataControl; + +/** + * @class AppManager + * @brief This class manages all the applications. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %AppManager class manages all the applications. + * The application manager supports normal and conditional application launch, and application control search and launch. + * It looks up the specific application control from the application control registry and creates an application control instance. + * @n + * For more information on the class features, see Launching Other Applications, Registering a Launch Condition, and Application Controls. + */ +class _OSP_EXPORT_ AppManager + : public Tizen::Base::Object +{ +public: + /** + * @enum LaunchOption + * + * Defines the launch options. + * + * @since 2.0 + */ + enum LaunchOption + { + LAUNCH_OPTION_DEFAULT /**< The launch option: default */ + }; + + /** + * Finds the application control that the caller wants to start. @n + * It resolves the matched application control with the delivered application ID and operation ID. + * + * @since 2.0 + * + * @return A pointer to the newly created AppControl instance if a matched %AppControl is found, @n + * else @c null + * @param[in] appId The application ID + * @param[in] operationId The operation ID + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_SYSTEM A system error has occurred. @n + * Either the file operation or the DB operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks %Tizen platform defines platform-defined alias for application ID and this aliased application ID + * can be used to find the AppControl. For more information, see + * here. + * + * The following example demonstrates how to use the %FindAppControlN() method to find the application control. + * + * @code + * ArrayList dataList(SingleObjectDeleter); + * dataList.Construct(); + * dataList.Add(new String(L"tel:1234567900")); + * dataList.Add(new String(L"type:voice")); + * + * AppControl* pAc = AppManager::FindAppControlN(L"tizen.phone", L"http://tizen.org/appcontrol/operation/call"); + * pAc->Start(&dataList, null); + * @endcode + */ + static AppControl* FindAppControlN(const AppId& appId, const Tizen::Base::String& operationId); + + /** + * Finds a list of AppControl instances that matches the specified operation ID, category, + * data type, and URI pattern. + * + * @since 2.0 + * + * @return A pointer to the list of the AppControl instances that matches the specified operation ID, category, URI, and data type, @n + * else @c null if it fails + * @param[in] pOperationId The operation ID + * @param[in] pCategory The application category + * @param[in] pDataType The MIME type (RFC 2046) or file extension @n + * The '.' prefix must be used when specifying the file extension. + * @param[in] pUriPattern The URI pattern + * + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG At least one of the specified @c pOperationId, @c pCategory, @c pDataType, or @c pUriScheme must not be @c null. + * @exception E_INVALID_FORMAT The specified URI scheme is invalid (RFC 2396). + * @exception E_UNSUPPORTED_FORMAT The specified file extension for @c pDataType is not supported. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_SYSTEM A system error has occurred. @n + * Either the file operation or the DB operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks For the delivered launch arguments, see App::GetAppArgumentListN(). + */ + static Tizen::Base::Collection::IList* FindAppControlsN(const Tizen::Base::String* pOperationId, const Tizen::Base::String* pCategory, const Tizen::Base::String* pDataType, const Tizen::Base::String* pUriPattern); + + /** + * @if OSPDEPREC + * Starts the application control if there is only one application control that matches the specified URI, operation ID, and data type. @n + * If there are more than one application controls, the one that the user selects is started. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because IAppControlListener is deprecated and replaced by IAppControlResponselistener. + * Instead of using this method, use AppControl::FindAndStart(). + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] uriData The URI that has a maximum size of @c 1024 bytes + * @param[in] pOperationId The operation ID + * @param[in] pDataType The MIME type (RFC 2046) or file extension @n + * The '.' prefix must be used for the @c dataType when specifying the file extension. + * @param[in] pListener A listener that gets notified when the resolved application control has started + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The size of @c uri has exceeded the maximum limit. + * @exception E_UNSUPPORTED_FORMAT The specified file extension for @c pDataType is not supported. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_IN_PROGRESS The target application control is in progress. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * + * @see App::GetAppArgumentListN() + * @see FindAppControlN() + * @see FindAppControlsN() + * @see AppControl::Start() + * + * The following example demonstrates how to use the %StartAppControl() method. + * @code + * String operationId = L"http://tizen.org/appcontrol/operation/call"; + * StartAppControl(L"tel:1234567890", &operationId, null, null); + * @endcode + * @endif + */ + static result StartAppControl(const Tizen::Base::String& uriData, const Tizen::Base::String* pOperationId, const Tizen::Base::String* pDataType, IAppControlListener* pListener); + + /** + * @if OSPDEPREC + * Starts the application control if there is only one application control that matches the specified operation ID, category, URI, and data type. @n + * If there are more than one application controls, the one that the user selects is started. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because IAppControlListener is deprecated and replaced by IAppControlResponselistener. + * Instead of using this method, use AppControl::FindAndStart(). + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] pOperationId The operation ID + * @param[in] pCategory The application control category + * @param[in] pDataType The MIME type (RFC 2046) or file extension @n + * The '.' prefix must be used when specifying the file extension. + * @param[in] pUriPattern A URI pattern which is used for application control resolution and delivered as the argument + * @param[in] pDataList The data list that is delivered to the resolved application control @n + * It has a maximum size of @c 1024 bytes. + * @param[in] pListener A listener that gets notified when the resolved application control has started + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG At least one of the specified @c pOperationId, @c pCategory, @c pDataType, or @c pUri must not be @c null. + * @exception E_MAX_EXCEEDED The size of @c pDataList has exceeded the maximum limit. + * @exception E_UNSUPPORTED_FORMAT The specified file extension for @c pDataType is not supported. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_IN_PROGRESS The target application control is in progress. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks For delivered launch arguments, see App::GetAppArgumentListN(). + * @see App::GetAppArgumentListN() + * @see FindAppControlsN() + * @see AppControl::Start() + * @endif + */ + static result StartAppControl(const Tizen::Base::String* pOperationId, const Tizen::Base::String* pCategory, const Tizen::Base::String* pDataType, const Tizen::Base::String* pUriPattern, const Tizen::Base::Collection::IList* pDataList, IAppControlListener* pListener); + + /** + * Gets the SQL-type data control that the caller wants to use. @n + * It resolves the matching data control with the specified data control provider ID. + * + * @since 2.0 + * + * @return A pointer to the SqlDataControl instance if a matching data control is found, @n + * else @c null + * @param[in] providerId The provider ID + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The data control specified with the @c providerId is not found. + * @exception E_ILLEGAL_ACCESS The access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static SqlDataControl* GetSqlDataControlN(const Tizen::Base::String& providerId); + + /** + * Gets the MAP-type data control that the caller wants to use. @n + * It resolves the matching data control with the specified data control provider ID. + * + * @since 2.0 + * + * @return A pointer to the MapDataControl instance if a matching data control is found, @n + * else @c null + * @param[in] providerId The provider ID + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The data control specified with the @c providerId is not found. + * @exception E_ILLEGAL_ACCESS The access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static MapDataControl* GetMapDataControlN(const Tizen::Base::String& providerId); + + /** + * Gets the path of the read-only shared directory exported by an other application specified with an application ID. + * + * @since 2.0 + * + * @return The other application's shared directory path, @n + * else an empty string if an exception occurs + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The expected shared directory cannot be found + * because the application specified with @c appId cannot be installed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Tizen::Base::String GetAppSharedPath(const AppId& appId); + + /** + * Gets the application manager instance. + * + * @since 2.0 + * + * @return A pointer to the %AppManager instance, @n + * else @c null if it fails + */ + static AppManager* GetInstance(void); + + /** + * @if OSPDEPREC + * Launches the default application with given @c appId. @n + * The launch arguments are given as App::OnUserEventReceivedN() or can be obtained by + * invoking App::GetAppArgumentListN(), especially within App::OnAppInitializing(). + * + * @brief [Deprecated] + * @deprecated This method is deprecated because sending argument with %LaunchApplication() is not recommended. @n + * Instead of using this method, use %LaunchApplication() without launch arguments or AppControl::Start(). + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] appId The application's ID to execute + * @param[in] pArguments A pointer to the list of string arguments that has a maximum size of @c 1024 bytes + * @param[in] option The launch option (currently only AppManager::LAUNCH_OPTION_DEFAULT is available) + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_INVALID_ARG The specified @c appId is empty. + * @exception E_OBJ_NOT_FOUND The target application is not installed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_MAX_EXCEEDED The size of @c appId or @c pArguments has exceeded the maximum limit. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result LaunchApplication(const AppId& appId, const Tizen::Base::Collection::IList* pArguments, LaunchOption option = LAUNCH_OPTION_DEFAULT); + + /** + * Launches the default application with given @c appId. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] appId The application's ID to execute + * @param[in] option The launch option (currently only AppManager::LAUNCH_OPTION_DEFAULT is available) + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_APP_NOT_INSTALLED The target application is not installed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + result LaunchApplication(const AppId& appId, LaunchOption option = LAUNCH_OPTION_DEFAULT); + + /** + * @if VISPARTNER + * Terminates an application. + * + * @since 2.0 + * @visibility partner + * @privilege %http://tizen.org/privilege/application.kill + * + * @return An error code + * @param[in] appId The application's ID to execute + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OBJ_NOT_FOUND The application is not installed or not running. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result TerminateApplication(const AppId& appId); + + /** + * Checks whether an application is running. + * + * @since 2.0 + * + * @return @c true if the application is running, @n + * else @c false + * @param[in] appId The installed application ID + */ + bool IsRunning(const AppId& appId) const; + + /** + * Gets a list of running applications at the time of invocation. + * + * @since 2.0 + * + * @return A pointer to the running state application list (AppId), @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetRunningAppListN(void) const; + + /** + * Registers an application with a specific condition and launches it if the condition is met. @n + * If the requested application is already running, the application is notified through IAppLaunchConditionEventListener::OnAppLaunchConditionMetN(). + * The launch arguments are given as input parameters to %IAppLaunchConditionEventListener::OnAppLaunchConditionMetN(). + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] condition The launch condition for the application @n + * The condition has L"Key='value'" format and is case sensitive. To use single or double quotes in the condition values, prefix them with a slash (\' or \"). @n + * For more information on the condition formats, see Registering a Launch Condition. + * + + + + + +
Condition FormatMeaning
L"DateTime='mm/dd/yyyy hh:mm:ss'"The specified condition is the local due time.
L"DueTime='mm/dd/yyyy hh:mm:ss' LaunchPeriod='mm'"The specific condition is the time period after due time.
L"Serial='command'"The specified condition is a serial + communication input command.
L"NFC='command'"The specified condition is a Near Field Communication (NFC) tag that has the NFC Data Exchange Format (NDEF) data. +
@n + + * + * @param[in] pArguments A list of string arguments that has a maximum size of @c 1024 bytes @n + * The parameter can also contain @c null. @n + * For more information on the arguments, see Launching Other Applications. + * @param[in] option The launch option (currently only AppManager::LAUNCH_OPTION_DEFAULT is available) + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The launch condition is empty or too long (Maximum 400 bytes). + * @exception E_INVALID_FORMAT The specified condition format is invalid. + * @exception E_INVALID_CONDITION The specified condition format is valid but the condition has at least one or more invalid values. + * @exception E_OBJ_ALREADY_EXIST The specified @c condition is already registered by a different application. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_MAX_EXCEEDED The size of @c pArguments has exceeded the maximum limit. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * + * @remarks When the registered application is about to be launched, the registered launch condition and arguments are given as parameters to IAppLaunchConditionEventListener::OnAppLaunchConditionMetN(). + * @remarks The newly introduced launch condition does not work on the previous SDK version and the E_INVALID_CONDITION exception is returned. + * @remarks Registering the same launch condition overwrites the previous launch argument without throwing an exception. + * @remarks The launch period requires more consideration because an inappropriate short period value may lead + * to an adverse effect on the device battery. + * @remarks For the NFC launch condition, the detected NDEF message can be acquired using the @c pExtraData parameter of %IAppLaunchConditionEventListener::OnAppLaunchConditionMetN() method. + * @see UnregisterAppLaunch() + * @see IsAppLaunchRegistered() + * @see LaunchApplication() + * @see Tizen::Base::DateTime::ToString() + * @see Tizen::Io::SerialPort + * + * The following example demonstrates how to use the %RegisterAppLaunch() method. + * + * @code + * + * DateTime time; + * SystemTime::GetCurrentTime(TIME_MODE_WALL, time); + * time.AddMinutes(1); + * + * String cond; + * cond.Format(70, L"DueTime='%S' LaunchPeriod='60'", time.ToString().GetPointer()); + * + * // Registers a periodic condition that fires every 60 minutes starting after one minute + * AppManager::GetInstance()->RegisterAppLaunch(cond, null, AppManager::LAUNCH_OPTION_DEFAULT) + * + * @endcode + */ + result RegisterAppLaunch(const Tizen::Base::String& condition, const Tizen::Base::Collection::IList* pArguments, LaunchOption option); + + /** + * Unregisters the previously registered launch condition. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks E_SUCCESS An error occurs when there is no registered launch condition. + * @see RegisterAppLaunch() + * @see IsAppLaunchRegistered() + */ + result UnregisterAppLaunch(void); + + /** + * Unregisters the specified launch condition. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/application.launch + * + * @return An error code + * @param[in] condition The launch condition for the application + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified launch condition is not found. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @see RegisterAppLaunch() + * @see IsAppLaunchRegistered() + */ + result UnregisterAppLaunch(const Tizen::Base::String& condition); + + /** + * Checks whether a launch condition is registered for the application. + * + * @since 2.0 + * + * @return @c true if a condition is already registered to the application invoking this method, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see RegisterAppLaunch() + * @see UnregisterAppLaunch() + */ + bool IsAppLaunchRegistered(void) const; + + /** + * @if VISPARTNER + * Registers the specified application with a specific condition and launches it if the condition is met. @n + * If the requested application is already running, the application is notified through IAppLaunchConditionEventListener::OnAppLaunchConditionMetN(). + * The launch arguments are given as input parameters to %IAppLaunchConditionEventListener::OnAppLaunchConditionMetN(). + * + * @since 2.0 + * @visibility partner + * @privilege %http://tizen.org/privilege/appmanager.launch + * + * @return An error code + * @param[in] appId The ID of the application registered for launch + * @param[in] condition The launch condition for the application @n + * The condition has L"Key='value'" format and is case sensitive. To use single or double quotes in the condition values, prefix them with a slash (\' or \"). @n + * For more information on the condition formats, see Registering a Launch Condition. + * + + + + + +
Condition FormatMeaning
L"DateTime='mm/dd/yyyy hh:mm:ss'"The specified condition is the local due time.
L"DueTime='mm/dd/yyyy hh:mm:ss' LaunchPeriod='mm'"The specific condition is the time period after due time.
L"Serial='command'"The specified condition is a serial + communication input command.
L"NFC='command'"The specified condition is a Near Field Communication (NFC) tag that has the NFC Data Exchange Format (NDEF) data. +
@n + + * + * @param[in] pArguments A list of string arguments that has a maximum size of @c 1024 bytes @n + * The parameter can also contain @c null. @n + * For more information on the arguments, see Launching Other Applications. + * @param[in] option The launch option (currently only AppManager::LAUNCH_OPTION_DEFAULT is available) + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_ARG The launch condition is empty or too long (Maximum 400 bytes). + * @exception E_INVALID_FORMAT The specified condition format is invalid. + * @exception E_INVALID_CONDITION The specified condition format is valid but the condition has at least one or more invalid values. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_MAX_EXCEEDED The size of @c pArguments has exceeded the maximum limit. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * + * @remarks When the registered application is about to be launched, the registered launch condition and arguments are given as parameters to IAppLaunchConditionEventListener::OnAppLaunchConditionMetN(). + * @remarks The newly introduced launch condition does not work on the previous SDK version and the E_INVALID_CONDITION exception is returned. + * @remarks Registering the same launch condition overwrites the previous launch argument without throwing an exception. + * @remarks The launch period requires more consideration because an inappropriate short period value may lead + * to an adverse effect on the device battery. + * @remarks For the NFC launch condition, the detected NDEF message can be acquired using the @c pExtraData parameter of %IAppLaunchConditionEventListener::OnAppLaunchConditionMetN() method. + * @see UnregisterAppLaunch() + * @see IsAppLaunchRegistered() + * @see LaunchApplication() + * @see IAppLaunchConditionEventListener::OnAppLaunchConditionMetN() + * @see Tizen::Base::DateTime::ToString() + * @see Tizen::Io::SerialPort + * @endif + */ + result RegisterAppLaunch(const AppId& appId, const Tizen::Base::String& condition, const Tizen::Base::Collection::IList* pArguments, LaunchOption option); + + /** + * @if VISPARTNER + * Unregisters the launch condition. + * + * @since 2.0 + * @visibility partner + * @privilege %http://tizen.org/privilege/appmanager.launch + * + * @return An error code + * @param[in] appId The application ID + * @param[in] pCondition The launch condition to unregister @n + * If the parameter contains @c null, all the conditions are unregistered. + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_OBJ_NOT_FOUND The specified launch condition is not found. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * + * @see RegisterAppLaunch() + * @see IsAppLaunchRegistered() + * @endif + */ + result UnregisterAppLaunch(const AppId& appId, const Tizen::Base::String* pCondition); + + /** + * @if VISPARTNER + * Checks whether a previously registered launch condition is present for the specified application. + * + * @since 2.0 + * @visibility partner + * @privilege %http://tizen.org/privilege/appmanager.launch + * + * @return @c true if a condition is already registered to the specified application with the specified condition, @n + * else @c false + * @param[in] appId The application ID + * @param[in] pCondition The launch condition to register for the specified @c appId @n + * If the parameter contains @c null, the method checks for any registered launch condition for the specified @c appId. + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see RegisterAppLaunch() + * @see UnregisterAppLaunch() + * @endif + */ + bool IsAppLaunchRegistered(const AppId& appId, const Tizen::Base::String* pCondition = null) const; + + /** + * Sets a checkpoint event listener. @n + * The listener gets notified when a checkpoint event is fired. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The listener to receive the checkpoint event + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_ALREADY_EXIST The listener is already set. + * @exception E_SYSTEM A system error has occurred. + * @see IAppCheckpointEventListener + * + */ + result SetCheckpointEventListener(IAppCheckpointEventListener& listener); + + /** + * @if OSPDEPREC + * Sends the result list for the application control request. @n + * The client can get the result list by implementing IAppControlEventListener::OnAppControlCompleted(). + * + * @brief [Deprecated] + * @deprecated This method is deprecated because a new method has been added. @n + * Instead of using this method, use AppControlProviderManager::SendAppControlResult(). + * @since 2.0 + * + * @return An error code + * @param[in] appControlRequestId The application control request ID @n + * The application control request ID is given as an argument for + * App::GetAppArgumentListN() or App::OnUserEventReceivedN(). + * @param[in] pResultList The list of the result strings of the application control + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The application control request is not found. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @see IAppControlEventListener + * @endif + */ + static result SendAppControlResult(const Tizen::Base::String& appControlRequestId, const Tizen::Base::Collection::IList* pResultList); + + /** + * Sets an IAppLaunchConditionEventListener to the %AppManager. @n + * The listener gets notified when the application is launched by the registered condition. + * + * @since 2.0 + * + * @param[in] pListener The event listener @n + * To unset the listener, pass a @c null value to the listener parameter. + * @remarks If the application is newly launched by the condition, then %SetAppLaunchConditionEventListener() must + * be set within App::OnAppInitializing(). + * If the application does not set the listener using %SetAppLaunchConditionEventListener(), + * then the application is launched without invoking any listener for the condition. + * @see RegisterAppLaunch() + */ + void SetAppLaunchConditionEventListener(IAppLaunchConditionEventListener* pListener); + + /** + * @if VISPARTNER + * Adds an IActiveAppEventListener to the %AppManager. @n + * The listener gets notified when the active application is changed. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/appusage + * + * @return An error code + * @param[in] listener The event listener + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_ALREADY_EXIST The listener is already added. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks Active application is the top most window with focus. + * @see GetActiveApp() + * @see RemoveActiveAppEventListener() + * @see IActiveAppEventListener + * @endif + */ + result AddActiveAppEventListener(IActiveAppEventListener& listener); + + /** + * @if VISPARTNER + * Removes an IActiveAppEventListener from the %AppManager. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/appusage + * + * @return An error code + * @param[in] listener The event listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c listener is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @see GetActiveApp() + * @see AddActiveAppEventListener() + * @see IActiveAppEventListener + * @endif + */ + result RemoveActiveAppEventListener(IActiveAppEventListener& listener); + + /** + * @if VISPARTNER + * Gets the current active application AppId. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/appusage + * + * @return An error code + * @param[out] appId The AppId of the active application + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks Active application is the top most window with focus. + * @see AddActiveAppEventListener() + * @see RemoveActiveAppEventListener() + * @endif + */ + result GetActiveApp(AppId& appId); + +private: + /** + * This default constructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + AppManager(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppManager(const AppManager& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppManager& operator =(const AppManager& rhs); + + /** + * Constructs the instance of this class. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(void); + + /** + * This destructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + virtual ~AppManager(void); + +private: + class _AppManagerImpl* __pAppManagerImpl; + + friend class _AppManagerImpl; +}; // AppManager + +}} // Tizen::App + +#endif // _FAPP_APP_MANAGER_H_ + diff --git a/inc/FAppAppRegistry.h b/inc/FAppAppRegistry.h new file mode 100644 index 0000000..9936a78 --- /dev/null +++ b/inc/FAppAppRegistry.h @@ -0,0 +1,354 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppRegistry.h + * @brief This is the header file for the %AppRegistry class. + * + * This header file contains the declarations of the %AppRegistry class. + */ + +#ifndef _FAPP_APP_REGISTRY_H_ +#define _FAPP_APP_REGISTRY_H_ + +#include +#include + +namespace Tizen { namespace App +{ + +/** + * @class AppRegistry + * @brief This class manages an application's preferences. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %AppRegistry class lets an application to save or restore its preferences. + * An instance of this class can be obtained through the Application class. + * Also, since an application's state is generally restored in the App::OnAppInitializing() method and saved in the App::OnAppTerminating() method, an instance of this class is passed as an argument when these methods are invoked. + * @n + * For more information on the class features, see App Guide. + * + * The following example demonstrates how to use the %AppRegistry class. + * + * @code + * + * void + * MyAppClass::AppRegistryCallSample(void) + * { + * AppRegistry* pAppRegistry = GetAppRegistry(); + * String countKey("BasicAppRunCount"); + * String nameKey("BasicAppUserName"); + * String temperatureKey("BasicAppTemperature"); + * String name("BasicApp"); + * double temperature = 32.5; + * result r = E_SUCCESS; + * int count = 0; + * + * r = pAppRegistry->Get(nameKey, name); + * if (r == E_KEY_NOT_FOUND) + * { + * pAppRegistry->Add(nameKey, name); + * } + * + * r = pAppRegistry->Get(countKey, count); + * if (r == E_KEY_NOT_FOUND) + * { + * pAppRegistry->Add(countKey, count); + * } + * + * r = pAppRegistry->Get(temperatureKey, temperature); + * if (r == E_KEY_NOT_FOUND) + * { + * pAppRegistry->Add(temperatureKey, temperature); + * } + * + * r = pAppRegistry->Save(); + * if (IsFailed(r)) + * { + * // Failed to save data to registry + * } + * + * // Displays the retrieved data + * AppLog("AppRegistry Name value [%ls]", name.GetPointer()); + * AppLog("AppRegistry count [%d]", count); + * AppLog("AppRegistry temperature value [%f]", temperature); + * + * // Updates the state of the application variables + * count++; + * name.Append(count); + * temperature++; + * + * // Saves the app registry + * r = pAppRegistry->Set(nameKey, name); + * if (IsFailed(r)) + * { + * // Error condition + * } + * + * r = pAppRegistry->Set(countKey, count); + * if (IsFailed(r)) + * { + * // Error condition + * } + * + * r = pAppRegistry->Set(temperatureKey, temperature); + * if (IsFailed(r)) + * { + * // Error condition + * } + * + * r = pAppRegistry->Save(); + * if (IsFailed(r)) + * { + * // Failed to save data to registry + * } + * + * // Retrieves the saved content + * pAppRegistry->Get(nameKey, name); + * pAppRegistry->Get(countKey, count); + * pAppRegistry->Get(temperatureKey, temperature); + * + * AppLog("AppRegistry Name value [%ls]", name.GetPointer()); + * AppLog("AppRegistry count [%d]", count); + * AppLog("AppRegistry temperature value [%f]", temperature); + * + * return; + * } + * @endcode + * + **/ +class _OSP_EXPORT_ AppRegistry + : public Tizen::Base::Object +{ +public: + /** + * Adds a string value along with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value A string value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_ALREADY_EXIST The key has already been used in the application preferences. + * @remarks In order to save the value in the persistent storage, the AppRegistry::Save() method must be called. + */ + result Add(const Tizen::Base::String& key, const Tizen::Base::String& value); + + /** + * Adds an integer value along with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value An integer value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_ALREADY_EXIST The key has already been used in the application preferences. + * @remarks In order to save the value in the persistent storage, the AppRegistry::Save() method must be called. + */ + result Add(const Tizen::Base::String& key, int value); + + /** + * Adds a floating point value along with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value A floating point value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_ALREADY_EXIST The key has already been used in the application preferences. + * @remarks In order to save the value in the persistent storage, the AppRegistry::Save() method must be called. + */ + result Add(const Tizen::Base::String& key, double value); + + /** + * Sets a string value associated with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value A string value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_NOT_FOUND The specified @c key is not used in the application preferences. + * @remarks In order to save the value in the persistent storage, the AppRegistry::Save() method must be called. + */ + result Set(const Tizen::Base::String& key, const Tizen::Base::String& value); + + /** + * Sets an integer value associated with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value An integer value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_NOT_FOUND The specified @c key is not used in the application preferences. + * @remarks In order to save the value in the persistent storage, the AppRegistry::Save() method must be called. + */ + result Set(const Tizen::Base::String& key, int value); + + /** + * Sets a floating point value associated with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value A floating point value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_NOT_FOUND The specified @c key is not used in the application preferences. + * @remarks In order to save the value in the persistent storage, the AppRegistry::Save() method must be called. + */ + result Set(const Tizen::Base::String& key, double value); + + /** + * Saves the values temporarily in the persistent storage. @n + * The %Save() method is invoked internally when the instance of this class is deleted. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + */ + result Save(void); + + /** + * Removes a preference associated with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key of the value to remove + * @exception E_SUCCESS The method is successful. + * @exception E_KEY_NOT_FOUND The specified @c key is not used in the application preferences. + */ + result Remove(const Tizen::Base::String& key); + + /** + * Gets a string value associated with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key of the value to retrieve + * @param[out] value A string value to retrieve + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_NOT_FOUND The specified @c key is not used in the application preferences. + */ + result Get(const Tizen::Base::String& key, Tizen::Base::String& value) const; + + /** + * Gets an integer value associated with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key of the value to retrieve + * @param[out] value An integer value to retrieve + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_NOT_FOUND The specified @c key is not used in the application preferences. + */ + result Get(const Tizen::Base::String& key, int& value) const; + + /** + * Gets a floating point value associated with the specified @c key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key of the value to retrieve + * @param[out] value A floating point value to retrieve + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is empty or is string with '\0' and '\n'. + * @exception E_KEY_NOT_FOUND The specified @c key is not used in the application preferences. + */ + result Get(const Tizen::Base::String& key, double& value) const; + + /** + * Gets the %AppRegistry instance pointer. + * + * @since 2.0 + * + * @return A pointer to the %AppRegistry instance, @n + * else @c null if it fails + */ + static AppRegistry* GetInstance(void); + +private: + /** + * This default constructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + AppRegistry(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppRegistry(const AppRegistry& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppRegistry& operator =(const AppRegistry& rhs); + + /** + * This destructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + virtual ~AppRegistry(void); + + /** + * Initializes this instance. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(void); + +private: + class _AppRegistryImpl* __pAppRegistryImpl; + + friend class _AppRegistryImpl; +}; // AppRegistry + +} } // Tizen::App + +#endif // _FAPP_APP_REGISTRY_H_ diff --git a/inc/FAppAppResource.h b/inc/FAppAppResource.h new file mode 100755 index 0000000..cbd70b7 --- /dev/null +++ b/inc/FAppAppResource.h @@ -0,0 +1,272 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppResource.h + * @brief This is the header file for the %AppResource class. + * + * This header file contains the declarations of the %AppResource class. + */ + +#ifndef _FAPP_APP_RESOURCE_H_ +#define _FAPP_APP_RESOURCE_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Locales { class Locale; } } +namespace Tizen { namespace Graphics { class Bitmap; } } + +namespace Tizen { namespace App +{ + +/** +* @class AppResource +* @brief This class provides convenient methods to load application resources at run time. +* +* @since 2.0 +* +* @final This class is not intended for extension. +* +* The %AppResource class provides convenient methods to load application resources at run time: @n +* - Use AppResource::GetString() to get handle and display localized strings. +* - Use AppResource::GetBitmapN() to obtain a bitmap image that matches the screen density. +* - If the matching image does not exist, the image of the baseline density folder, ScreenDensity-High is used. +* +* The instance of this class can be obtained through App::GetAppResource(). +* The following example demonstrates how to use the %AppResource class to get strings. +* +* @code +#include + +using namespace Tizen::App; + +void +MyClass::StringResourceSample(void) +{ + String hello; + AppResource *pAppResource = App::GetInstance()->GetAppResource(); + if (pAppResource) + { + pAppResource->GetString(L"IDS_HELLO", hello); + } +} +* @endcode +* +* +* +* The following example demonstrates how to use the %AppResource class to retrieve bitmaps. +* @code +#include + +using namespace Tizen::App; +using namespace Tizen::Graphics; + +void +MyClass::BitmapResourceSample(void) +{ + AppResource *pAppResource = App::GetInstance()->GetAppResource(); + Bitmap* pBitmap = null; + + if (pAppResource) + { + pBitmap = pAppResource->GetBitmapN(L"Tizen.png", BITMAP_PIXEL_FORMAT_ARGB8888); + } +} +* @endcode +*/ + +class _OSP_EXPORT_ AppResource + : public Tizen::Base::Object +{ +public: + /** + * Gets the string at the specified resource ID. + * + * @since 2.0 + * + * @return An error code + * @param[in] resourceId The resource ID of type Tizen::Base::String that describes the resource + * @param[out] loadedString The string obtained from the loaded application resource + * @exception E_SUCCESS The method is successful. + * @exception E_FAILURE The argument passed is not found. + * @exception E_INVALID_ARG The argument passed to a method contains an invalid resource ID. + */ + result GetString(const Tizen::Base::String& resourceId, Tizen::Base::String& loadedString) const; + + /** + * Gets the bitmap at the specified path. @n + * The %GetBitmapN() method interprets the given resource path and reads the best matching image file for the current device resolution. @n + * To load the bitmap image from a file, give the name of the file as the input parameter and not the file path (For example: "img.png"). + * Then, the system will first look for the image file in the folder specific to the current device resolution, such as + * '720x1280' and if the file does not exist, it will then search the folder that corresponds to the current screen density, + * such as 'screen-density-xhigh'. After searching the density folder, all the other density folders are searched in the order high to low. + * Currently supported image formats are: JPEG, GIF, PNG, BMP, TIFF, and WBMP. + * + * @since 2.0 + * + * @return A pointer to the Bitmap instance generated from the specified file + * @param[in] imagePath The relative path starting from the directory @b "res/screen-density-XXX/" or @b "res/AxB", @n + * where A and B represent the screen width and height of the supported device models, respectively. + * @param[in] pixelFormat The pixel format of the resulting bitmap + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_UNSUPPORTED_FORMAT The image file format or specified pixel format is not supported. + * @exception E_FILE_NOT_FOUND The specified file cannot be found. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks There is a high probability for an occurrence of an out-of-memory exception. If possible, check whether the exception is E_OUT_OF_MEMORY or not. For more information on how to handle the out-of-memory exception, refer here. + */ + Tizen::Graphics::Bitmap* GetBitmapN(const Tizen::Base::String& imagePath, Tizen::Graphics::BitmapPixelFormat pixelFormat) const; + + /** + * Gets the bitmap at the specified path. @n + * The %GetBitmapN() method interprets the given resource path and reads the best matching image file for the current device resolution. @n + * To load the bitmap image from a file, give the name of the file as the input parameter and not the file path (For example: "img.png"). + * Then, the system will first look for the image file in the folder specific to the current device resolution, such as + * '720x1280' and if the file does not exist, it will then search the folder that corresponds to the current screen density, + * such as 'screen-density-xhigh'. After searching the density folder, all the other density folders are searched in the order high to low. + * Currently supported image formats are: JPEG, GIF, PNG, BMP, TIFF, and WBMP. + * + * In this method, the system decides the proper pixel format. + * Currently supported image formats are: JPEG, GIF, PNG, BMP, TIFF, and WBMP. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Graphics::Bitmap instance generated from the specified file + * @param[in] imagePath The relative path starting from the density directory @b "res/screen-density-XXX/" or @b "res/AxB", @n + * where A and B represent the width and height of the screen of the supported device models, respectively + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_UNSUPPORTED_FORMAT The image file format is not supported. + * @exception E_FILE_NOT_FOUND The specified file cannot be found. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks There is a high probability for an occurrence of an out-of-memory exception. If possible, check whether the exception is E_OUT_OF_MEMORY or not. For more information on how to handle the out-of-memory exception, refer here. + */ + Tizen::Graphics::Bitmap* GetBitmapN(const Tizen::Base::String& imagePath) const; + + /** + * Gets the %AppResource instance pointer. + * + * @since 2.0 + * + * @return A pointer to the %AppResource instance, @n + * else @c null if it fails + */ + static AppResource* GetInstance(void); + + /** + * @if VISPARTNER + * Gets the application resource instance of the specified @c appId. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/appsetting + * + * @return A pointer to the %AppResource instance, @n + * else @c null if it fails + * @param[in] appId The AppId of the installed application + * @exception E_SUCCESS The method is successful. + * @exception E_DATA_NOT_FOUND The instance of specified @c appId does not provide the string resource. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_APP_NOT_INSTALLED The specified @c appId is not found in the list of installed applications. + * @exception E_SYSTEM Initializing string and bitmap resource has failed due to a system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @endif + */ + static AppResource* GetInstanceByAppId(const AppId& appId); + + /** + * @if VISPARTNER + * Releases the application resource instance of the specified @c appId. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/appsetting + * + * @return An error code + * @param[in] appId The AppId of the installed application + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The application resource instance of the specified @c appId is not found. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks Individual instances are managed by the platform. @n + * It is recommended to release instances to reduce memory usage. + * @endif + */ + static result ReleaseInstanceByAppId(const AppId& appId); + +private: + /** + * This default constructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + AppResource(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppResource(const AppResource& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppResource& operator =(const AppResource& rhs); + + /** + * This destructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + virtual ~AppResource(void); + + /** + * Initializes this instance. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(void); + result Construct(const AppId& appId); + static void Reinitialize(void); + void Reinitialize(const AppId& appId); + +private: + class _AppResourceImpl* __pAppResourceImpl; + + friend class _AppResourceImpl; + static Tizen::Base::Collection::HashMap* pContainer; +}; // AppResource + +} } // Tizen::App + +#endif diff --git a/inc/FAppAppSetting.h b/inc/FAppAppSetting.h new file mode 100755 index 0000000..df08c32 --- /dev/null +++ b/inc/FAppAppSetting.h @@ -0,0 +1,357 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppSetting.h + * @brief This is the header file for the %AppSetting class. + * + * This header file contains the declarations of the %AppSetting class. + */ + +#ifndef _FAPP_APP_SETTING_H_ +#define _FAPP_APP_SETTING_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ +class IList; +}}} + + +namespace Tizen { namespace App +{ + +class IAppSettingEventListener; + +/** + * @class AppSetting + * @brief This class manages an application's settings. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %AppSetting class lets an application to save or restore its settings. + * + * + * The following example demonstrates how to use the %AppSetting class. + * + * @code + * void + * AppSettingForm::RefreshSetting(void) + * { + * AppSetting* pAppSetting = AppSetting::GetInstance(); + * AppAssert(pAppSetting); + * + * bool valueBool = false; + * int valueInt = 0; + * const String strLn(L"\n"); + * String valueString; + * String settingText; + * + * AppAssert(pAppSetting->GetValue(L"checkbox1", valueBool) == E_SUCCESS); + * settingText += L"checkbox1: "; + * settingText += strFalseTrue[valueBool ? 1 : 0]; + * settingText += strLn; + * + * AppAssert(pAppSetting->GetValue(L"slider1", valueInt) == E_SUCCESS); + * settingText += L"slider1: "; + * settingText += Integer(valueInt).ToString(); + * settingText += strLn; + * + * AppAssert(pAppSetting->GetValue(L"editbox1", valueString) == E_SUCCESS); + * settingText += L"editbox1: "; + * settingText += valueString; + * settingText += strLn; + * // . . . + * } + * + * void + * AppSettingForm::SetSettingValueSet1(void) + * { + * AppSetting* pAppSetting = AppSetting::GetInstance(); + * AppAssert(pAppSetting); + * + * AppAssert(pAppSetting->SetValue(L"checkbox1", false) == E_SUCCESS); + * AppAssert(pAppSetting->SetValue(L"slider1", 100) == E_SUCCESS); + * AppAssert(pAppSetting->SetValue(L"editbox1", String(L"AppSetting working!")) == E_SUCCESS); + * AppAssert(pAppSetting->SetValue(L"expanditem1", String(L"1 minute")) == E_SUCCESS); + * AppAssert(pAppSetting->SetValue(L"expanditem1", false) == E_SUCCESS); + * AppAssert(pAppSetting->SetValue(L"slider2", 0) == E_SUCCESS); + * AppAssert(pAppSetting->SetValue(L"editbox2", String(L"AppSetting running!")) == E_SUCCESS); + * // . . . + * } + * @endcode + * + */ +class _OSP_EXPORT_ AppSetting + : public Tizen::Base::Object +{ +public: + /** + * Gets the application setting instance. + * + * @since 2.0 + * + * @return A pointer to the %AppSetting instance, @n + * else @c null if it fails + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks It returns an instance for the latest setting. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + static AppSetting* GetInstance(void); + + /** + * Gets the application setting instance of the specified version. + * + * @since 2.0 + * + * @return A pointer to the %AppSetting instance, @n + * else @c null if it fails + * @param[in] settingVersion The version of setting is retrieved from GetAppSettingVersionListN() + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified version is not found. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetAppSettingVersionListN() + */ + static AppSetting* GetInstance(const Tizen::Base::String& settingVersion); + + /** + * @if VISPARTNER + * Gets the application setting instance of the specified AppId. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/appsetting + * + * @return A pointer to the %AppSetting instance, @n + * else @c null if it fails + * @param[in] appId The AppId of the application that has a valid application setting + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The instance of specified AppId does not have setting information. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_APP_NOT_INSTALLED The AppId is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see ReleaseInstanceByAppId() + * @endif + */ + static AppSetting* GetInstanceByAppId(const AppId& appId); + + /** + * @if VISPARTNER + * Releases the specified application setting instance. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/appsetting + * + * @return An error code + * @param[in] appId The AppId of the application that has a valid application setting + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified instance of AppId is not found or already released. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks Individual instances are managed by the platform. @n + * It is recommended to release instances to reduce memory usage. + * @see GetInstanceByAppId() + * @endif + */ + static result ReleaseInstanceByAppId(const AppId& appId); + + /** + * Gets a list of all the versions that existed prior to the current version. @n + * The versions listed are based on the setting.xml file, which is generated when an application is installed. + * + * @since 2.0 + * + * @return A pointer to the list that contains the Tizen::Base::String instances of version list + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The latest version string is located in the first position. + * If the old version does not exist then return empty collection. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + static Tizen::Base::Collection::IList* GetAppSettingVersionListN(void); + + /** + * Gets a @c bool value associated with the specified @c id. + * + * @since 2.0 + * + * @return An error code + * @param[in] id The ID of the value to retrieve + * @param[out] value A boolean value to retrieve + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The specified @c id is not found in the application setting. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access different types. + */ + result GetValue(const Tizen::Base::String& id, bool& value) const; + + /** + * Gets an integer value associated with the specified @c id. + * + * @since 2.0 + * + * @return An error code + * @param[in] id The ID of the value to retrieve + * @param[out] value An integer value to retrieve + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The specified @c id is not found in the application setting. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access different types. + */ + result GetValue(const Tizen::Base::String& id, int& value) const; + + /** + * Gets a string value associated with the specified @c id. + * + * @since 2.0 + * + * @return An error code + * @param[in] id The id of the value to retrieve + * @param[out] value A string value to retrieve + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The specified @c id is not found in the application setting. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access different types. + */ + result GetValue(const Tizen::Base::String& id, Tizen::Base::String& value) const; + + /** + * Sets a @c bool value associated with the specified @c id. + * + * @since 2.0 + * + * @return An error code + * @param[in] id The ID of the value to modify + * @param[in] value A boolean value + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The specified @c id is not found in the application setting. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access different types. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result SetValue(const Tizen::Base::String& id, bool value); + + /** + * Sets an integer value associated with the specified @c id. + * + * @since 2.0 + * + * @return An error code + * @param[in] id The ID of the value to modify + * @param[in] value An integer value + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The specified @c id is not found in the application setting. + * @exception E_OUT_OF_RANGE The specified @c value is out of range. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access different types. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result SetValue(const Tizen::Base::String& id, int value); + + /** + * Sets a string value associated with the specified @c id. + * + * @since 2.0 + * + * @return An error code + * @param[in] id The ID of the value to modify + * @param[in] value A string value + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The specified @c id is not found in the application setting. + * @exception E_OUT_OF_RANGE The specified string length is out of range. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access different types. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result SetValue(const Tizen::Base::String& id, const Tizen::Base::String& value); + + /** + * Sets a setting event listener. + * + * @since 2.0 + * + * @return An error code + * @param[in] pListener An instance of IAppSettingEventListener to set, @n + * else @c null to clear a previous one + * @exception E_SUCCESS The method is successful. + */ + result SetAppSettingEventListener(IAppSettingEventListener* pListener); + +private: + /** + * This default constructor is intentionally declared as private to implement the Singleton semantic. + * + * @since 2.0 + */ + AppSetting(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppSetting(const AppSetting& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + AppSetting& operator =(const AppSetting& rhs); + + /** + * This destructor is intentionally declared as private to implement the Singleton semantic. + * + * @since 2.0 + */ + virtual ~AppSetting(void); + + static void InitSingleton(void); + static void DestroySingleton(void); + +private: + friend class _AppSettingImpl; + class _AppSettingImpl* __pAppSettingImpl; + static AppSetting* __pAppSettingInstance; + +}; // AppSetting +} } // Tizen::App + +#endif // _FAPP_APP_SETTING_H_ diff --git a/inc/FAppApplication.h b/inc/FAppApplication.h new file mode 100644 index 0000000..0bc9c5e --- /dev/null +++ b/inc/FAppApplication.h @@ -0,0 +1,30 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppApplication.h + * @brief This is the header file for the deprecated %Application class. + * + *This header file is for the deprecated %Application class. + */ + +#ifndef _FAPP_APPLICATION_H_ +#define _FAPP_APPLICATION_H_ + +#include + +#endif // _FAPP_APPLICATION_H_ diff --git a/inc/FAppDataControlProviderManager.h b/inc/FAppDataControlProviderManager.h new file mode 100644 index 0000000..fbd6740 --- /dev/null +++ b/inc/FAppDataControlProviderManager.h @@ -0,0 +1,278 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppDataControlProviderManager.h + * @brief This is the header file for the %DataControlProviderManager class. + * + * This header file contains the declarations of the %DataControlProviderManager class. + */ + +#ifndef _FAPP_DATA_CONTROL_PROVIDER_MANAGER_H_ +#define _FAPP_DATA_CONTROL_PROVIDER_MANAGER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +}} +namespace Tizen { namespace Io +{ +class DbEnumerator; +class DataControlResultSet; +}} + +namespace Tizen { namespace App +{ + +class ISqlDataControlProviderEventListener; +class IMapDataControlProviderEventListener; + +/** + * @class DataControlProviderManager + * @brief This class manages the data control provider. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %DataControlProviderManager class manages the data control provider. + */ +class _OSP_EXPORT_ DataControlProviderManager + : public Tizen::Base::Object +{ + +public: + /** + * Sets a SQL-type data control provider listener to the data control provider manager. @n + * The listener gets notified when a data control request is received from the other applications. + * To unset the listener, pass a @c null value to the listener parameter. + * + * @since 2.0 + * + * @return An error code + * @param[in] pListener The SQL-type data control provider listener @n + * The listener must implement the ISqlDataControlProviderEventListener interface. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_INVALID_OPERATION The listener must be set for a service application. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks This method must be called in App::OnAppInitializing() for setting the data control provider listener + * before receiving the data control request. + */ + result SetSqlDataControlProviderEventListener(ISqlDataControlProviderEventListener* pListener); + + /** + * Sets a MAP-type data control provider listener to the data control provider manager. @n + * The listener gets notified when a data control request is received from the other applications. + * To unset the listener, pass a @c null value to the listener parameter. + * + * @since 2.0 + * + * @return An error code + * @param[in] pListener The MAP-type data control provider listener @n + * The listener must implement the IMapDataControlProviderEventListener interface. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_INVALID_OPERATION The listener must be set for a service application. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks This method must be called in App::OnAppInitializing() for setting the data control provider listener + * before receiving the data control request. + */ + result SetMapDataControlProviderEventListener(IMapDataControlProviderEventListener* pListener); + + /** + * Sends the success result and the result set of SELECT request to the application requesting the SQL-type + * data control. @n + * The data control provider must call the %SendSqlDataControlSelectResult() method to notify success to the requesting application. + * The application requesting the data control can get the success result and the result set + * by implementing Tizen::App::ISqlDataControlResponseListener. + * + * @since 2.0 + * + * @return An error code + * @param[in] reqId The request ID + * @param[in] pDbEnum The Tizen::Io::DbEnumerator instance to obtain the result set + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: + * - This method cannot send result for the specified @c reqId of INSERT, UPDATE, or DELETE requests. + * - Tizen::Io::Database or Tizen::Io::DbStatement instance associated with the specified @c pDbEnum is deleted. + * @exception E_OBJ_NOT_FOUND The data control request specified with the @c reqId did not exist. + * @exception E_OBJECT_LOCKED The database instance associated to the specified @c pDbEnum is locked. + * @exception E_INVALID_FORMAT The database file associated to the specified @c pDbEnum is malformed. + * @exception E_IO Either of the following conditions has occurred: + * - An unexpected device failure has occurred as the media ejected suddenly. + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlInsertResult() + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlUpdateDeleteResult() + * @see Tizen::App::DataControlProviderManager::SendDataControlError() + * @see Tizen::App::ISqlDataControlProviderEventListener + */ + result SendSqlDataControlSelectResult(RequestId reqId, Tizen::Io::IDbEnumerator* pDbEnum); + + /** + * Sends the success result of INSERT request and the last inserted row ID to the application requesting + * the SQL-type data control. @n + * The data control provider must call the %SendSqlDataControlInsertResult() method to notify success to the requesting application. + * The application requesting the data control can get the success result and the last inserted row ID + * by implementing Tizen::App::ISqlDataControlResponseListener. + * + * @since 2.0 + * + * @return An error code + * @param[in] reqId The request ID + * @param[in] insertRowId The row ID of database changed by INSERT request + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG This method cannot send result for the specified @c reqId of SELECT, UPDATE, or DELETE request. + * @exception E_OBJ_NOT_FOUND The data control request specified with the @c reqId did not exist. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlSelectResult() + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlUpdateDeleteResult() + * @see Tizen::App::DataControlProviderManager::SendDataControlError() + * @see Tizen::App::ISqlDataControlProviderEventListener + * @see Tizen::Io::Database::GetLastInsertRowId() + */ + result SendSqlDataControlInsertResult(RequestId reqId, long long insertRowId); + + /** + * Sends the success result of UPDATE / DELETE request to the application requesting the SQL-type data control. @n + * The data control provider must call the %SendSqlDataControlUpdateDeleteResult() method to notify success to the requesting application. + * The application requesting the data control can get the success result by implementing Tizen::App::ISqlDataControlResponseListener. + * + * @since 2.0 + * + * @return An error code + * @param[in] reqId The request ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG This method cannot send result for the specified @c reqId of SELECT or INSERT request. + * @exception E_OBJ_NOT_FOUND The data control request specified with the @c reqId did not exist. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlSelectResult() + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlInsertResult() + * @see Tizen::App::DataControlProviderManager::SendDataControlError() + * @see Tizen::App::ISqlDataControlProviderEventListener + */ + result SendSqlDataControlUpdateDeleteResult(RequestId reqId); + + /** + * Sends the success result and the result list of the provider to the application requesting the MAP-type + * data control. @n + * The data control provider must call the %SendMapDataControlResult() method to notify success to the requesting application. + * The application requesting the data control can get the success result and the result set + * by implementing Tizen::App::IMapDataControlResponseListener. + * + * @since 2.0 + * + * @return An error code + * @param[in] reqId The request ID + * @param[in] pResultValueList The result list to request @n + * The type of objects contained in the specified @c pResultValueList must be + * Tizen::Base::String class. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: + * - The specified @c pResultValueList must be @c null if the request is one of + * AddValue, SetValue, RemoveValue queries. + * - The specified @c pResultValueList must not be @c null if the request is + * GetValue() query. + * @exception E_OBJ_NOT_FOUND The data control request specified with the @c reqId does not exist. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::App::DataControlProviderManager::SendDataControlError() + * @see Tizen::App::IMapDataControlProviderEventListener + */ + result SendMapDataControlResult(RequestId reqId, Tizen::Base::Collection::IList* pResultValueList = null); + + /** + * Sends the provider error message to the application requesting the data control. @n + * The data control provider must call the %SendDataControlError() method to notify failure to the requesting application. + * The application requesting the data control can get the failure result and the error message + * by implementing Tizen::App::ISqlDataControlResponseListener. + * + * @since 2.0 + * + * @return An error code + * @param[in] reqId The request ID + * @param[in] errorMsg The provider-defined error message + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The data control request specified with the @c reqId did not exist. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlSelectResult() + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlInsertResult() + * @see Tizen::App::DataControlProviderManager::SendSqlDataControlUpdateDeleteResult() + * @see Tizen::App::DataControlProviderManager::SendMapDataControlResult() + * @see Tizen::App::ISqlDataControlProviderEventListener + * @see Tizen::App::IMapDataControlProviderEventListener + */ + result SendDataControlError(RequestId reqId, const Tizen::Base::String& errorMsg); + + /** + * Gets the data control provider manager instance. + * + * @since 2.0 + * + * @return A pointer to the %DataControlProviderManager instance if it succeeds, @n + * else @c null + */ + static DataControlProviderManager* GetInstance(void); + +private: + /** + * This default constructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + DataControlProviderManager(void); + + /** + * This destructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + virtual ~DataControlProviderManager(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + DataControlProviderManager(const DataControlProviderManager& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + DataControlProviderManager& operator =(const DataControlProviderManager& rhs); + +private: + class _DataControlProviderManagerImpl* __pDataControlProviderManagerImpl; + + friend class _DataControlProviderManagerImpl; + +}; // DataControlProviderManager + +}} // Tizen::App + +#endif // _FAPP_DATA_CONTROL_PROVIDER_MANAGER_H_ + diff --git a/inc/FAppIActiveAppEventListener.h b/inc/FAppIActiveAppEventListener.h new file mode 100644 index 0000000..3314787 --- /dev/null +++ b/inc/FAppIActiveAppEventListener.h @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppIActiveAppEventListener.h + * @brief This is the header file for the %IActiveAppEventListener interface. + * + * This header file contains the declarations of the %IActiveAppEventListener interface. + */ + +#ifndef _FAPP_IACTIVE_APP_EVENT_LISTENER_H_ +#define _FAPP_IACTIVE_APP_EVENT_LISTENER_H_ + +#include +#include +#include + + +namespace Tizen { namespace App +{ + +/** + * @if VISPARTNER + * @interface IActiveAppEventListener + * @brief This interface is the listener interface for receiving the AppId of active application. + * + * @since 2.0 + * + * @visibility partner + * + * The %IActiveAppEventListener interface is the listener interface for receiving the active application change events. + * The class that processes an active application change event implements this interface and registers using + * the AppManager::AddActiveAppEventListener() method. + * + * @endif + */ +class _OSP_EXPORT_ IActiveAppEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * @if VISPARTNER + * This polymorphic destructor should be overridden if required. This way, + * the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + * + * @visibility partner + * + * @endif + */ + virtual ~IActiveAppEventListener(void) {} + + /** + * @if VISPARTNER + * Called when the active application is changed. + * + * @since 2.0 + * + * @visibility partner + * + * @param[in] appId The AppId of the active application + * @endif + */ + virtual void OnActiveAppChanged(const AppId& appId) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IActiveAppEventListener_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IActiveAppEventListener_Reserved2(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IActiveAppEventListener_Reserved3(void) {} + +}; // IActiveAppEventListener +} } // Tizen::App + +#endif // _FAPP_IACTIVE_APP_EVENT_LISTENER_H_ diff --git a/inc/FAppIAppCheckPointEventListener.h b/inc/FAppIAppCheckPointEventListener.h new file mode 100644 index 0000000..9cc842a --- /dev/null +++ b/inc/FAppIAppCheckPointEventListener.h @@ -0,0 +1,98 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppIAppCheckPointEventListener.h + * @brief This is the header file for the %IAppCheckpointEventListener interface. + * + * This header file contains the declarations of the %IAppCheckpointEventListener interface. @n + * If a checkpoint event is generated, a method of this interface is called. + */ + +#ifndef _FAPP_IAPP_CHECK_POINT_EVENT_LISTENER_H_ +#define _FAPP_IAPP_CHECK_POINT_EVENT_LISTENER_H_ + +#include + +namespace Tizen { namespace App +{ + +class AppRegistry; + +/** + * @interface IAppCheckpointEventListener + * @brief This interface defines the listener for the checkpoint event. + * + * @since 2.0 + * + * The %IAppCheckpointEventListener interface is used for receiving the checkpoint event. + * The event is fired when the system is about to terminate an application due to, for example, low memory or when another application + * is being launched. + * @n + * For more information on the class features, see Multitasking in Tizen. + * + */ +class _OSP_EXPORT_ IAppCheckpointEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IAppCheckpointEventListener(void) {} + + /** + * Called when a checkpoint event occurs. + * + * @since 2.0 + * @param[in] appRegistry The application registry + */ + virtual void OnAppCheckpointing(AppRegistry& appRegistry) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppCheckpointEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppCheckpointEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppCheckpointEventListener_Reserved3(void) {} + +}; // IAppCheckpointEventListener + +} } // Tizen::App + +#endif //_FAPP_IAPP_CHECK_POINT_EVENT_LISTENER_H_ diff --git a/inc/FAppIAppControlEventListener.h b/inc/FAppIAppControlEventListener.h new file mode 100644 index 0000000..cfab978 --- /dev/null +++ b/inc/FAppIAppControlEventListener.h @@ -0,0 +1,124 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppIAppControlEventListener.h + * @brief This is the header file for the %IAppControlEventListener interface. + * + * This header file contains the declarations of the %IAppControlEventListener interface. + */ + +#ifndef _FAPP_IAPP_CONTROL_EVENT_LISTENER_H_ +#define _FAPP_IAPP_CONTROL_EVENT_LISTENER_H_ + +#include + +namespace Tizen { namespace Base { class String; } } +namespace Tizen { namespace Base { namespace Collection { class IList; } } } + +namespace Tizen { namespace App +{ + +/** +* @if OSPDEPREC +* @interface IAppControlEventListener +* @brief [Deprecated] This interface defines a listener for the AppControl result events. +* +* @deprecated This class is deprecated. Instead of using this interface, use the IAppControlResponseListener interface. +* @since 2.0 +* +* The %IAppControlEventListener interface defines a listener for the AppControl result events. +* @endif +*/ +class _OSP_EXPORT_ IAppControlEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * @if OSPDEPREC + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this interface, use the IAppControlResponseListener interface. + * @since 2.0 + * @endif + */ + virtual ~IAppControlEventListener(void) {} + + /** + * @if OSPDEPREC + * Called when the application control is completed. @n + * The client can get callback result for some application controls by implementing this listener. @n + * %OnAppControlCompleted() is called after AppControl::Start() with listener for some application controls. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this interface, use the IAppControlResponseListener interface. + * @since 2.0 + * + * @param[in] providerId The provider ID + * @param[in] operationId The operation ID used in application control invocation + * @param[in] pResultList The list of callback strings of application control + * + * @remarks The specified @c pResultList provides the result code for the first array element. + * @remarks When the invoked application control is terminated without sending a result, + * then this method is invoked with @c pResultList and it contains App::APPCONTROL_RESULT_TERMINATED. + * @remarks Switching forms using Tizen::Ui::Controls::Frame::SetCurrentForm() in this listener disables the upcoming form + * (UiApp::OnForeground()). If %UiApp::OnForeground() is being used in the application logic, + * it is recommended to avoid switching forms in this listener. + * @see Tizen::App::AppControl + * @endif + */ + virtual void OnAppControlCompleted(const Tizen::Base::String& providerId, const Tizen::Base::String& operationId, const Tizen::Base::Collection::IList* pResultList) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppControlEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppControlEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppControlEventListener_Reserved3(void) {} +}; // IAppControlEventListener + +} } // Tizen::App + +#endif // _FAPP_IAPP_CONTROL_EVENT_LISTENER_H_ diff --git a/inc/FAppIAppControlListener.h b/inc/FAppIAppControlListener.h new file mode 100644 index 0000000..8bfd226 --- /dev/null +++ b/inc/FAppIAppControlListener.h @@ -0,0 +1,109 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppIAppControlListener.h + * @brief This is the header file for the %IAppControlListener interface. + * + * This header file contains the declarations of the %IAppControlListener interface. + */ + +#ifndef _FAPP_IAPP_CONTROL_LISTENER_H_ +#define _FAPP_IAPP_CONTROL_LISTENER_H_ + +#include + +namespace Tizen { namespace App { class AppControl; } } +namespace Tizen { namespace Base { class String; } } +namespace Tizen { namespace Base { namespace Collection { class IList; } } } + +namespace Tizen { namespace App +{ + +/** + * @if OSPDEPREC + * @interface IAppControlListener + * @brief [Deprecated] This interface defines a listener for the AppControl start and result events. + * + * @deprecated This class is deprecated. Instead of using this interface, use the IAppControlResponseListener interface. + * @since 2.0 + * + * The %IAppControlListener interface defines a listener for the AppControl start and result events. + * @endif + */ +class _OSP_EXPORT_ IAppControlListener + : public IAppControlEventListener + , virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * @if OSPDEPREC + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this interface, use the IAppControlResponseListener interface. + * @since 2.0 + * @endif + */ + virtual ~IAppControlListener(void) {} + + /** + * @if OSPDEPREC + * Called when the application control is about to start. @n + * The client can get the callback result for some application controls by implementing this listener. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this interface, use the IAppControlResponseListener interface. + * @since 2.0 + * + * @param[in] pAppControl A pointer to the AppControl instance that is started + * @param[in] r The error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_IN_PROGRESS The target AppControl is in progress. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @see AppControl::Start() + * @see AppManager::StartAppControl() + * @endif + */ + virtual void OnAppControlStarted(const AppControl* pAppControl, result r) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppControlListener_Reserved1() {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppControlListener_Reserved2() {} +}; // IAppControlListener + +} } // Tizen::App + +#endif // _FAPP_IAPP_CONTROL_LISTENER_H_ diff --git a/inc/FAppIAppControlProviderEventListener.h b/inc/FAppIAppControlProviderEventListener.h new file mode 100644 index 0000000..a2a9993 --- /dev/null +++ b/inc/FAppIAppControlProviderEventListener.h @@ -0,0 +1,112 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppIAppControlProviderEventListener.h + * @brief This is the header file for the %IAppControlProviderEventListener interface. + * + * This header file contains the declarations of the %IAppControlProviderEventListener interface. + */ + +#ifndef _FAPP_IAPPCONTROL_PROVIDER_EVENT_LISTENER_H_ +#define _FAPP_IAPPCONTROL_PROVIDER_EVENT_LISTENER_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection { +class IList; +class IMap; +}}} + +namespace Tizen { namespace App +{ + +/** +* @interface IAppControlProviderEventListener +* @brief This interface defines the provider listener for the AppControl request. +* +* @since 2.0 +* +* The %IAppControlProviderEventListener interface defines a listener for the AppControl request events. +* Applications that provide the %AppControl functionality must implement this interface. +* +* @see AppControlProviderManager +*/ +class _OSP_EXPORT_ IAppControlProviderEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IAppControlProviderEventListener(void) {} + + /** + * Called when the application control request is received from the caller application. @n + * The application control provider must implement this listener for exporting its own functionality. + * + * @since 2.0 + * + * @param[in] reqId The application control request ID + * @param[in] operationId The application control operation ID + * @param[in] pUriData A pointer to the URI data + * @param[in] pMimeType A pointer to the MIME type (RFC 2046) data + * @param[in] pExtraData A pointer to an argument map of key and value pair where the key is of type String and the value is of type String + * @remarks To reply to the application control request, use AppControlProviderManager::SendAppControlResult() with the given request ID. + * @remarks When the application receives the AppControl request on the background, + * %OnAppControlRequestReceived() is invoked before UiApp::OnForeground(). + * @remarks When the application control is resolved with the file extension with AppControl::FindAndStart(), + * the delivered file extension is converted to the corresponding MIME type in the @c pMimeType parameter. + * @see AppControlProviderManager::SendAppControlResult() + */ + virtual void OnAppControlRequestReceived(RequestId reqId, const Tizen::Base::String& operationId, const Tizen::Base::String* pUriData, const Tizen::Base::String* pMimeType, const Tizen::Base::Collection::IMap* pExtraData) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppControlProviderEventListener_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppControlProviderEventListener_Reserved2(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppControlProviderEventListener_Reserved3(void) {} + +}; // IAppControlProviderEventListener + +}} // Tizen::App + +#endif // _FAPP_IAPPCONTROL_PROVIDER_EVENT_LISTENER_H_ diff --git a/inc/FAppIAppControlResponseListener.h b/inc/FAppIAppControlResponseListener.h new file mode 100644 index 0000000..58302c5 --- /dev/null +++ b/inc/FAppIAppControlResponseListener.h @@ -0,0 +1,150 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppIAppControlResponseListener.h + * @brief This is the header file for the %IAppControlResponseListener interface. + * + * This header file contains the declarations of the %IAppControlResponseListener interface. + */ + +#ifndef _FAPP_IAPP_CONTROL_RESPONSE_LISTENER_H_ +#define _FAPP_IAPP_CONTROL_RESPONSE_LISTENER_H_ + +#include + +namespace Tizen { namespace Base { +class String; +namespace Collection { +class IMap; +} +}} + +namespace Tizen { namespace App +{ + +/** +* @interface IAppControlResponseListener +* @brief This interface defines a listener for the AppControl response events. +* +* @since 2.0 +* +* The %IAppControlResponseListener interface defines a listener for the AppControl response events. +*/ +class _OSP_EXPORT_ IAppControlResponseListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IAppControlResponseListener(void) {} + + /** + * Called when the response for application control completion is received. + * + * @since 2.0 + * + * @param[in] appId The ID of the requested application + * @param[in] operationId The operation ID used in application control invocation + * @param[in] appControlResult The application control result + * @param[in] pExtraData The Tizen::Base::String key and %Tizen::Base::String value pair map of application result data + * @remarks The application control completion result is received when the requested application control + * sends the result using AppControlProviderManager::SendAppControlResult(). + * @see AppControl + * @see AppControlProviderManager::SendAppControlResult() + */ + virtual void OnAppControlCompleteResponseReceived(const AppId& appId, const Tizen::Base::String& operationId, AppCtrlResult appControlResult, const Tizen::Base::Collection::IMap* pExtraData) = 0; + + /** + * Called when the application control is about to start or to be canceled by the user resolution. @n + * The calling application can get the result of the resolution by implementing this empty body method. + * + * @since 2.0 + * + * @param[in] appId The ID of the requested application + * @param[in] operationId The operation ID used in application control invocation + * @param[in] r The result of the application control start response @n + * The exception code may be given through this parameter. + * @exception E_SUCCESS The method is successful. + * @exception E_OPERATION_CANCELED The application control resolve request is canceled by a user operation. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM A system error has occurred. + * @remarks This method invoked only for the implicit AppControl resolution. + * @see AppControl + * @see AppControl::FindAndStart() + */ + virtual void OnAppControlStartResponseReceived(const AppId& appId, const Tizen::Base::String& operationId, result r) {} + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppControlResponseListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppControlResponseListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppControlResponseListener_Reserved3(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppControlResponseListener_Reserved4(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppControlResponseListener_Reserved5(void) {} +}; // IAppControlResponseListener + +} } // Tizen::App + +#endif // _FAPP_IAPP_CONTROL_RESPONSE_LISTENER_H_ diff --git a/inc/FAppIAppFrame.h b/inc/FAppIAppFrame.h new file mode 100644 index 0000000..0427056 --- /dev/null +++ b/inc/FAppIAppFrame.h @@ -0,0 +1,149 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppIAppFrame.h + * @brief This is the header file for the %IAppFrame interface. + * + * This header file contains the declarations of the %IAppFrame interface. + */ + +#ifndef _FAPP_IAPP_FRAME_H_ +#define _FAPP_IAPP_FRAME_H_ + +namespace Tizen { namespace Graphics { class Canvas; } } +namespace Tizen { namespace Ui { class IKeyEventListener; } } +namespace Tizen { namespace Ui { class ITouchEventListener; } } +namespace Tizen { namespace Ui { class IWindowEventListener; } } +namespace Tizen { namespace Ui { namespace Controls { class Frame; } } } + +namespace Tizen { namespace App +{ + +/** + * @interface IAppFrame + * @brief This interface provides methods for the application frame. + * + * @since 2.0 + * + * The %IAppFrame interface provides methods for the application frame. A frame is the outermost boundary of the application UI. + */ +class IAppFrame +{ +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IAppFrame(void) {} + + /** + * Gets the values of the frame's canvas. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Graphics::Canvas class + */ + virtual Tizen::Graphics::Canvas* GetCanvasN(void) const = 0; + + /** + * Adds a key event listener to the frame. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener A Tizen::Ui::IKeyEventListener instance to add + * @exception E_SUCCESS The method is successful. + */ + virtual result AddKeyEventListener(Tizen::Ui::IKeyEventListener& listener) = 0; + + /** + * Removes an existing key event listener from the frame. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener A Tizen::Ui::IKeyEventListener instance to remove + * @exception E_SUCCESS The method is successful. + */ + virtual result RemoveKeyEventListener(Tizen::Ui::IKeyEventListener& listener) = 0; + + /** + * Adds a touch event listener to the frame. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener A Tizen::Ui::ITouchEventListener instance to add + * @exception E_SUCCESS The method is successful. + */ + virtual result AddTouchEventListener(Tizen::Ui::ITouchEventListener& listener) = 0; + + /** + * Removes an existing touch event listener from the frame. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener A Tizen::Ui::ITouchEventListener instance to add + * @exception E_SUCCESS The method is successful. + */ + virtual result RemoveTouchEventListener(Tizen::Ui::ITouchEventListener& listener) = 0; + + /** + * Adds a window event listener to the frame. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener A Tizen::Ui::IWindowEventListener instance to remove + * @exception E_SUCCESS The method is successful. + */ + virtual result AddWindowEventListener(Tizen::Ui::IWindowEventListener& listener) = 0; + + /** + * Removes an existing window event listener from the frame. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener A Tizen::Ui::IWindowEventListener instance to remove + * @exception E_SUCCESS The method is successful. + */ + virtual result RemoveWindowEventListener(Tizen::Ui::IWindowEventListener& listener) = 0; + + /** + * Gets the frame of the application. + * + * @since 2.0 + * + * @return A pointer to Tizen::Ui::Controls::Frame if successful, @n + * else @c null + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance is in an invalid state. + * @exception E_UNSUPPORTED_OPERATION This method cannot be supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Ui::Controls::Frame* GetFrame(void) = 0; + +}; // IAppFrame + +} } // Tizen::App + +#endif // _FAPP_IAPP_FRAME_H_ diff --git a/inc/FAppIAppLaunchConditionEventListener.h b/inc/FAppIAppLaunchConditionEventListener.h new file mode 100644 index 0000000..9c7ecd6 --- /dev/null +++ b/inc/FAppIAppLaunchConditionEventListener.h @@ -0,0 +1,116 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppIAppLaunchConditionEventListener.h + * @brief This is the header file for the %IAppLaunchConditionEventListener interface. + * + * This header file contains the declarations of the %IAppLaunchConditionEventListener interface. + */ + +#ifndef _FAPP_IAPP_LAUNCH_CONDITION_EVENT_LISTENER_H_ +#define _FAPP_IAPP_LAUNCH_CONDITION_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace Base { class String; } } + +namespace Tizen { namespace App +{ + +/** +* @interface IAppLaunchConditionEventListener +* @brief This interface defines a listener for the AppLaunchCondition events. +* +* @since 2.0 +* +* The %IAppLaunchConditionEventListener interface defines a listener for the AppLaunchCondition events. +* @n +* For more information on the class features, see Launching Other Applications, Registering a Launch Condition. +*/ +class _OSP_EXPORT_ IAppLaunchConditionEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IAppLaunchConditionEventListener(void) {} + + /** + * Called when the registered launch condition is met. + * + * @since 2.0 + * + * @param[in] condition The registered condition for the application launch + * @param[in] pArguments A list of string arguments specified when the condition is registered + * @param[in] pExtraData A pointer to the instance of object that system delivered, @n + * else @c null if there is no extra data + * + * @remarks If extra data is required to be delivered, @c pExtraData contains the data, + * and this must be freed by the launched application after use. + * ( Currently, only NFC condition uses this to deliver to Tizen::Net::Nfc::NdefMessage. ) + * @see Tizen::App::AppManager::RegisterAppLaunch() + * @see Tizen::App::AppManager::SetAppLaunchConditionEventListener() + * + * The following example demonstrates how to use the %OnAppLaunchConditionMetN() method to get Tizen::Net::Nfc::NdefMessage instance, when an application is launched by NFC condition. + * @code + * NdefMessage* pMessage = dynamic_cast(pExtraData); + * @endcode + */ + virtual void OnAppLaunchConditionMetN(const Tizen::Base::String& condition, Tizen::Base::Object* pExtraData, Tizen::Base::Collection::IList* pArguments) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppLaunchConditionEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppLaunchConditionEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAppLaunchConditionEventListener_Reserved3(void) {} +}; // IAppLaunchConditionEventListener + +} } // Tizen::App + +#endif // _FAPP_IAPP_LAUNCH_CONDITION_EVENT_LISTENER_H_ + diff --git a/inc/FAppIAppSettingEventListener.h b/inc/FAppIAppSettingEventListener.h new file mode 100644 index 0000000..75a5732 --- /dev/null +++ b/inc/FAppIAppSettingEventListener.h @@ -0,0 +1,95 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppIAppSettingEventListener.h + * @brief This is the header file for the %IAppSettingEventListener interface. + * + * This header file contains the declarations of the %IAppSettingEventListener interface. + */ + +#ifndef _FAPP_IAPP_SETTING_EVENT_LISTENER_H_ +#define _FAPP_IAPP_SETTING_EVENT_LISTENER_H_ + +#include +#include +#include + + +namespace Tizen { namespace App +{ + +/** + * @interface IAppSettingEventListener + * @brief This interface is the listener interface for receiving the setting change events. + * + * @since 2.0 + * + * The %IAppSettingEventListener interface is the listener interface for receiving the setting change events. + * The class that processes a setting change event implements this interface and registers using + * the AppSetting::SetAppSettingEventListener() method. + * + */ +class _OSP_EXPORT_ IAppSettingEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. This way, + * the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IAppSettingEventListener(void) {} + + /** + * Called when the application setting is changed. + * + * @since 2.0 + * + * @param[in] id The ID of the application setting whose value is changed + */ + virtual void OnAppSettingChanged(const Tizen::Base::String& id) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppSettingEventListener_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppSettingEventListener_Reserved2(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, + // security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void IAppSettingEventListener_Reserved3(void) {} + +}; // IAppSettingEventListener +} } // Tizen::App + +#endif // _FAPP_IAPP_SETTING_EVENT_LISTENER_H_ diff --git a/inc/FAppIMapDataControlProviderEventListener.h b/inc/FAppIMapDataControlProviderEventListener.h new file mode 100644 index 0000000..474e460 --- /dev/null +++ b/inc/FAppIMapDataControlProviderEventListener.h @@ -0,0 +1,317 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppIMapDataControlProviderEventListener.h + * @brief This is the header file for the %IMapDataControlProviderEventListener interface. + * + * This header file contains the declarations of the %IMapDataControlProviderEventListener interface. + */ + +#ifndef _FAPP_IMAP_DATACONTROL_REQUESTEVENT_LISTENER_H_ +#define _FAPP_IMAP_DATACONTROL_REQUESTEVENT_LISTENER_H_ + +#include +#include +#include + +namespace Tizen { namespace App +{ + +/** + * @interface IMapDataControlProviderEventListener + * @brief This interface defines a listener for dealing with MAP-type data control request. + * + * @since 2.0 + * + * The %IMapDataControlProviderEventListener interface defines a listener for dealing with MAP-type data control request. + * + * The following example demonstrates how to use the %IMapDataControlProviderEventListener interface. + * @code +#include +#include +#include + +class MyServiceApp + : public Tizen::App::ServiceApp + : public Tizen::App::IMapDataControlProviderEventListener +{ +public: + MyServiceApp(void); + virtual ~MyServiceApp(void); + + virtual bool OnAppInitializing(Tizen::App::AppRegistry& appRegistry); + virtual bool OnAppTerminating(Tizen::App::AppRegistry& appRegistry, bool forcedTermination = false); + + virtual void OnMapDataControlGetValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key); + virtual void OnMapDataControlAddValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& value); + virtual void OnMapDataControlSetValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& oldValue, + const Tizen::Base::String& newValue); + virtual void OnMapDataControlRemoveValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& value); +}; + +bool +MyServiceApp::OnAppInitializing(Tizen::App::AppRegistry& appRegistry) +{ + result r = E_SUCCESS; + + DataControlProviderManager* pDcMgr = DataControlProviderManager::GetInstance(); + if (pDcMgr == null) + { + AppLog("Failed to get the instance of data control provider manager."); + return false; + } + + r = pDcMgr->SetMapDataControlProviderEventListener(this); + if (IsFailed(r)) + { + AppLog("Failed to set the data control provider listener."); + return false; + } + + return true; +} + +void +MyServiceApp::OnMapDataControlGetValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key) +{ + Registry* pReg = null; + String retValue; + ArrayList* pResultValueList = null; + String errorMsg; + result r = E_SUCCESS; + + if (providerId.compareTo(L"http://tizen.org/datacontrol/provider/example") == 0) + { + if (dataId.compareTo(L"test") == 0) + { + String regPath(GetAppRootPath() + L"data/test.ini"); + + pReg = new Registry(); + if (pReg == null) + { + errorMsg.Append(L"The memory is insufficient."); + goto CATCH; + } + + r = pReg->Construct(regPath, false); + if (IsFailed(r)) + { + errorMsg.Append(L"The data control provider failed to open the registry file."); + goto CATCH; + } + + r = pReg->GetValue(dataId, key, retValue); + if (IsFailed(r)) + { + errorMsg.Append(L"The data control provider failed to get the value."); + goto CATCH: + } + + pResultValueList = new ArrayList(); + pResultValueList->Add(retValue); + + delete pReg; + } + else + { + errorMsg.Append(L"The data ID is invalid."); + } + } + else + { + errorMsg.Append(L"The provider ID is invalid."); + } + + r = DataControlProviderManager::GetInstance()->SendMapDataControlResult(reqId, pResultValueList); + if (IsFailed(r)) + { + AppLog("The data control provider failed to send the result."); + } + + if (pResultValueList) + { + pResultValueList->RemoveAll(); + delete pResultValueList; + } + return; + +CATCH: + r = DataControlProviderManager::GetInstance()->SendDataControlError(reqId, errorMsg); + if (IsFailed(r)) + { + AppLog("The data control provider failed to send the result."); + } + + delete pReg; + if (pResultValueList) + { + pResultValueList->RemoveAll(); + delete pResultValueList; + } + return; +} +* @endcode +*/ +class _OSP_EXPORT_ IMapDataControlProviderEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ + +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMapDataControlProviderEventListener(void) {} + + /** + * Called when the request for getting the value list is received from MAP-type data control consumer. @n + * The provider must implement this listener for providing its own data. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific map to get from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] key A key of the value list to obtain + * @remarks For replying to the data control request, use DataControlProviderManager::SendMapDataControlResult() + * or DataControlProviderManager::SendDataControlError(). + */ + virtual void OnMapDataControlGetValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key) = 0; + + /** + * Called when the request for adding the value is received from MAP-type data control consumer. @n + * The provider must implement this listener for providing its own data. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific map to add to @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] key A key of the value list to add + * @param[in] value A value to add + * @remarks For replying to the data control request, use DataControlProviderManager::SendMapDataControlResult() + * or DataControlProviderManager::SendDataControlError(). + */ + virtual void OnMapDataControlAddValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& value) = 0; + + /** + * Called when the request for replacing the value is received from MAP-type data control consumer. @n + * The provider must implement this listener for providing its own data. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific map to update @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] key A key of the value to replace + * @param[in] oldValue A value to replace + * @param[in] newValue A new value to replace the existing value + * @remarks For replying to the data control request, use DataControlProviderManager::SendMapDataControlResult() + * or DataControlProviderManager::SendDataControlError(). + */ + virtual void OnMapDataControlSetValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& oldValue, + const Tizen::Base::String& newValue) = 0; + + /** + * Called when the request for removing the value is received from MAP-type data control consumer. @n + * The provider must implement this listener for providing its own data. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific map to remove from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] key A key of the value to remove + * @param[in] value A value to remove + * @remarks For replying to the data control request, use DataControlProviderManager::SendMapDataControlResult() + * or DataControlProviderManager::SendDataControlError(). + */ + virtual void OnMapDataControlRemoveValueRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& value) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlProviderEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlProviderEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlProviderEventListener_Reserved3(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlProviderEventListener_Reserved4(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlProviderEventListener_Reserved5(void) {} + +}; // IMapDataControlProviderEventListener + +}} // Tizen::App + +#endif // _FAPP_IMAP_DATACONTROL_REQUESTEVENT_LISTENER_H_ + diff --git a/inc/FAppIMapDataControlResponseListener.h b/inc/FAppIMapDataControlResponseListener.h new file mode 100644 index 0000000..71c83ff --- /dev/null +++ b/inc/FAppIMapDataControlResponseListener.h @@ -0,0 +1,193 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FAppIMapDataControlResponseListener.h +* @brief This is the header file for the %IMapDataControlResponseListener interface. +* +* This header file contains the declarations of the %IMapDataControlResponseListener interface. +*/ + +#ifndef _FAPP_IMAP_DATA_CONTROL_RESPONSE_LISTENER_H_ +#define _FAPP_IMAP_DATA_CONTROL_RESPONSE_LISTENER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace App +{ + +/** +* @interface IMapDataControlResponseListener +* @brief This interface defines a listener for the MAP-type data control response. +* +* @since 2.0 +* +* The %IMapDataControlResponseListener interface defines a listener for the MAP-type data control response. +*/ +class _OSP_EXPORT_ IMapDataControlResponseListener + : virtual public Tizen::Base::Runtime::IEventListener +{ + +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMapDataControlResponseListener(void) {} + + /** + * Called when the result value list is received from MAP-type data control provider. @n + * The application requesting the data control can get the result value list by implementing this listener. @n + * This listener must be registered by MapDataControl::SetMapDataControlResponseListener() for receiving the result value set. + * It is called after MapDataControl::GetValue(). + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific map to get from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] resultValueList The result value list of data control request getting matching values @n + * The type of objects contained in the specified @c resultValueList is + * Tizen::Base::String class. + * @param[in] providerResult Set to @c true if the data control provider successfully processed the request getting the values, @n + * else @c false + * @param[in] pErrorMsg The error message from the data control provider + */ + virtual void OnMapDataControlGetValueResponseReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, Tizen::Base::Collection::IList& resultValueList, + bool providerResult, const Tizen::Base::String* pErrorMsg) = 0; + + /** + * Called when the response is received from MAP-type data control provider. @n + * The application requesting the data control can get the result by implementing this listener. @n + * This listener must be registered by MapDataControl::SetMapDataControlResponseListener() for receiving the result response. + * It is called after MapDataControl::AddValue(). + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific map to add to @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] providerResult Set to @c true if the data control provider successfully processed the request adding a value, @n + * else @c false + * @param[in] pErrorMsg The error message from the data control provider + */ + virtual void OnMapDataControlAddValueResponseReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, bool providerResult, const Tizen::Base::String* pErrorMsg) = 0; + + /** + * Called when the response is received from MAP-type data control provider. @n + * The application requesting the data control can get the result for some data controls by implementing this listener. @n + * This listener must be registered by MapDataControl::SetMapDataControlResponseListener() for receiving the result response. + * It is called after MapDataControl::SetValue(). + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific map to update @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] providerResult Set to @c true if the data control provider successfully processed the request replacing a value, @n + * else @c false + * @param[in] pErrorMsg The error message from the data control provider + */ + virtual void OnMapDataControlSetValueResponseReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, bool providerResult, const Tizen::Base::String* pErrorMsg) = 0; + + /** + * Called when the response is received from MAP-type data control provider. @n + * The application requesting the data control can get the result for some data controls by implementing this listener. @n + * This listener must be registered by MapDataControl::SetMapDataControlResponseListener() for receiving the result response. + * It is called after MapDataControl::RemoveValue(). + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific map to remove from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] providerResult Set to @c true if the data control provider successfully processed the request removing a value, @n + * else @c false + * @param[in] pErrorMsg The error message from the data control provider + */ + virtual void OnMapDataControlRemoveValueResponseReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, bool providerResult, const Tizen::Base::String* pErrorMsg) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlResponseListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlResponseListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlResponseListener_Reserved3(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlResponseListener_Reserved4(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMapDataControlResponseListener_Reserved5(void) {} + +}; // IMapDataControlResponseListener + +}} // Tizen::App + +#endif // _FAPP_IMAP_DATA_CONTROL_RESPONSE_LISTENER_H_ + diff --git a/inc/FAppISqlDataControlProviderEventListener.h b/inc/FAppISqlDataControlProviderEventListener.h new file mode 100644 index 0000000..a919fc4 --- /dev/null +++ b/inc/FAppISqlDataControlProviderEventListener.h @@ -0,0 +1,396 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppISqlDataControlProviderEventListener.h + * @brief This is the header file for the %ISqlDataControlProviderEventListener interface. + * + * This header file contains the declarations of the %ISqlDataControlProviderEventListener interface. + */ + +#ifndef _FAPP_ISQL_DATACONTROL_REQUESTEVENT_LISTENER_H_ +#define _FAPP_ISQL_DATACONTROL_REQUESTEVENT_LISTENER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace App +{ + +/** + * @interface ISqlDataControlProviderEventListener + * @brief This interface defines a listener for dealing with SQL-type data control request. + * + * @since 2.0 + * + * The %ISqlDataControlProviderEventListener interface defines a listener for dealing with SQL-type data control request. + * + * The following example demonstrates how to use the %ISqlDataControlProviderEventListener interface. + * + * @code +#include +#include +#include + +class MyServiceApp + : public Tizen::App::ServiceApp + : public Tizen::App::ISqlDataControlProviderEventListener +{ +public: + MyServiceApp(void); + virtual ~MyServiceApp(void); + + virtual bool OnAppInitializing(Tizen::App::AppRegistry& appRegistry); + virtual bool OnAppTerminating(Tizen::App::AppRegistry& appRegistry, bool forcedTermination = false); + + virtual void OnSqlDataControlSelectRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::Collection::IList* pColumnList, + const Tizen::Base::String* pWhere, const Tizen::Base::String* pOrder); + virtual void OnSqlDataControlInsertRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& insertMap); + virtual void OnSqlDataControlUpdateRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& updateMap, + const Tizen::Base::String* pWhere); + virtual void OnSqlDataControlDeleteRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String* pWhere); +}; + +bool +MyServiceApp::OnAppInitializing(Tizen::App::AppRegistry& appRegistry) +{ + result r = E_SUCCESS; + + DataControlProviderManager* pDcMgr = DataControlProviderManager::GetInstance(); + if (pDcMgr == null) + { + AppLog("Failed to get the instance of data control provider manager."); + return false; + } + + r = pDcMgr->SetSqlDataControlProviderEventListener(this); + if (IsFailed(r)) + { + AppLog("Failed to set the data control provider listener."); + return false; + } + + return true; +} + +void +MyServiceApp::OnSqlDataControlSelectRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::Collection::IList* pColumnList, + const Tizen::Base::String* pWhere, const Tizen::Base::String* pOrder) +{ + Database* pDb = null; + DbEnumerator* pDbEnum = null; + String errorMsg; + result r = E_SUCCESS; + + if (providerId == L"http://tizen.org/datacontrol/provider/example") + { + if (dataId == L"test") + { + String sql = SqlStatementBuilder::CreateSelectStatement(dataId, pColumnList, pWhere, pOrder, + null, null, null); + + String dbPath(App::GetInstance()->GetAppDataPath() + L"test.db"); + + pDb = new Database(); + if (pDb == null) + { + errorMsg.Append(L"The memory is insufficient."); + goto CATCH; + } + + r = pDb->Construct(dbPath, "r"); + if (IsFailed(r)) + { + errorMsg.Append(L"The data control provider failed to open the database file."); + goto CATCH; + } + + pDbEnum = pDb->QueryN(sql); + r = GetLastResult(); + if (IsFailed(r)) + { + errorMsg.Append(L"The data control provider failed to execute SQL statement."); + goto CATCH; + } + } + else + { + errorMsg.Append(L"The data ID is invalid."); + } + } + else + { + errorMsg.Append(L"The provider ID is invalid."); + } + + r = DataControlProviderManager::GetInstance()->SendSqlDataControlSelectResult(reqId, pDbEnum); + if (IsFailed(r)) + { + AppLog("The data control provider failed to send the result."); + } + + delete pDbEnum; + delete pDb; + return; + +CATCH: + r = DataControlProviderManager::Getinstance()->SendDataControlError(reqId, errorMsg); + if (IsFailed(r)) + { + AppLog("The data control provider failed to send the result."); + } + + delete pDbEnum; + delete pDb; + return; +} + +void +MyServiceApp::OnSqlDataControlInsertRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& insertMap) +{ + Database* pDb = null; + String errorMsg; + long long insertRowId = -1; + result r = E_SUCCESS; + + if (providerId == L"http://tizen.org/datacontrol/provider/example") + { + if (dataId == L"test") + { + String sql = SqlStatementBuilder::CreateInsertStatement(dataId, insertMap); + + String dbPath(App::GetInstance()->GetAppDataPath() + L"test.db"); + + pDb = new Database(); + if (pDb == null) + { + errorMsg.Append(L"The memory is insufficient."); + goto CATCH; + } + + r = pDb->Construct(dbPath, "a+"); + if (IsFailed(r)) + { + errorMsg.Append(L"The data control provider failed to open the database file."); + goto CATCH; + } + + r = pDb->ExcuteSql(sql, true); + if (IsFailed(r)) + { + errorMsg.Append(L"The data control provider failed to execute SQL statement."); + goto CATCH; + } + + insertRowId = pDb->GetLastInsertRowId(); + } + else + { + errorMsg.Append(L"The data ID is invalid."); + } + } + else + { + errorMsg.Append(L"The provider ID is invalid."); + } + + r = DataControlProviderManager::GetInstance()->SendSqlDataControlInsertResult(reqId, insertRowId); + if (IsFailed(r)) + { + AppLog("The data control provider failed to send the result."); + } + + delete pDb; + return; + +CATCH: + r = DataControlProviderManager::Getinstance()->SendDataControlError(reqId, errorMsg); + if (IsFailed(r)) + { + AppLog("The data control provider failed to send the result."); + } + + delete pDb; + return; +} +* @endcode +*/ +class _OSP_EXPORT_ ISqlDataControlProviderEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ + +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISqlDataControlProviderEventListener(void) {} + + /** + * Called when a select request is received from an application using SQL-type data control. @n + * The provider must implement this listener for providing its own data. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The provider ID for identifying the data control + * @param[in] dataId A string for identifying a specific table to query from @n + * The string consists of one or more components, separated by a slash('/'). + * If the specified @c pColumnList is @c null, all columns are selected. + * @param[in] pColumnList A list of column names to query @n + * The type of objects contained in the specified @c pColumnList is + * Tizen::Base::String class. + * @param[in] pWhere A filter to select desired rows to query @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * @param[in] pOrder The sorting order of rows to query @n + * It is an SQL 'ORDER BY' clause excluding the 'ORDER BY' itself. + * @remarks For replying to the data control request, use DataControlProviderManager::SendSqlDataControlSelectResult() + * or DataControlProviderManager::SendDataControlError(). + */ + virtual void OnSqlDataControlSelectRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::Collection::IList* pColumnList, + const Tizen::Base::String* pWhere, const Tizen::Base::String* pOrder) = 0; + + /** + * Called when an insert request is received from an application using SQL-type data control. @n + * The provider must implement this listener for providing its own data. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The provider ID for identifying the data control + * @param[in] dataId A string for identifying a specific table to insert into @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] insertMap The column-value pairs to insert @n + * The type of objects contained in the specified @c insertMap is + * Tizen::Base::String class. + * @remarks For replying to the data control request, use DataControlProviderManager::SendSqlDataControlInsertResult() + * or DataControlProviderManager::SendDataControlError(). + */ + virtual void OnSqlDataControlInsertRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& insertMap) = 0; + + /** + * Called when an update request is received from an application using SQL-type data control. @n + * The provider must implement this listener for providing its own data. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The provider ID for identifying the data control + * @param[in] dataId A string for identifying a specific table to update @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] updateMap The column-value pairs to update @n + * The type of objects contained in the specified @c updateMap is + * Tizen::Base::String class. + * @param[in] pWhere A filter to select desired rows to update @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * @remarks For replying to the data control request, use DataControlProviderManager::SendSqlDataControlUpdateDeleteResult() + * or DataControlProviderManager::SendDataControlError(). + */ + virtual void OnSqlDataControlUpdateRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& updateMap, + const Tizen::Base::String* pWhere) = 0; + + /** + * Called when a delete request is received from an application using SQL-type data control. @n + * The provider must implement this listener for providing its own data. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The provider ID for identifying the data control + * @param[in] dataId A string for identifying a specific table to delete from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] pWhere A filter to select desired rows to delete @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * @remarks For replying to the data control request, use DataControlProviderManager::SendSqlDataControlUpdateDeleteResult() + * or DataControlProviderManager::SendDataControlError(). + */ + virtual void OnSqlDataControlDeleteRequestReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, const Tizen::Base::String* pWhere) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlProviderEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlProviderEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlProviderEventListener_Reserved3(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlProviderEventListener_Reserved4(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlProviderEventListener_Reserved5(void) {} + +}; // ISqlDataControlProviderEventListener + +}} // Tizen::App + +#endif // _FAPP_ISQL_DATACONTROL_REQUESTEVENT_LISTENER_H_ + diff --git a/inc/FAppISqlDataControlResponseListener.h b/inc/FAppISqlDataControlResponseListener.h new file mode 100644 index 0000000..5ff6b1b --- /dev/null +++ b/inc/FAppISqlDataControlResponseListener.h @@ -0,0 +1,192 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FAppISqlDataControlResponseListener.h +* @brief This is the header file for the %ISqlDataControlResponseListener interface. +* +* This header file contains the declarations of the %ISqlDataControlResponseListener interface. +*/ + +#ifndef _FAPP_ISQL_DATACONTROL_RESPONSE_LISTENER_H_ +#define _FAPP_ISQL_DATACONTROL_RESPONSE_LISTENER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace App +{ + +/** +* @interface ISqlDataControlResponseListener +* @brief This interface defines a listener for the SQL-type data control response. +* +* @since 2.0 +* +* The %ISqlDataControlResponseListener interface defines a listener for the SQL-type data control response. +*/ +class _OSP_EXPORT_ ISqlDataControlResponseListener + : virtual public Tizen::Base::Runtime::IEventListener +{ + +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISqlDataControlResponseListener(void) {} + + /** + * Called when the result set is received from SQL-type data control provider. @n + * The application requesting the data control can get the query result by implementing this listener. @n + * This listener must be registered by SqlDataControl::SetSqlDataControlResponseListener() for receiving the result set. + * It is called after SqlDataControl::Select(). + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific table to query from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] resultSetEnumerator Navigates the result of data control select request + * @param[in] providerResult Set to @c true if the data control provider successfully processed the query request, @n + * else @c false + * @param[in] pErrorMsg The error message from the data control provider + */ + virtual void OnSqlDataControlSelectResponseReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, Tizen::Io::IDbEnumerator& resultSetEnumerator, bool providerResult, const Tizen::Base::String* pErrorMsg) = 0; + + /** + * Called when the response is received from SQL-type data control provider. @n + * The application requesting the data control can get insert result by implementing this listener. @n + * This listener must be registered by SqlDataControl::SetSqlDataControlResponseListener() for receiving the result response. + * It is called after SqlDataControl::Insert(). + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific table to insert into @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] insertRowId The inserted row ID set by the data control provider if the specified @c providerResult is @c true, @n + * else @c -1 + * @param[in] providerResult Set to @c true if the data control provider successfully processed the insert request, @n + * else @c false + * @param[in] pErrorMsg The error message from the data control provider + */ + virtual void OnSqlDataControlInsertResponseReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, long long insertRowId, bool providerResult, const Tizen::Base::String* pErrorMsg) = 0; + + /** + * Called when the response is received from SQL-type data control provider. @n + * The application requesting the data control can get update result implementing this listener. @n + * This listener must be registered by SqlDataControl::SetSqlDataControlResponseListener() for receiving the result response. + * It is called after SqlDataControl::Update(). + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific table to update @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] providerResult Set to @c true if the data control provider successfully processed the update request, @n + * else @c false + * @param[in] pErrorMsg The error message from the data control provider + */ + virtual void OnSqlDataControlUpdateResponseReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, bool providerResult, const Tizen::Base::String* pErrorMsg) = 0; + + /** + * Called when the response is received from SQL-type data control provider. @n + * The application requesting the data control can get delete result by implementing this listener. @n + * This listener must be registered by SqlDataControl::SetSqlDataControlResponseListener() for receiving the result response. + * It is called after SqlDataControl::Delete(). + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] providerId The data control provider ID + * @param[in] dataId A string for identifying a specific table to delete from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] providerResult Set to @c true if the data control provider successfully processed the delete request, @n + * else @c false + * @param[in] pErrorMsg The error message from the data control provider + */ + virtual void OnSqlDataControlDeleteResponseReceived(RequestId reqId, const Tizen::Base::String& providerId, + const Tizen::Base::String& dataId, bool providerResult, const Tizen::Base::String* pErrorMsg) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlResponseListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlResponseListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlResponseListener_Reserved3(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlResponseListener_Reserved4(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISqlDataControlResponseListener_Reserved5(void) {} + +}; // ISqlDataControlResponseListener + +}} // Tizen::App + +#endif // _FAPP_ISQL_DATACONTROL_RESPONSE_LISTENER_H_ + diff --git a/inc/FAppMapDataControl.h b/inc/FAppMapDataControl.h new file mode 100644 index 0000000..02aa664 --- /dev/null +++ b/inc/FAppMapDataControl.h @@ -0,0 +1,221 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppMapDataControl.h + * @brief This is the header file for the %MapDataControl class. + * + * This header file contains the declarations of the %MapDataControl class. + */ + +#ifndef _FAPP_MAP_DATA_CONTROL_H_ +#define _FAPP_MAP_DATA_CONTROL_H_ + +#include +#include + +namespace Tizen { namespace Base +{ +class String; +}} + +namespace Tizen { namespace App +{ + +class IMapDataControlResponseListener; + +/** + * @class MapDataControl + * @brief This class represents the MAP-type data control behavior. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %MapDataControl class represents the MAP-type data control behavior, that provides a standard mechanism + * for accessing specific data exported by other applications. + * Data control provider can share its own data to data control consumers. + * + * For more information on the class features, see Data Controls. + * + * @see Tizen::App::AppManager + */ + +class _OSP_EXPORT_ MapDataControl + : public Tizen::Base::Object +{ + +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~MapDataControl(void); + + /** + * Gets the value list associated with the specified @c key, from a key-values map owned by MAP-type data control provider. @n + * The %GetValue() method is asynchronous. + * For receiving the response from data control provider, set the listener + * with MapDataControl::SetMapDataControlResponseListener(). @n + * When the requested value list has been received from data control provider, + * the IMapDataControlResponseListener::OnMapDataControlGetValueResponseReceived() method is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] dataId A string for identifying specific data, usually a registry section to get from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] key A key of the value list to obtain + * @param[out] reqId The ID of the request + * @param[in] pageNo The page number of the value set @n + * It starts from @c 1. + * @param[in] countPerPage The desired maximum count of the data item on the page + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed as yet. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c pageNo parameter is less than @c 1. + * - The specified @c countPerPage parameter is less than @c 1. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result GetValue(const Tizen::Base::String& dataId, const Tizen::Base::String& key, RequestId& reqId, int pageNo = 1, int countPerPage = 20); + + /** + * Adds the value associated with the specified @c key, to a key-values map owned by MAP-type data control provider. @n + * The %AddValue() method is asynchronous. + * For receiving the response from data control provider, set the listener + * with MapDataControl::SetMapDataControlResponseListener(). @n + * When the response has been received from the data control provider, + * the IMapDataControlResponseListener::OnMapDataControlAddValueResponseReceived() method is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] dataId A string for identifying specific data, usually a registry section to add to @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] key A key of the value list to add + * @param[in] value A value to add + * @param[out] reqId The ID of the request + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed as yet. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result AddValue(const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& value, RequestId& reqId); + + /** + * Sets the value associated with the specified @c key with a new value. @n + * The key-values map is owned by MAP-type data control provider. @n + * The %SetValue() method is asynchronous. + * For receiving the response from data control provider, set the listener + * with MapDataControl::SetMapDataControlResponseListener(). @n + * When the response has been received from the data control provider, + * the IMapDataControlResponseListener::OnMapDataControlSetValueResponseReceived() method is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] dataId A string for identifying specific data, usually a registry section to update @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] key A key of the value to replace + * @param[in] oldValue A value to replace + * @param[in] newValue A new value to replace the existing value + * @param[out] reqId The ID of the request + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed as yet. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result SetValue(const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& oldValue, const Tizen::Base::String& newValue, RequestId& reqId); + + /** + * Removes the value associated with the specified @c key, from a key-values map owned by MAP-type data control provider. + * The %RemoveValue() method is asynchronous. + * For receiving the response from data control provider, set the listener + * with MapDataControl::SetMapDataControlResponseListener(). @n + * When the response has been received from the data control provider, + * the IMapDataControlResponseListener::OnMapDataControlRemoveValueResponseReceived() method is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] dataId A string for identifying specific data, usually a registry section to remove from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] key A key of the value to removed + * @param[in] value A value to removed + * @param[out] reqId The ID of the request + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed as yet. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result RemoveValue(const Tizen::Base::String& dataId, const Tizen::Base::String& key, const Tizen::Base::String& value, RequestId& reqId); + + /** + * Sets the MAP-based data control listener to this instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] pListener The data control callback listener @n + * Some data controls need to get the callback result by implementing + * the IMapDataControlResponseListener interface. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_SYSTEM A system error has occurred. + */ + result SetMapDataControlResponseListener(IMapDataControlResponseListener* pListener); + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + MapDataControl(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * @remarks This constructor is hidden. + */ + MapDataControl(const MapDataControl& mapDataControl); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * @remarks This operator is hidden. + */ + MapDataControl& operator =(const MapDataControl& mapDataControl); + +private: + class _MapDataControlImpl * __pMapDataControlImpl; + + friend class _MapDataControlImpl; +}; // MapDataControl + +}} // Tizen::App + +#endif // _FAPP_MAP_DATA_CONTROL_H_ + diff --git a/inc/FAppNotificationManager.h b/inc/FAppNotificationManager.h new file mode 100755 index 0000000..bd5b8db --- /dev/null +++ b/inc/FAppNotificationManager.h @@ -0,0 +1,650 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppNotificationManager.h + * @brief This is the header file for the %NotificationManager class. + * + * This header file contains the declarations of the %NotificationManager class. + */ + +#ifndef _FAPP_NOTIFICATION_MANAGER_H_ +#define _FAPP_NOTIFICATION_MANAGER_H_ + +#include +#include + +namespace Tizen { namespace App +{ + +/** + * @if OSPDEPREC + * The maximum length of the notification message. + * + * @brief [Deprecated] + * + * @deprecated This variable is deprecated. Instead of using this variable, use the Tizen::Shell::MAX_NOTIFICATION_MESSAGE_LENGTH variable. + * @since 2.0 + * @endif + */ +static const int MAX_NOTIFICATION_MESSAGE_LENGTH = 127; + +/** + * @if OSPDEPREC + * The maximum length of the launch arguments for the notification in bytes. + * + * @brief [Deprecated] + * + * @deprecated This variable is deprecated. Instead of using this variable, use the Tizen::Shell::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH variable. + * @since 2.0 + * @endif + */ +static const int MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH = 1024; + +/** + * @if OSPDEPREC + * The maximum length of the notification badge number. + * + * @brief [Deprecated] + * + * @deprecated This variable is deprecated. Instead of using this variable, use the Tizen::Shell::MAX_NOTIFICATION_BADGE_NUMBER variable. + * @since 2.0 + * @endif + */ +static const int MAX_NOTIFICATION_BADGE_NUMBER = 999; + +/* + * The maximum length of the title text. + * + * @since 2.0 + */ +static const int MAX_NOTIFICATION_TITLE_LENGTH = 1024; + +/* + * @enum OngoingActivityType + * + * Defines the ongoing activity notification type. + * + * @since 2.0 + */ +enum OngoingActivityType +{ + ONGOING_ACTIVITY_TYPE_TEXT = 1, /**< The text type */ + ONGOING_ACTIVITY_TYPE_PROGRESS_BYTE, /**< The progress type in byte */ + ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE /**< The progress type in percentage */ +}; + + +/** + * @if OSPDEPREC + * @class NotificationManager + * @brief [Deprecated] This class provides methods to alert the user about a notification. + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %NotificationManager class provides methods to alert the user about a notification. + * @n + * For more information about the class features, see Notifications. + * + * The following example demonstrates how to use the %NotificationManager class. + * + * @code + * + * result + * MyClass::NotificationSample(void) + * { + * int badgeNumber; + * NotificationManager* pNotiMgr = new NotificationManager(); + * pNotiMgr->Construct(); + * badgeNumber = pNotiMgr->GetBadgeNumber(); + * badgeNumber++; + * pNotiMgr->Notify(L"A new message has arrived.", badgeNumber); + * + * } + * + * @endcode + * @endif + */ +class _OSP_EXPORT_ NotificationManager + : public Tizen::Base::Object +{ + +public: + /** + * @if OSPDEPREC + * This is the default constructor for this class. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @endif + */ + NotificationManager(void); + + /** + * @if OSPDEPREC + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @endif + */ + virtual ~NotificationManager(void); + + /** + * @if OSPDEPREC + * Initializes this instance of %NotificationManager. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @endif + */ + result Construct(void); + + /** + * @if OSPDEPREC + * Gets the current badge number of the application icon. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return The current badge number + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OBJ_NOT_FOUND The application is not installed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. @n + * In case of failure, this method returns @c -1. + * @endif + */ + int GetBadgeNumber(void); + + /** + * @if OSPDEPREC + * Notifies the user using a badge number. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return An error code + * @param[in] badgeNumber The badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the specified @c badgeNumber is less than @c 0. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the %Tizen platform policy. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result Notify(int badgeNumber); + + /** + * @if OSPDEPREC + * Notifies the user using a message. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return An error code + * @param[in] messageText The notification message + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the %Tizen platform policy. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result Notify(const Tizen::Base::String& messageText); + + /** + * @if OSPDEPREC + * Notifies the user using a message and badge number. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return An error code + * @param[in] messageText The notification message + * @param[in] badgeNumber The badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c badgeNumber is less than @c 0, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the %Tizen platform policy. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result Notify(const Tizen::Base::String& messageText, int badgeNumber); + + /** + * @if OSPDEPREC + * Notifies the user using a message and badge number. @n + * If the user checks the message, @c launchArguments is delivered to the application. @n + * @c launchArguments is delivered as the value of the http://tizen.org/appcontrol/data/notification key + * for IAppControlProviderEventListener::OnAppControlRequestReceived(). + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return An error code + * @param[in] messageText The notification message + * @param[in] badgeNumber The badge number + * @param[in] launchArguments The message for application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The specified @c badgeNumber is less than @c 0. @n + * - The length of the specified @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of the specified @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the %Tizen platform policy. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @see IAppControlProviderEventListener::OnAppControlRequestReceived() + * @endif + */ + result Notify(const Tizen::Base::String& messageText, int badgeNumber, const Tizen::Base::String& launchArguments); + + /** + * @if OSPDEPREC + * Removes the notification message. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks This method returns @c E_SUCCESS when there is no outstanding notification. + * @endif + */ + result RemoveNotification(void); + + /** + * @if OSPDEPREC + * Notifies the user about the ongoing activity using a message. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return An error code + * @param[in] messageText The notification message + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the %Tizen platform policy. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result NotifyOngoingActivity(const Tizen::Base::String& messageText); + + /** + * @if OSPDEPREC + * Notifies the user about the ongoing activity using a message. @n + * @c launchArguments is delivered as the value of the http://tizen.org/appcontrol/data/notification key + * for IAppControlProviderEventListener::OnAppControlRequestReceived(). + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return An error code + * @param[in] messageText The notification message + * @param[in] launchArguments The launch arguments for the application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The length of the specified @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of the specified @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the %Tizen platform policy. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result NotifyOngoingActivity(const Tizen::Base::String& messageText, const Tizen::Base::String& launchArguments); + + /** + * @if OSPDEPREC + * Removes the notification message for the ongoing activity. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The method returns @c E_SUCCESS when there is no outstanding notification. + * @endif + */ + result RemoveOngoingActivityNotification(void); + + /** + * @if OSPDEPREC + * Gets the badge number of the application icon. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * @privilege %http://tizen.org/privilege/notification + * + * @return The current badge number + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OBJ_NOT_FOUND The application is not installed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. @n + * In case of failure, this method returns @c -1. + * @endif + */ + int GetBadgeNumber(const AppId& appId); + + /** + * @if OSPDEPREC + * @if VISPARTNER + * Notifies the user using a badge number on behalf of the specified application. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/notificationmanager + * + * @return An error code + * @param[in] appId The application ID + * @param[in] badgeNumber The badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c badgeNumber is less than @c 0. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to receive any notification as per the %Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + * @endif + */ + result NotifyOnBehalf(const AppId& appId, int badgeNumber); + + /** + * @if OSPDEPREC + * @if VISPARTNER + * Notifies the user using a message on behalf of the specified application. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/notificationmanager + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to receive any notification as per the %Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + * @endif + */ + result NotifyOnBehalf(const AppId& appId, const Tizen::Base::String& messageText); + + /** + * @if OSPDEPREC + * @if VISPARTNER + * Notifies the user using a message and badge number on behalf of the specified application. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/notificationmanager + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @param[in] badgeNumber The badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The specified @c badgeNumber is less than @c 0. @n + * - The length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to receive any notification as per the %Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + * @endif + */ + result NotifyOnBehalf(const AppId& appId, const Tizen::Base::String& messageText, int badgeNumber); + + /** + * @if OSPDEPREC + * @if VISPARTNER + * Notifies the user using a message and badge number on behalf of the specified application. @n + * If the user checks the message, the @c launchArguments is delivered to the application. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/notificationmanager + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @param[in] launchArguments The launch arguments for the application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The length of the specified @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of the specified @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to receive any notification as per the %Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + * @endif + */ + result NotifyOnBehalf(const AppId& appId, const Tizen::Base::String& messageText, const Tizen::Base::String& launchArguments); + + /** + * @if OSPDEPREC + * @if VISPARTNER + * Notifies the user about the ongoing activity using a message on behalf of the specified application. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/notificationmanager + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the %Tizen platform policy. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + * @endif + */ + result NotifyOngoingActivityOnBehalf(const AppId& appId, const Tizen::Base::String& messageText); + + /** + * @if OSPDEPREC + * @if VISPARTNER + * Notifies the user about the ongoing activity using a message on behalf of the specified application. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/notificationmanager + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @param[in] launchArguments The launch arguments for application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the %Tizen platform policy. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + * @endif + */ + result NotifyOngoingActivityOnBehalf(const AppId& appId, const Tizen::Base::String& messageText, const Tizen::Base::String& launchArguments); + + /** + * @if OSPDEPREC + * @if VISPARTNER + * Removes the notification message for ongoing activity on behalf of the specified application. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/notificationmanager + * + * @return An error code + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks Although there is no outstanding notification for the calling application, this method returns @c E_SUCCESS. + * @endif + * @endif + */ + result RemoveOngoingActivityNotificationOnBehalf(const AppId& appId); + + /** + * @if OSPDEPREC + * @if VISPARTNER + * Removes the notification message on behalf of the specified application. + * + * @brief [Deprecated] + * + * @deprecated This class is deprecated. Instead of using this class, use the Tizen::Shell::NotificationManager class. + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/notificationmanager + * + * @return An error code + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks Although there is no outstanding notification for the calling application, this method returns @c E_SUCCESS. + * @endif + * @endif + */ + result RemoveNotificationOnBehalf(const AppId& appId); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + NotificationManager(const NotificationManager& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + NotificationManager& operator =(const NotificationManager& rhs); + +private: + class _NotificationManagerImpl * __pNotificationManagerImpl; + + friend class _NotificationManagerImpl; +}; // NotificationManager + +} } // Tizen::App + +#endif // _FAPP_NOTIFICATION_MANAGER_H_ diff --git a/inc/FAppPkg.h b/inc/FAppPkg.h new file mode 100644 index 0000000..a3d2587 --- /dev/null +++ b/inc/FAppPkg.h @@ -0,0 +1,53 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppPkg.h + * @brief This is the header file for the %Package namespace. + * + * This header file contains the declarations and descriptions of the %Package namespace. + * + */ + +#ifndef _FAPP_PKG_H_ +#define _FAPP_PKG_H_ + +#include +#include +#include +#include +#include +#include + +/** + * @namespace Tizen::App::Package + * @brief This namespace contains classes and interfaces for a package. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %Package namespace contains classes and interfaces for information of packages and management of its installation or uninstallation. + * @image html app_package_namespace_classdiagram.png + */ + +namespace Tizen { namespace App { namespace Package +{ + +}}} // Tizen::App::Package + +#endif // _FAPP_PKG_H_ diff --git a/inc/FAppPkgIPackageInstallationEventListener.h b/inc/FAppPkgIPackageInstallationEventListener.h new file mode 100644 index 0000000..d1ce3e3 --- /dev/null +++ b/inc/FAppPkgIPackageInstallationEventListener.h @@ -0,0 +1,136 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppPkgIPackageInstallationEventListener.h + * @brief This is the header file for the %IPackageInstallationEventListener interface. + * + * This header file contains the declarations of the %IPackageInstallationEventListener interface. + */ + +#ifndef _FAPP_PKG_IPACKAGE_INSTALLATION_EVENT_LISTENER_H_ +#define _FAPP_PKG_IPACKAGE_INSTALLATION_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace App { namespace Package +{ +/** + * @enum PackageInstallationResult + * + * Defines the result of package installation. + * + * @since 2.0 + */ +enum PackageInstallationResult +{ + PACKAGE_INSTALLATION_RESULT_SUCCESS = 0, /**< Success */ + PACKAGE_INSTALLATION_RESULT_INVALID_PACKAGE, /**< An invalid package */ + PACKAGE_INSTALLATION_RESULT_STORAGE_FULL, /**< The installation target storage is full. */ +}; + +/** +* @interface IPackageInstallationEventListener +* @brief This interface defines a listener for a package installation and uninstallation. +* +* @since 2.0 +* +* The %IPackageInstallationEventListener interface defines a listener for a package installation and uninstallation. +*/ +class _OSP_EXPORT_ IPackageInstallationEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IPackageInstallationEventListener(void) {} + + /** + * Called when a package installation is completed. @n + * The value of @c installationResult is @c PACKAGE_INSTALLATION_RESULT_SUCCESS if the installation is successful. + * + * @since 2.0 + * + * @param[in] packageId The package ID + * @param[in] installationResult The installation result + */ + virtual void OnPackageInstallationCompleted(const PackageId& packageId, PackageInstallationResult installationResult) = 0; + + /** + * Called when a package uninstallation is completed. @n + * The value of @c uninstallationResult is @c true if the uninstallation is successful, else @c false. + * + * @since 2.0 + * + * @param[in] packageId The package ID + * @param[in] uninstallationResult Set to @c true if the uninstallation is successful, @n + * else @c false + */ + virtual void OnPackageUninstallationCompleted(const PackageId& packageId, bool uninstallationResult) = 0; + + /** + * Called when a package installation is in progress. + * + * @since 2.0 + * + * @param[in] packageId The package ID + * @param[in] progress The progress of an installation in percentage + */ + virtual void OnPackageInstallationInProgress(const PackageId& packageId, int progress) = 0; + + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageInstallationEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageInstallationEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageInstallationEventListener_Reserved3(void) {} + +}; // IPackageInstallationEventListener + +} } } // Tizen::App::Package + +#endif // _FAPP_PKG_IPACKAGE_INSTALLATION_EVENT_LISTENER_H_ diff --git a/inc/FAppPkgIPackageInstallationResponseListener.h b/inc/FAppPkgIPackageInstallationResponseListener.h new file mode 100644 index 0000000..5fd46d6 --- /dev/null +++ b/inc/FAppPkgIPackageInstallationResponseListener.h @@ -0,0 +1,130 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @if VISPARTNER-OPERATOR + * @file FAppPkgIPackageInstallationResponseListener.h + * @brief This is the header file for the %IPackageInstallationResponseListener interface. + * + * This header file contains the declarations of the %IPackageInstallationResponseListener interface. + * + * @endif + */ +#ifndef _FAPP_PKG_IPACKAGE_INSTALLATION_RESPONSE_LISTENER_H_ +#define _FAPP_PKG_IPACKAGE_INSTALLATION_RESPONSE_LISTENER_H_ + +#include +#include +#include + +namespace Tizen { namespace App { namespace Package +{ + +/** + * @if VISPARTNER-OPERATOR + * @interface IPackageInstallationResponseListener + * @brief This interface defines a listener for the asynchronous package installation operation. + * + * @since 2.0 + * @visibility partner-operator + * + * The %IPackageInstallationResponseListener interface defines a listener for the asynchronous package installation operation. + * + * @endif + */ +class _OSP_EXPORT_ IPackageInstallationResponseListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * @if VISPARTNER-OPERATOR + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + * @visibility partner-operator + * + * @endif + */ + virtual ~IPackageInstallationResponseListener(void) {} + + /** + * @if VISPARTNER-OPERATOR + * Called when a package installation is completed. @n + * The value of @c installationResult is @c PACKAGE_INSTALLATION_RESULT_SUCCESS if the installation is successful. + * + * @since 2.0 + * @visibility partner-operator + * + * @param[in] packageId The package ID + * @param[in] installationResult The installation result + * + * @endif + */ + virtual void OnPackageInstallationResponseReceived(const PackageId& packageId, PackageInstallationResult installationResult) = 0; + + /** + * @if VISPARTNER-OPERATOR + * Called when a package installation is in progress. + * + * @since 2.0 + * @visibility partner-operator + * + * @param[in] packageId The package ID + * @param[in] progress The progress of an installation in percentage + * + * @endif + */ + virtual void OnPackageInstallationInProgressResponseReceived(const PackageId& packageId, int progress) = 0; + + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageInstallationResponseListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageInstallationResponseListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageInstallationResponseListener_Reserved3(void) {} + +}; // IPackageInstallationResponseListener + +} } } // Tizen::App::Package + +#endif // _FAPP_PKG_IPACKAGE_INSTALLATION_RESPONSE_LISTENER_H_ diff --git a/inc/FAppPkgIPackageUninstallationResponseListener.h b/inc/FAppPkgIPackageUninstallationResponseListener.h new file mode 100644 index 0000000..2b25b9b --- /dev/null +++ b/inc/FAppPkgIPackageUninstallationResponseListener.h @@ -0,0 +1,117 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @if VISPARTNER-OPERATOR + * @file FAppPkgIPackageUninstallationResponseListener.h + * @brief This is the header file for the %IPackageUninstallationResponseListener interface. + * + * This header file contains the declarations of the %IPackageUninstallationResponseListener interface. + * + * @endif + */ +#ifndef _FAPP_PKG_IPACKAGE_UNINSTALLATION_RESPONSE_LISTENER_H_ +#define _FAPP_PKG_IPACKAGE_UNINSTALLATION_RESPONSE_LISTENER_H_ + +#include +#include +#include + +namespace Tizen { namespace App { namespace Package +{ + +/** + * @if VISPARTNER-OPERATOR + * @interface IPackageUninstallationResponseListener + * @brief This interface defines a listener for the asynchronous package uninstallation operation. + * + * @since 2.0 + * @visibility partner-operator + * + * The %IPackageUninstallationResponseListener interface defines a listener for the asynchronous package uninstallation operation. + * + * @endif + */ +class _OSP_EXPORT_ IPackageUninstallationResponseListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * @if VISPARTNER-OPERATOR + * This polymorphic destructor should be overridden if required. + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + * @visibility partner-operator + * + * @endif + */ + virtual ~IPackageUninstallationResponseListener(void) {} + + /** + * @if VISPARTNER-OPERATOR + * Called when a package uninstallation is completed. @n + * The value of @c uninstallationResult is @c true if the uninstallation is successful, else @c false. + * + *@since 2.0 + * @visibility partner-operator + * + * @param[in] packageId The package ID + * @param[in] uninstallationResult Set to @c true if the uninstallation is successful, @n + * else @c false + * + * @endif + */ + virtual void OnPackageUninstallationResponseReceived(const PackageId& packageId, bool uninstallationResult) = 0; + + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageUninstallationResponseListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageUninstallationResponseListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void IPackageUninstallationResponseListener_Reserved3(void) {} + +}; // IPackageUninstallationResponseListener + +} } } // Tizen::App::Package + +#endif // _FAPP_PKG_IPACKAGE_UNINSTALLATION_RESPONSE_LISTENER_H_ diff --git a/inc/FAppPkgPackageAppInfo.h b/inc/FAppPkgPackageAppInfo.h new file mode 100755 index 0000000..3a10c76 --- /dev/null +++ b/inc/FAppPkgPackageAppInfo.h @@ -0,0 +1,188 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppPkgPackageAppInfo.h + * @brief This is the header file for the %PackageAppInfo class. + * + * This header file contains the declarations of the %PackageAppInfo class. + */ + +#ifndef _FAPP_PKG_PACKAGE_APP_INFO_H_ +#define _FAPP_PKG_PACKAGE_APP_INFO_H_ + +#include +#include +#include + +namespace Tizen { namespace App { namespace Package +{ + +/** + * @class PackageAppInfo + * @brief This class represents the information of the application in package. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %PackageAppInfo class provides the information of the application in package. + * + */ +class _OSP_EXPORT_ PackageAppInfo + : public Tizen::Base::Object +{ +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~PackageAppInfo(void); + + /** + * Gets an application ID. + * + * @since 2.0 + * + * @return An application ID + */ + AppId GetAppId(void) const; + + /** + * Gets the name of an application. + * + * @since 2.0 + * + * @return The name of an application + */ + Tizen::Base::String GetAppName(void) const; + + /** + * Gets the display name of an application. + * + * @since 2.0 + * + * @return The display name of an application + */ + Tizen::Base::String GetAppDisplayName(void) const; + + /** + * @if VISPARTNER-MANUFACTURER + * Gets the menu icon path of an application. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/packagesetting + * + * @return The menu icon path of an application, @n + * else an empty string is returned if there is no value + * @endif + */ + Tizen::Base::String GetAppMenuIconPath(void) const; + + /** + * @if VISPARTNER-MANUFACTURER + * Gets the setting icon path of an application. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/packagesetting + * + * @return The setting icon path of an application, @n + * else an empty string is returned if there is no value + * @endif + */ + Tizen::Base::String GetAppSettingIconPath(void) const; + + /** + * @if VISPARTNER-MANUFACTURER + * Gets the notification icon path of an application. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/packagesetting + * + * @return The notification icon path of an application, @n + * else an empty string is returned if there is no value + * @endif + */ + Tizen::Base::String GetAppNotificationIconPath(void) const; + + /** + * Gets the category list of an application. + * + * @since 2.0 + * + * @return A pointer to the list of the Tizen::Base::String instances, @n + * else @c null if it fails + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetAppCategoryListN(void) const; + + /** + * Checks whether an application is visible on the menu. + * + * @since 2.0 + * + * @return @c true if an application is visible on the menu, @n + * else @c false + * @remarks If the return value is @c false, it is recommended not to display the application on the menu. + */ + bool IsMenuIconVisible(void) const; + + /** + * Checks whether an application is the main application of the package. + * + * @since 2.0 + * + * @return @c true if an application is the main application of the package, @n + * else @c false + */ + bool IsMainApp(void) const; + +private: + /** + * This is the default constructor for this class. This default constructor is intentionally + declared as private so that only the platform can create an instance. + */ + PackageAppInfo(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + PackageAppInfo(const PackageAppInfo& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + PackageAppInfo& operator =(const PackageAppInfo& rhs); + +private: + class _PackageAppInfoImpl* __pPackageAppInfoImpl; + + friend class _PackageAppInfoImpl; + friend class _PackageInfoImpl; + friend class _PackageManagerImpl; + +}; // PackageAppInfo + +} } } // Tizen::App::Package + +#endif // _FAPP_PKG_PACKAGE_APP_INFO_H_ diff --git a/inc/FAppPkgPackageInfo.h b/inc/FAppPkgPackageInfo.h new file mode 100755 index 0000000..940d80f --- /dev/null +++ b/inc/FAppPkgPackageInfo.h @@ -0,0 +1,266 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppPkgPackageInfo.h + * @brief This is the header file for the %PackageInfo class. + * + * This header file contains the declarations of the %PackageInfo class. + */ + +#ifndef _FAPP_PKG_PACKAGE_INFO_H_ +#define _FAPP_PKG_PACKAGE_INFO_H_ + +#include +#include +#include + +namespace Tizen { namespace App { namespace Package +{ + +/** + * @class PackageInfo + * @brief This class represents the information of a package. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %PackageInfo class provides the information of a package. + * + */ +class _OSP_EXPORT_ PackageInfo + : public Tizen::Base::Object +{ +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~PackageInfo(void); + + /** + * Gets a package ID. + * + * @since 2.0 + * + * @return A package ID + */ + PackageId GetId(void) const; + + /** + * Gets the version of a package. + * + * @since 2.0 + * + * @return The version of a package + */ + Tizen::Base::String GetVersion(void) const; + + /** + * Gets the display name of a package. + * + * @since 2.0 + * + * @return The display name of a package + */ + Tizen::Base::String GetDisplayName(void) const; + + /** + * Gets the description of a package. + * + * @since 2.0 + * + * @return The description of a package, @n + * else an empty string is returned if there is no value + */ + Tizen::Base::String GetDescription(void) const; + + /** + * Gets the author of a package. + * + * @since 2.0 + * + * @return The author of a package, @n + * else an empty string is returned if there is no value + */ + Tizen::Base::String GetAuthor(void) const; + + /** + * Gets the URL of a package. + * + * @since 2.0 + * + * @return The URL of a package, @n + * else an empty string is returned if there is no value + */ + Tizen::Base::String GetUrl(void) const; + + /** + * Gets the date and time when a package is installed. + * + * @since 2.0 + * + * @return An instance of Tizen::Base::DateTime when a package is installed + */ + Tizen::Base::DateTime GetInstallationTime(void) const; + + /** + * Checks whether a package is installed in the external storage. + * + * @since 2.0 + * + * @return @c true if a package is installed in the external storage, @n + * else @c false + */ + bool IsInstalledInExternalStorage(void) const; + + /** + * Checks whether it is possible to uninstall a package. + * + * @since 2.0 + * + * @return @c true if it is possible to uninstall a package, @n + * else @c false + */ + bool IsUninstallable(void) const; + + /** + * Checks whether it is possible to move a package to either internal or external storage. + * + * @since 2.0 + * + * @return @c true if it is possible to move a package to either internal or external storage, @n + * else @c false + */ + bool IsMovable(void) const; + + /** + * Checks whether a package is downloaded. + * + * @since 2.0 + * + * @return @c true if a package is downloaded, @n + * else @c false + */ + bool IsDownloaded(void) const; + + /** + * Gets the size of a package. + * + * @since 2.0 + * + * @return The size of a package + */ + long long GetSize(void) const; + + /** + * Gets the data size of a package. + * + * @since 2.0 + * + * @return The data size of a package + */ + long long GetDataSize(void) const; + + /** + * Gets the main application ID of a package. + * + * @since 2.0 + * + * @return The main application ID + */ + AppId GetMainAppId(void) const; + + /** + * Gets the store client package ID that installed the package. + * + * @since 2.0 + * + * @return The store client package ID + */ + PackageId GetStoreClientId(void) const; + + /** + * Gets the application information list of a package. + * + * @since 2.0 + * + * @return A pointer to the list of the PackageAppInfo instances + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetPackageAppInfoListN(void) const; + + /** + * Gets the application information with the specific application ID. + * + * @since 2.0 + * + * @return A pointer to PackageAppInfo + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OBJ_NOT_FOUND The application information is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::App::Package::PackageAppInfo* GetPackageAppInfoN(const AppId& appId) const; + + /** + * @if VISPARTNER-MANUFACTURER + * Gets the type of a package. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/packagesetting + * + * @return The package type + * @endif + */ + PackageType GetType(void) const; + +private: + /** + * This is the default constructor for this class. This default constructor is intentionally + declared as private so that only the platform can create an instance. + */ + PackageInfo(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + PackageInfo(const PackageInfo& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + PackageInfo& operator =(const PackageInfo& rhs); + +private: + class _PackageInfoImpl * __pPackageInfoImpl; + + friend class _PackageInfoImpl; + friend class _PackageManagerImpl; + +}; // PackageInfo + +} } } // Tizen::App::Package + +#endif // _FAPP_PKG_PACKAGE_INFO_H_ diff --git a/inc/FAppPkgPackageManager.h b/inc/FAppPkgPackageManager.h new file mode 100755 index 0000000..7d08468 --- /dev/null +++ b/inc/FAppPkgPackageManager.h @@ -0,0 +1,314 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppPkgPackageManager.h + * @brief This is the header file for the %PackageManager class. + * + * This header file contains the declarations of the %PackageManager class. + */ + +#ifndef _FAPP_PKG_PACKAGE_MANAGER_H_ +#define _FAPP_PKG_PACKAGE_MANAGER_H_ + +#include +#include + +namespace Tizen { namespace App { namespace Package +{ + +class PackageInfo; +class PackageAppInfo; +class IPackageInstallationEventListener; +class IPackageInstallationResponseListener; +class IPackageUninstallationResponseListener; + +/** + * @if VISPARTNER-MANUFACTURER + * @enum PackageType + * + * Defines the package types. + * + * @since 2.0 + * @visibility partner-manufacturer + * @endif + */ +enum PackageType +{ + PACKAGE_TYPE_TPK, /**< TIZEN Native package */ + PACKAGE_TYPE_WGT, /**< TIZEN %Web package */ + PACKAGE_TYPE_RPM, /**< TIZEN Core package */ +}; + +/** + * @class PackageManager + * @brief This class gets the information of packages and manages package installation or uninstallation. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %PackageManager class provides methods to install or uninstall the packages, retrieves the information of the packages that are installed on the device. + */ +class _OSP_EXPORT_ PackageManager + : public Tizen::Base::Object +{ +public: + /** + * Gets the package ID from the application ID. + * + * @since 2.0 + * + * @return The package ID, @n + * else @c packageId.IsEmtpy() == true is returned if an error occurs + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static PackageId GetPackageIdByAppId(const AppId& appId); + + /** + * Adds a package installation event listener. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/packageinfo + * + * @return An error code + * @param[in] listener The package installation event listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_ALREADY_EXIST The listener is already added. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + result AddPackageInstallationEventListener(IPackageInstallationEventListener& listener); + + /** + * Removes a package installation event listener. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/packageinfo + * + * @return An error code + * @param[in] listener The package installation event listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The listener is not added or is already removed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + result RemovePackageInstallationEventListener(IPackageInstallationEventListener& listener); + + /** + * Gets a package information with the specific package ID. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/packageinfo + * + * @return A pointer to PackageInfo + * @param[in] packageId The package ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PKG_NOT_INSTALLED The package is not installed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::App::Package::PackageInfo* GetPackageInfoN(const PackageId& packageId) const; + + /** + * Gets the application information with the specific application ID. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/packageinfo + * + * @return A pointer to PackageAppInfo + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::App::Package::PackageAppInfo* GetPackageAppInfoN(const AppId& appId) const; + + /** + * Gets the package information list. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/packageinfo + * + * @return A pointer to the list of the PackageInfo instances, @n + * else @c null if it fails + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetPackageInfoListN(void) const; + + /** + * Checks whether a package is installed. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/packageinfo + * + * @return @c true if a package is installed, @n + * else @c false + * @param[in] packageId The package ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + bool IsPackageInstalled(const PackageId& packageId) const; + + /** + * @if VISPARTNER-OPERATOR + * Installs a package. @n + * The %InstallPackage() method operates asynchronously, that is, it ends immediately without an installation response. The application is notified when the installation is completed, so the response is available through the IPackageInstallationResponseListener::OnPackageInstallationCompleted() method, if this method returns @c E_SUCCESS. + * + * @since 2.0 + * @visibility partner-operator + * @privilege %http://tizen.org/privilege/packagemanager.install + * + * @return An error code + * @param[in] packageId The package ID + * @param[in] packagePath The package path + * @param[in] pListener The response listener + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks A listener instance ownership is transferred to the platform. After notifying result, the listener instance is removed automatically. A reuse of the listener instance is not allowed. + * @see IPackageInstallationResponseListener + * @endif + */ + result InstallPackage(const PackageId& packageId, const Tizen::Base::String& packagePath, IPackageInstallationResponseListener* pListener); + + /** + * @if VISPARTNER-OPERATOR + * Uninstalls a package with the specified package ID. @n + * The %UninstallPackage() method operates asynchronously, that is, it ends immediately without an uninstallation response. The application is notified when the uninstallation is completed, so the response is available through the IPackageUninstallationResponseListener::OnPackageUninstallationCompleted() method, if this method returns @c true. + * + * @since 2.0 + * @visibility partner-operator + * @privilege %http://tizen.org/privilege/packagemanager.install + * + * @return An error code + * @param[in] packageId The package ID + * @param[in] pListener The response listener + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PKG_NOT_INSTALLED The package is not installed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks A listener instance ownership is transferred to the platform. After notifying result, the listener instance is removed automatically. A reuse of the listener instance is not allowed. + * @see IPackageUninstallationResponseListener + * @endif + */ + result UninstallPackage(const PackageId& packageId, IPackageUninstallationResponseListener* pListener); + + /** + * @if VISPARTNER-MANUFACTURER + * Moves a package with the specified package ID to an external storage. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/packagesetting + * + * @return An error code + * @param[in] packageId The package ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_INVALID_OPERATION The package is already installed in an external storage. + * @exception E_STORAGE_FULL The storage is full. + * @exception E_PKG_NOT_INSTALLED The package is not installed. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result MoveToExternalStorage(const PackageId& packageId); + + /** + * @if VISPARTNER-MANUFACTURER + * Moves a package with the specified package ID to an internal storage. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/packagesetting + * + * @return An error code + * @param[in] packageId The package ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_INVALID_OPERATION The package is already installed in an internal storage. + * @exception E_STORAGE_FULL The storage is full. + * @exception E_PKG_NOT_INSTALLED The package is not installed. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result MoveToInternalStorage(const PackageId& packageId); + + /** + * Gets the package manager instance. + * + * @since 2.0 + * + * @return A pointer to the %PackageManager instance, @n + * else @c null + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static PackageManager* GetInstance(void); + +private: + /** + * This default constructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + PackageManager(void); + + /** + * This destructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + */ + virtual ~PackageManager(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + PackageManager(const PackageManager& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + PackageManager& operator =(const PackageManager& rhs); + +private: + class _PackageManagerImpl* __pPackageManagerImpl; + friend class _PackageManagerImpl; + +}; // PackageManager + +} } } // Tizen::App::Package + +#endif // _FAPP_PKG_PACKAGE_MANAGER_H_ diff --git a/inc/FAppService.h b/inc/FAppService.h new file mode 100644 index 0000000..4ce919c --- /dev/null +++ b/inc/FAppService.h @@ -0,0 +1,30 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppService.h + * @brief This is the header file of the deprecated %Service class. + * + * This header file contains the declarations of the deprecated %Service class. + */ + +#ifndef _FAPP_SERVICE_H_ +#define _FAPP_SERVICE_H_ + +#include + +#endif // _FAPP_SERVICE_H_ diff --git a/inc/FAppServiceApp.h b/inc/FAppServiceApp.h new file mode 100644 index 0000000..2599850 --- /dev/null +++ b/inc/FAppServiceApp.h @@ -0,0 +1,151 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppServiceApp.h + * @brief This is the header file for the %ServiceApp class. + * + * This header file contains the declarations of the %ServiceApp class. + */ + +#ifndef _FAPP_SERVICE_APP_H_ +#define _FAPP_SERVICE_APP_H_ + +#include + +namespace Tizen { namespace Base { namespace Collection { class IList; } } } + +namespace Tizen { namespace App +{ + +class ServiceApp; + +typedef ServiceApp* (*ServiceAppInstanceFactory)(void); + +/** + * @class ServiceApp + * @brief This class is the base class of a %Tizen native service application. + * + * @since 2.0 + * + * The %ServiceApp class is the base class of a %Tizen native service application which has no UI. + * A %Tizen native service application must inherit from the %ServiceApp class. This class provides the basic features necessary to define the + * %Tizen native service application. + * @n + * For more information on the class features, see App Guide and Native Application Model. + * + */ +class _OSP_EXPORT_ ServiceApp + : public Tizen::App::App +{ +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~ServiceApp(void); + + /** + * Gets the %ServiceApp instance's pointer. + * + * @since 2.0 + * + * @return A pointer to the %ServiceApp instance, @n + * else @c null if it fails + */ + static ServiceApp* GetInstance(void); + + /** + * Executes an application implemented by inheriting this class. + * This method must be called from the entry method - OspMain(), which is generated by IDE. + * + * @since 2.0 + * + * @return An error code + * @param[in] pServiceAppFactory The factory method that creates this %ServiceApp's instance + * @param[in] pArguments The launch arguments for %App + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INIT_FAILED The initialization failure during OnAppInitializing(). + * @exception E_SYSTEM A system error has occurred. + */ + static result Execute(ServiceAppInstanceFactory pServiceAppFactory, const Tizen::Base::Collection::IList* pArguments); + +protected: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + ServiceApp(void); + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void ServiceApp_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void ServiceApp_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void ServiceApp_Reserved3(void) {} + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + ServiceApp(const ServiceApp& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + ServiceApp& operator =(const ServiceApp& rhs); + +private: + class _ServiceAppImpl* __pServiceAppImpl; +}; // ServiceApp + +typedef ServiceApp Service; + +} } // Tizen::App + +#endif // _FAPP_SERVICE_APP_H_ diff --git a/inc/FAppSqlDataControl.h b/inc/FAppSqlDataControl.h new file mode 100644 index 0000000..f5445ab --- /dev/null +++ b/inc/FAppSqlDataControl.h @@ -0,0 +1,259 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FAppSqlDataControl.h +* @brief This is the header file for the %SqlDataControl class. +* +* This header file contains the declarations of the %SqlDataControl class. +*/ + +#ifndef _FAPP_SQL_DATA_CONTROL_H_ +#define _FAPP_SQL_DATA_CONTROL_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +class String; +namespace Collection { +class IList; +class IMap; +} +}} + +namespace Tizen { namespace App +{ + +class _SqlDataControlImpl; +class ISqlDataControlResponseListener; + +/** + * @class SqlDataControl + * @brief This class represents the SQL-type data control behavior. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %SqlDataControl class represents the data control behavior, that provides a standard mechanism + * for accessing specific data exported by other applications. + * Data control provider can share its own data to data control consumers. + * + * For more information on the class features, see Data Controls. + * + * @see Tizen::App::AppManager + */ + +class _OSP_EXPORT_ SqlDataControl + : public Tizen::Base::Object +{ + +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~SqlDataControl(void); + + /** + * Selects the specified columns to be queried. @n + * The result set of the specified columns is retrieved from a table owned by an SQL-type data control provider. @n + * The %Select() method is asynchronous. + * For receiving the response from the data control provider, set the listener with + * SqlDataControl::SetSqlDataControlResponseListener(). @n + * When the requested result set has been received from the data control provider, + * the ISqlDataControlResponseListener::OnSqlDataControlSelectResponseReceived() method is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] dataId A string for identifying specific data, usually a database table to query from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] pColumnList A list of column names to query @n + * The type of objects contained in the specified @c pColumnList must be + * Tizen::Base::String class. + * If the specified @c pColumnList is @c null, all columns are selected. + * @param[in] pWhere A filter to select desired rows to query @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * @param[in] pOrder The sorting order of rows to query @n + * It is an SQL 'ORDER BY' clause excluding the 'ORDER BY' itself. + * @param[out] reqId The request ID + * @param[in] pageNo The page number of the result set @n It starts from @c 1. + * @param[in] countPerPage The desired maximum count of rows on a page + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_INVALID_ARG Either of the following conditions has occurred: + * - The specified @c pColumnList is empty. + * - The specified @c pageNo parameter is less than @c 1. + * - The specified @c countPerPage parameter is less than @c 1. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks If the value specified in the @c pWhere is string, the value must be wrapped in + * single quotes. Otherwise it is not needed to wrap the numeric value in single quotes. + * For more information on the SQL statement, see SQLite SQL documents. + */ + result Select(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IList* pColumnList, + const Tizen::Base::String* pWhere, const Tizen::Base::String *pOrder, RequestId& reqId, + int pageNo = 1, int countPerPage = 20); + + /** + * Inserts new rows into a table owned by an SQL-type data control provider. @n + * The %Insert() method is asynchronous. + * For receiving the response from the data control provider, set the listener with + * SqlDataControl::SetSqlDataControlResponseListener(). @n + * When the response has been received from the data control provider, + * the ISqlDataControlResponseListener::OnSqlDataControlInsertResponseReceived() method is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] dataId A string for identifying specific data, usually a database table to insert into @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] insertMap The column-value pairs to insert @n + * The type of objects contained in the specified @c insertMap must be + * Tizen::Base::String class. + * @param[out] reqId The request ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_INVALID_ARG The specified @c insertMap is empty. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks If the value specified in the @c insertMap is string, the value must be wrapped in + * single quotes. Otherwise it is not needed to wrap the numeric value in single quotes. + * For more information on the SQL statement, see SQLite SQL documents. + */ + result Insert(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& insertMap, RequestId& reqId); + + /** + * Updates values of a table owned by an SQL-type data control provider. @n + * The %Update() method is asynchronous. + * For receiving the response from the data control provider, set the listener with + * SqlDataControl::SetSqlDataControlResponseListener(). @n + * When the response has been received from the data control provider, + * the ISqlDataControlResponseListener::OnSqlDataControlUpdateResponseReceived() method is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] dataId A string for identifying specific data, usually a database table to update @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] updateMap The column-value pairs to update @n + * The type of objects contained in the specified @c updateMap must be + * Tizen::Base::String class. @n + * @param[in] pWhere A filter to select desired rows to update @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * @param[out] reqId The request ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_INVALID_ARG The specified @c updateMap is empty. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks If the value specified in the @c pWhere or @c updateMap is string, the value must be wrapped in + * single quotes. Otherwise it is not needed to wrap the numeric value in single quotes. + * For more information on the SQL statement, see SQLITE SQL documents. + */ + result Update(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& updateMap, + const Tizen::Base::String* pWhere, RequestId& reqId); + + /** + * Deletes rows of a table owned by an SQL-type data control provider. @n + * The %Delete() method is asynchronous. + * For receiving the response from the data control provider, set the listener with + * SqlDataControl::SetSqlDataControlResponseListener(). @n + * When the response has been received from the data control provider, + * the ISqlDataControlResponseListener::OnSqlDataControlDeleteResponseReceived() method is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] dataId A string for identifying specific data, usually a database table to delete from @n + * The string consists of one or more components, separated by a slash('/'). + * @param[in] pWhere A filter to select desired rows to delete @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * If it is @c null, all rows are deleted. + * @param[out] reqId The request ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_INVALID_ARG A specified parameter is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks If the value specified in the @c pWhere is string, the value must be wrapped in + * single quotes. Otherwise it is not needed to wrap the numeric value in single quotes. + * For more information on the SQL statement, see SQLITE SQL documents. + */ + result Delete(const Tizen::Base::String& dataId, const Tizen::Base::String* pWhere, RequestId& reqId); + + /** + * Sets an SQL-type data control listener to this instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] pListener The data control callback listener @n + * Some data controls need to get the callback result by implementing + * the ISqlDataControlResponseListener interface. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been properly constructed. + * @exception E_SYSTEM A system error has occurred. + */ + result SetSqlDataControlResponseListener(ISqlDataControlResponseListener* pListener); + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + SqlDataControl(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * @remarks This constructor is hidden. + */ + SqlDataControl(const SqlDataControl& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * @remarks This operator is hidden. + */ + SqlDataControl& operator =(const SqlDataControl& rhs); + + class _SqlDataControlImpl* __pSqlDataControlImpl; + + friend class _SqlDataControlImpl; + +}; // SqlDataControl + +}} // Tizen::App + +#endif // _FAPP_SQL_DATA_CONTROL_H_ + diff --git a/inc/FAppTypes.h b/inc/FAppTypes.h new file mode 100644 index 0000000..7385171 --- /dev/null +++ b/inc/FAppTypes.h @@ -0,0 +1,143 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppTypes.h + * @brief This is the header file for the enumerations of the App class. + * + * This header file contains the declarations of the enumerations of the App class. + * @see Application + */ + +#ifndef _FAPP_TYPES_H_ +#define _FAPP_TYPES_H_ + +#include + +namespace Tizen { namespace App +{ + +/** + * The package ID + * + * @since 2.0 + */ +typedef Tizen::Base::String PackageId; + +/** + * The application ID + * + * @since 2.0 + */ +typedef Tizen::Base::String AppId; + +/** + * @if OSPDEPREC + * The application secret + * @brief [Deprecated] + * @deprecated This type is deprecated because the associated App::GetAppSecret() method is deprecated. + * + * @since 2.0 + * @endif + */ +typedef Tizen::Base::String AppSecret; + +/** + * @enum AppState + * Defines the various states of an application's life cycle. + * + * @since 2.0 + */ +enum AppState +{ + INITIALIZING, /**< The application has been launched */ + RUNNING, /**< The application has been initialized and is currently being executed */ + TERMINATING, /**< The application is about to exit and releases its resources and saves its preferences */ + TERMINATED /**< The application has been destroyed */ +}; + +/** + * @enum AppUiState + * Defines the UI state of an application. + * + * @since 2.0 + */ +enum AppUiState +{ + APP_UI_STATE_FOREGROUND = 0x01, /**< The application is completely visible on foreground */ + APP_UI_STATE_PARTIAL_BACKGROUND = 0x02, /**< The application is partially hidden by another window such as a system pop-up */ + APP_UI_STATE_BACKGROUND = 0x04 /**< The application is completely hidden by a full-screen window, usually by another application or an application control */ +}; + +/** + * @enum AppCtrlResult + * Defines the application control result. + * + * @since 2.0 + */ +enum AppCtrlResult +{ + APP_CTRL_RESULT_SUCCEEDED = 0x00, /**< The application operation is successful */ + APP_CTRL_RESULT_FAILED = 0x01, /**< The application operation has failed */ + APP_CTRL_RESULT_CANCELED = 0x02, /**< The application operation is canceled by the callee application */ + APP_CTRL_RESULT_TERMINATED = 0x04, /**< The callee application is terminated without sending the result */ + APP_CTRL_RESULT_ABORTED = 0x08, /**< The application operation is aborted by the platform */ +}; + +/** + * @if OSPDEPREC + * The application launch request ID. @n + * Represents the application launch arguments in App::App::OnUserEventReceivedN(). + * + * @brief [Deprecated] + * @deprecated This variable is deprecated. From %Tizen, App::App::OnUserEventReceivedN() + * is not invoked for the request from application and %AppLaunchRequestId is not used anymore. + * Instead, use IAppControlProviderEventListener. + * @since 2.0 + * + * @see App::App::OnUserEventReceivedN() + * @endif + */ +const long AppLaunchRequestId = (-0xFFFF); + +/** + * @if OSPDEPREC + * Defines the launch type - normal launch. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * Instead of using this variable, it is recommended to use IAppControlProviderEventListener to acquire the launch information. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APP_LAUNCH_NORMAL; + +/** + * @if OSPDEPREC + * Defines the launch type - conditional launch. + * + * @brief [Deprecated] + * @deprecated This variable is provided only for backward compatibility and will be deleted in the near future. + * Instead of using this variable, it is recommended to use IAppLaunchConditionEventListener to acquire the conditional launch information. + * @since 2.0 + * @endif + */ +_OSP_EXPORT_ extern const Tizen::Base::String APP_LAUNCH_CONDITIONAL; + +}} // Tizen::App + +#endif // _FAPP_TYPES_H_ diff --git a/inc/FAppUiApp.h b/inc/FAppUiApp.h new file mode 100644 index 0000000..a30d589 --- /dev/null +++ b/inc/FAppUiApp.h @@ -0,0 +1,300 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppUiApp.h + * @brief This is the header file for the %UiApp class. + * + * This header file contains the declarations of the %UiApp class. + */ + +#ifndef _FAPP_UI_APP_H_ +#define _FAPP_UI_APP_H_ + +#include + +namespace Tizen { namespace Base { namespace Collection { class IList; } } } +namespace Tizen { namespace Ui { namespace Controls { class Frame; } } } + +namespace Tizen { namespace App +{ + +class UiApp; +class IAppFrame; + +typedef UiApp* (*UiAppInstanceFactory)(void); + +/** + * @class UiApp + * @brief This class is the base class of a %Tizen native UI application. + * + * @since 2.0 + * + * The %UiApp class is the base class of a %Tizen native UI application. + * A %Tizen native UI application must inherit from the %UiApp class. This class provides the basic features necessary to define the + * Tizen native UI application. + * @n + * For more information on the class features, see App Guide and Native Application Model. + * + */ +class _OSP_EXPORT_ UiApp + : public Tizen::App::App +{ +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~UiApp(void); + + /** + * Gets the first frame in the frame list of the UI application. + * + * @since 2.0 + * + * @return A pointer to the IAppFrame interface of the frame, @n + * else @c null if it fails + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The frame has not been properly initialized. + * @exception E_OBJ_NOT_FOUND Frame is not found. + */ + IAppFrame* GetAppFrame(void) const; + + /** + * Adds the frame to the end of the list that is maintained by the UI application. + * + * @since 2.0 + * + * @return An error code + * @param[in] frame The frame that is added to the UI application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_INVALID_STATE The application is in an invalid state. + * @exception E_OBJ_ALREADY_EXIST The frame to be added is already registered with the UI application. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_MAX_EXCEEDED The number of frames has exceeded the maximum limit. + * @exception E_SYSTEM A system error has occurred. + */ + result AddFrame(const Tizen::Ui::Controls::Frame& frame); + + /** + * Removes the specified @c frame from the UI application. + * + * @since 2.0 + * + * @return An error code + * @param[in] frame The frame to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c frame cannot be found. + * @exception E_SYSTEM A system error has occurred. + * @remarks The removed frame is deleted from the memory. + */ + result RemoveFrame(const Tizen::Ui::Controls::Frame& frame); + + /** + * Gets the list of the frames of the UI application. + * + * @since 2.0 + * + * @return A pointer to Tizen::Base::Collection::IList that contains Tizen::Ui::Frame instances, @n + * else @c null if it fails + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The application is in an invalid state. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetFrameList(void) const; + + /** + * Gets the frame with the specified @c name. + * + * @since 2.0 + * + * @return A pointer to the frame having the specified @c name, @n + * else @c null if it fails + * @param[in] name The name of the frame + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c frame cannot be found. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Ui::Controls::Frame* GetFrame(const Tizen::Base::String& name) const; + + /** + * Gets the frame at the specified @c index of the list. + * + * @since 2.0 + * + * @return A pointer to the frame at the specified @c index, @n + * else @c null if it fails + * @param[in] index The index of the frame + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified @c index is outside the bounds of the frame list. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Ui::Controls::Frame* GetFrameAt(int index) const; + +/** + * Gets the UI state of the UI application. + * + * @since 2.0 + * + * @return The UI state of the UI application + * @remarks Note that UiApp::OnBackground() is invoked when the UI state of a UI application changes + * from App::APP_UI_STATE_FOREGROUND to App::APP_UI_STATE_PARTIAL_BACKGROUND or App::APP_UI_STATE_BACKGROUND. + * @see AppUiState + */ + AppUiState GetAppUiState(void) const; + + /** + * Called when a UI application moves to the foreground. @n + * User interaction is enabled when the UI application moves to the foreground. @n + * A UI application moves to the foreground when: + * + * - A UI application is selected from the Task Manager. + * - A UI application icon in the Launcher application is pressed when it is running in the background. + * - A UI application is to be launched while it is running in the background. + * - A system pop-up, such as an incoming call, notification (for example, SMS), or a low battery warning + * pop-up disappears. + * + * %OnForeground() is called when the UI application is moved to the foreground. @n + * When this method is invoked, the following actions are recommended: + * + * - Resume the graphic processing, such as 3D or animation, as the UI application now has the focus. + * - Resume the operations that stopped when the UI application is last moved to the background. + * + * @since 2.0 + * + * @remarks When the system needs to refresh a screen component, it can call this method even if the UI application is present in the foreground. + */ + virtual void OnForeground(void); + + /** + * Called when another UI application moves to the top or a system pop-up is displayed. @n + * User interaction is disabled when the UI application is in the background. @n + * A UI application moves to the background when: + * + * - A system pop-up, such as an incoming call or a low battery warning pop-up is displayed. + * - A device is locked. + * - The Home key is pressed. + * + * %OnBackground() is called when the UI application is moved to the background. @n + * Whenever this method is invoked, the following actions are recommended: + * + * - Stop the graphic processing, such as 3D or animation, as they will not be displayed. + * - Release unnecessary resources. + * - Stop media processing, sensor manipulations, and location updates. + * + * @since 2.0 + * + * @remarks When notification (for example, SMS) pops up, this method is not called. + * When a system pop-up is displayed, a UI application becomes partially hidden + * (App::APP_UI_STATE_PARTIAL_BACKGROUND). + * If a UI application is partially hidden, it is recommended to hold the activated + * tasks or resources instead of stopping or releasing them. + * @see GetAppUiState() + */ + virtual void OnBackground(void); + + /** + * Gets the %UiApp instance's pointer. + * + * @since 2.0 + * + * @return A pointer to the %UiApp instance, @n + * else @c null if it fails + */ + static UiApp* GetInstance(void); + + /** + * Executes an application implemented by inheriting this class. + * The %Execute() method must be called from the entry method - OspMain(), which is generated by IDE. + * + * @since 2.0 + * + * @return An error code + * @param[in] pUiAppFactory The factory method that creates this UiApp's instance + * @param[in] pArguments The launch arguments for %App + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INIT_FAILED The initialization failure during OnAppInitializing(). + * @exception E_SYSTEM A system error has occurred. + */ + static result Execute(UiAppInstanceFactory pUiAppFactory, const Tizen::Base::Collection::IList* pArguments); + +protected: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + UiApp(void); + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void UiApp_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void UiApp_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // The following methods are reserved and the name of the methods can be changed at any time without prior notice. + // + // @since 2.0 + // + virtual void UiApp_Reserved3(void) {} + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + UiApp(const UiApp& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + UiApp& operator =(const UiApp& rhs); + +private: + class _UiAppImpl* __pUiAppImpl; +}; // UiApp + +typedef UiApp Application; + +} } //Tizen::App + +#endif // _FAPP_UI_APP_H_ diff --git a/inc/FBase.h b/inc/FBase.h new file mode 100644 index 0000000..95723ad --- /dev/null +++ b/inc/FBase.h @@ -0,0 +1,94 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBase.h + * @brief This is the header file for the %Base namespace. + * + * This header file contains the declarations and descriptions of the %Base namespace. + */ +#ifndef _FBASE_H_ +#define _FBASE_H_ + + +// Base +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Collection +#include + +// Runtime +#include + +// Utility +#include + + +/** + * @namespace Tizen::Base + * @brief This namespace contains classes and interfaces for basic features. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %Base namespace contains classes and interfaces around which the entire Tizen platform is built. + * The main features of the namespace include basic data types, collections, runtime libraries, and various utilities. + * + * For more information on the %Base namespace features, see Base Guide. + * + * The following diagram illustrates the relationships between the classes belonging to the %Base namespace. + * @image html base_namespace_classdiagram.png + * + * + * + */ + +namespace Tizen { namespace Base +{ + +}} // Tizen::Base +#endif // _FBASE_H_ diff --git a/inc/FBaseBoolean.h b/inc/FBaseBoolean.h new file mode 100644 index 0000000..91c13f9 --- /dev/null +++ b/inc/FBaseBoolean.h @@ -0,0 +1,279 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseBoolean.h + * @brief This is the header file for the %Boolean class. + * + * This header file contains the declarations of the %Boolean class. + */ +#ifndef _FBASE_BOOL_H_ +#define _FBASE_BOOL_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Boolean + * @brief This class is the wrapper class for the @c bool data type. + * + * @since 2.0 + * + * The %Boolean class wraps a bool type value. This enables passing a bool value to a method that only accepts an instance of the Object class. + * It provides methods to convert %Boolean instances to String and %String instances to %Boolean. + * + * The following example demonstrates how to use the %Boolean class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::Test(void) + * { + * Boolean b1(true); + * + * String string1(b1.ToString()); // string1 == L"true" + * + * + * // Compares the string1 with L"true" + * if (Boolean::Parse(string1)) + * { + * // ... + * } + * + * } + * @endcode + */ +class _OSP_EXPORT_ Boolean + : public Object +{ +public: + /** + * Initializes this instance of the %Boolean class with the specified @c value. + * + * @since 2.0 + * + * @param[in] value The input @c bool value to initialize the %Boolean instance + */ + Boolean(bool value); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of the %Boolean class + */ + Boolean(const Boolean& value); + + /** + * Initializes this instance of %Boolean with the specified input string. @n + * If the input is "true" (ignoring case), the object is initialized to @c true, + * else @c false. + * + * @since 2.0 + * + * @param[in] value An instance of String + */ + Boolean(const String& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Boolean(void); + + /** + * Compares the values of two %Boolean instances. + * + * @since 2.0 + * + * @return @c true if the values of the objects are equal, @n + * else @c false. + * @param[in] rhs An instance of %Boolean to compare with the current instance + */ + bool operator ==(const Boolean& rhs) const; + + /** + * Checks whether the two %Boolean instances are not equal. + * + * @since 2.0 + * + * @return @c true if the values of the objects are not equal, @n + * else @c false + * @param[in] rhs A instance of %Boolean to compare with the current instance + */ + bool operator !=(const Boolean& rhs) const; + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %Boolean + */ + Boolean& operator =(const Boolean& rhs); + + /** + * Converts an instance of the Object class to an instance of %Boolean and then + * compares it with the calling %Boolean instance. + * + * @since 2.0 + * + * @return @c true if the value of @c obj matches the value of the calling %Boolean instance, @n + * else @c false + * @param[in] obj A reference to the Object instance to compare with the calling %Boolean instance + * @see Tizen::Base::Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Converts a bool value to an instance of %Boolean and then + * compares it with the calling %Boolean instance. + * + * @since 2.0 + * + * @return @c true if the parameter matches the calling %Boolean instance, @n + * else @c false + * @param[in] value The @c bool value to compare to this instance + */ + bool Equals(bool value) const; + + /** + * Returns the value of the calling object as @c bool. + * + * @since 2.0 + * + * @return The value of the %Boolean instance as bool + */ + bool ToBool(void) const; + + /** + * Parses the specified string and converts it to a bool value. + * + * @since 2.0 + * + * @return @c true if the value of the specified string is "true", @n + * else @c false + * @param[in] s An instance of String + * @remarks This method is case sensitive. @n + * It only accepts lowercase strings. + * + * @code + * bool b1 = Boolean::Parse(trueString); // trueString is L"true" + * bool b1 = Boolean::Parse(falseString); // falseString is L"false" + * @endcode + */ + static bool Parse(const String& s); + + /** + * Parses the specified string and converts it to a bool value. @n + * Case sensitivity can be controlled. + * + * @since 2.0 + * + * @return @c true if the value of the specified string is "true", @n + * else @c false + * @param[in] s An instance of String + * @param[in] caseSensitive Set to @c true to perform a + * case sensitive comparison of string @c s + * @remarks If @c caseSensitive is @c true, L"True" returns @c false, else @c true. + * + * @code + * bool b1 = Boolean::Parse(L"True", false ); // Returns @c true + * bool b1 = Boolean::Parse(L"True", true); // Returns @c false + * @endcode + */ + static bool Parse(const String& s, bool caseSensitive); + + /** + * Converts the value of the calling instance from bool to String. + * + * @since 2.0 + * + * @return @c true if this instance is @c true, @n + * else @c false + */ + String ToString(void) const; + + /** + * Converts bool parameter to a String + * instance of the String class and returns the string representation of the + * input bool value (@c true or @c false). + * + * @since 2.0 + * + * @return @c true if the parameter is @c true, @n + * else @c false + * @param[in] value A @c bool value to convert to String + */ + static String ToString(bool value); + + /** + * Returns a %Boolean instance whose value corresponds to the + * primitive value @c true. + * + * @since 2.0 + * + * @return A %Boolean instance equivalent to @c true + */ + static const Boolean GetTrue(void); + + /** + * Returns a %Boolean instance whose value corresponds to the primitive + * value @c false. + * + * @since 2.0 + * + * @return A %Boolean instance equivalent to @c false + */ + static const Boolean GetFalse(void); + + /** + * A boolean value of this instance. + * + * @since 2.0 + */ + bool value; + +private: + friend class _BooleanImpl; + class _BooleanImpl * __pBooleanImpl; + +}; // Boolean + +}} // Tizen::Base + +#endif //_FBASE_BOOL_H_ diff --git a/inc/FBaseBuffer.h b/inc/FBaseBuffer.h new file mode 100644 index 0000000..7140393 --- /dev/null +++ b/inc/FBaseBuffer.h @@ -0,0 +1,830 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseBuffer.h + * @brief This is the header file for the %Buffer class. + * + * This header file contains the declarations of the %Buffer classes. + */ + +#ifndef _FBASE_BUFFER_H_ +#define _FBASE_BUFFER_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base +{ + +// Forward declaration +class ByteBuffer; + +/** + * @class Buffer + * @brief This class represents a linear finite sequence of elements of the same type. + * + * @since 2.0 + * + * The %Buffer class represents a linear finite sequence of elements of the same type. + * It is a means of defining an aggregation of the same type of objects, similar to an array. + * @n + * For more information on the class features, see Buffer. + * + * @see Tizen::Base::BufferBase + * + * The following example demonstrates how to use the %Buffer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::BufferSample(void) + * { + * // Sets the buffer capacity to 1024 + * const int BUFFER_SIZE_MAX = 1024; + * + * // Initializes intBuf with capacity + * IntBuffer intBuf; + * intBuf.Construct(BUFFER_SIZE_MAX); + * + * int intArray[] = {0,1,2,3,4,5,6,7,8,9}; + * + * // Copies all values from intArray to intBuffer instance + * // position = 10 (num of element copied) + * intBuf.SetArray(intArray, 0, (sizeof(intArray) / sizeof(int))); + * + * // Flips the buffer: The limit is set to the current position and + * // then the position is set to zero + * intBuf.Flip(); // position = 0, limit = 10 + * + * // Gets the number of elements between the current position and the limit + * int remaining = intBuf.GetRemaining(); + * + * // Initializes a doubleBuf with capacity(10) using Construct() method + * DoubleBuffer doubleBuf; + * doubleBuf.Construct(remaining); + * + * // Reads and writes elements from the intBuf to the doubleBuf + * for (int i = 0; i < remaining; i++) + * { + * int value; + * + * // Demonstrates relative reading and writing + * + * // Reads the value at the current position, and then increments the position + * intBuf.Get(value); + * + * // Writes the value * 12.34 at the current position of the doubleBuf + * // and then increment the position + * doubleBuf.Set(value * 12.34); + * + * // Now, positions of the intBuf and the doubleBuf have been incremented by one + * } + * + * // Flips the doubleBuf + * doubleBuf.Flip(); + * // Now, the doubleBuf's position = 0 and limit = 10 + * + * // Gets the remaining elements of the doubleBuf + * remaining = doubleBuf.GetRemaining(); + * + * // Gets the second double value with index + * double doubleValue; + * doubleBuf.Get(1, doubleValue); // 12.34 + * } + * + * @endcode + */ +template +class _OSP_EXPORT_ Buffer + : public BufferBase +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks After creating an instance of the %Buffer class, one of the Construct() methods must be called explicitly to initialize this instance. + * @see Construct() + */ + Buffer(void) + { + + } + + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Buffer(void) + { + + } + + + /** + * Initializes this instance of %Buffer which is a view of the specified buffer. @n + * This is similar to a copy constructor. + * + * @since 2.0 + * + * @param[in] buffer The other %Buffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the source buffer is not constructed. + * @see Buffer() + */ + result Construct(const Buffer & buffer) + { + TryReturn(null != buffer._pData, E_INVALID_ARG, ("[E_INVALID_ARG] The source buffer is not constructed.")); + + _capacity = buffer._capacity; + _position = buffer._position; + _limit = buffer._limit; + _mark = buffer._mark; + _pData = buffer._pData; + + AddRef(); + __pArrayStart = buffer.__pArrayStart; + + return E_SUCCESS; + } + + /** + * Initializes this instance of %Buffer with the specified capacity. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The number of elements + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c capacity is negative. + * @see Buffer() + */ + result Construct(int capacity) + { + return BufferBase::Construct(capacity); + } + + /** + * Initializes this instance of %Buffer with the specified @c buffer which is shared with this instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] pBuffer The buffer which is shared + * @param[in] index The starting index of the buffer from where the first @c byte value is read + * @param[in] length The number of bytes to read from the given buffer @n This is a limit of this instance. + * @param[in] capacity The capacity of this instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c pBuffer is @c null. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the @c length. + */ + result Construct(const Type* pBuffer, int index, int length, int capacity) + { + TryReturn(pBuffer != null, E_INVALID_ARG, "[E_INVALID_ARG] The pBuffer is null."); + TryReturn(index >= 0 && length >= 0 && capacity >=0, E_OUT_OF_RANGE, + "[E_OUT_OF_RANGE] index(%d), length(%d) and capacity(%d) MUST be greater than or equal to 0.", index, + length, capacity); + TryReturn(index < capacity && length <= capacity && index + length <= capacity, E_OUT_OF_RANGE, + "[E_OUT_OF_RANGE] index(%d), length(%d) and capacity(%d) MUST be greater than or equal to 0.", index, + length, capacity); + + void* pTemp = null; + int sizeofBufferData = sizeof(_BufferData); + + Type* tempByte = const_cast (pBuffer + index); + __pArrayStart = reinterpret_cast (tempByte); + + pTemp = malloc(sizeofBufferData); + TryReturn(pTemp != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]"); + + memset(pTemp, 0, sizeofBufferData); + _pData = static_cast <_BufferData*>(pTemp); + + _pData->refCount = 1; + _pData->capacityInByte = capacity * sizeof(Type); + + _capacity = capacity; + _limit = length; + + return E_SUCCESS; + } + + /** + * This subscript operator returns the reference to the element indicated by the given index. + * + * @since 2.0 + * + * @return A reference to the indexed element + * @param[in] index The index of the element @n + * It must be less than the limit. + */ + Type& operator [](int index) const + { + AppAssertf(index < _limit, "index out of range.\n"); + AppAssertf(index >= 0, "index out of range.\n"); + + return ((Type*) __pArrayStart)[index]; + } + + /** + * Overloaded equality operator to compare two %Buffer instances. + * + * @since 2.0 + * + * @return @c true if the buffers being compared are equal, @n + else @c false + * @param[in] buffer The buffer to compare with the current instance of %Buffer + * @remarks This method returns @c true only if the two buffers have the same number of remaining elements @n + * and the two sequences of remaining elements are equal (considered independently of their starting positions). + * @see Equals() + */ + bool operator ==(const Buffer & buffer) const + { + bool r = true; + if (this == (void*) (&buffer)) + { + r = true; + } + else if (GetRemaining() != buffer.GetRemaining()) + { + r = false; + } + else + { + void* p1 = &(((Type*) __pArrayStart)[_position]); + void* p2 = &(((Type*) buffer.__pArrayStart)[buffer._position]); + if ((p1 != p2) && (memcmp(p1, p2, sizeof(Type) * GetRemaining()) != 0)) + { + r = false; + } + } + + return r; + } + + /** + * Checks whether the two %Buffer instances are not equal. + * + * @since 2.0 + * + * @return @c true if the buffers are not equal, @n + else @c false + * @param[in] buffer The buffer to compare with the current instance of %Buffer + * @remarks This method returns @c false only if the two buffers being compared have the same @n + * number of remaining elements and the two sequences of remaining elements are equal @n + * (considered independently of their starting positions). + * @see Equals() + */ + bool operator !=(const Buffer & buffer) const + { + return !(*this == buffer); + } + + /** + * Copies the remaining elements of the input %Buffer instance into the current + * %Buffer instance. @n + * It returns E_OVERFLOW if the remaining part of the current instance is smaller + * than the remaining part of the input instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] buffer The source buffer from which bytes are read @n + * It must not be the current instance of %Buffer. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the source buffer is same as destination buffer, + * that is, the current instance of %Buffer. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow. @n + * The number of remaining bytes of the current buffer is less than + * the number of remaining bytes of the given buffer. + * @remarks After the copy operation, the current (destination) buffer's position and the given + * (source) buffer's position are incremented by the number of elements copied (the number + * of remaining elements of the given buffer). @n + * If the remaining part of the current instance is not less than the remaining part of the input instance, + * the effect of this method and the ReadFrom() method is the same. But when the remaining part of the + * current instance is less, ReadFrom() method copies the number of remaining elements of the current + * instance while this method returns E_OVERFLOW and does not transfer. + * @see ReadFrom() + * + * The following example demonstrates how to use the %CopyFrom() method. + * + * @code + * + * // Create instances of IntBuffer to act as source and destination buffers + * IntBuffer srcBuf; + * IntBuffer destBuf; + * + * // Declare an array of integers + * int pArray[] = {0,1,2,3,4,5,6,7,8,9}; + * + * // Initialize the source buffer with 10 elements. + * srcBuf.Construct(10); + * + * // Copy the 10 values from pArray starting at position 0 to srcBuf + * // Now srcBuf's position = 10 + * srcBuf.SetArray(pArray, 0, 10); + * + * // Flip the buffer: The limit is set to the current position + * // and then the position is set to zero + * srcBuf.Flip(); // srcBuf's position = 0 and limit = 10 + * + * + * destBuf.Construct(20); + * + * // Copy from srcBuf to destBuf + * // Now srcBuf's position = 10, destBuf's position = 10 + * destBuf.CopyFrom(srcBuf); + * + * @endcode + * + * The following example has exactly the same effect as the above %CopyFrom() method. + * + * @code + * + * int copyNum = srcBuf.GetRemaining(); + * for (int i = 0; i < copyNum; i++) + * { + * int value; + * + * // Read from the source buffer + * srcBuf.Get(value); // srcBuf position is incremented by one. + * + * // Write to the destination buffer + * destBuf.Set(value); // destBuf position is incremented by one. + * + * } + * @endcode + */ + result CopyFrom(Buffer& buffer) + { + TryReturn(this != static_cast (&buffer), E_INVALID_ARG, + "[E_INVALID_ARG] The source and target buffers are identical."); + int copyLength = buffer.GetRemaining(); + TryReturn(GetRemaining() >= copyLength, E_OVERFLOW, "[E_OVERFLOW]"); + + memcpy(__pArrayStart + _position * sizeof(Type), buffer.__pArrayStart + buffer._position * sizeof(Type), + copyLength * sizeof(Type)); + + _position += copyLength; + buffer._position += copyLength; + + return E_SUCCESS; + } + + /** + * Reads the value from the current position in the buffer, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The value at the current position + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow. @n + * The current position is greater than the limit. + * @see Set() + */ + result Get(Type& value) + { + TryReturn(_position < _limit, E_UNDERFLOW, "[E_UNDERFLOW]"); + + value = ((Type*) __pArrayStart)[_position++]; + return E_SUCCESS; + } + + /** + * Reads the value at the given index. @n + * Provides a way for absolute indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index into the buffer from where the value is read + * @param[out] value The value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified @c index is outside the bounds of the data structure. @n + * The @c index is greater than the limit or less than @c 0. + * @see Set() + */ + result Get(int index, Type& value) const + { + TryReturn(index < _limit && index >= 0, E_OUT_OF_RANGE, + "[E_OUT_OF_RANGE] The index(%d) MUST be greater than or equal to 0, and less then the current limit(%d).", + index, _limit); + + value = ((Type*) __pArrayStart)[index]; + return E_SUCCESS; + } + + + /** + * Copies the specified range of values from the calling buffer to the specified destination array as per the given index of the array. + * + * @since 2.0 + * + * @return An error code + * @param[out] pArray A pointer to the array into which values are written + * @param[in] index The starting index in the array of the first value to write + * @param[in] length The number of values from the buffer to write to the array + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c pArray is @c null. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index or length is less than @c 0. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow. @n + * The remaining elements of this buffer are smaller than @c length. + * @remarks After the copy operation, the position is incremented by @c length. + * @see SetArray() + */ + result GetArray(Type* pArray, int index, int length) + { + TryReturn(0 != pArray, E_INVALID_ARG, "[E_INVALID_ARG] The pArray is null."); + TryReturn(index >= 0 && length >= 0, E_OUT_OF_RANGE, + "[E_OUT_OF_RANGE] Both of index(%d) and length(%d) MUST be greater than or equal to 0.", index, length); + TryReturn(GetRemaining() >= length, E_UNDERFLOW, "[E_UNDERFLOW]"); + + memcpy(pArray + index, __pArrayStart + _position * sizeof(Type), length * sizeof(Type)); + _position += length; + + return E_SUCCESS; + } + + /** + * Transfers bytes from the input buffer into the calling buffer. @n + * If the empty space in the calling buffer is larger than the remaining values from the input buffer, + * all the remaining elements from the input are copied to the destination. @n + * Otherwise, the number of bytes copied equals the number of elements remaining in the calling buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] buffer The source buffer from which bytes are read @n + * It must not be this buffer. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. @n + * The given buffer is same as the current buffer instance. + * @remarks After the copy operation, the current (destination) buffer's position and the given + * (source) buffer's position are incremented by the number of elements copied (the smaller value + * between the number of elements remaining in the calling buffer and the source buffer). @n + * If there are more elements remaining in the calling buffer than elements remaining in the input instance, + * this method is equivalent to CopyFrom() method. If there are less remaining elements in the + * calling buffer, the CopyFrom() method returns E_OVERFLOW and does not transfer + * while this method copies the number of remaining elements of the current instance. + * @see CopyFrom() + * + * The following example demonstrates how to use the %ReadFrom() method. + * + * @code + * + * // Create instances of IntBuffer to act as the source and destination buffers + * IntBuffer srcBuf; + * IntBuffer destBuf; + * + * // Declare an array of integers + * int pArray[] = {0,1,2,3,4,5,6,7,8,9}; + * + * // Initialize the source buffer with a capacity of 10 elements. + * srcBuf.Construct(10); + * + * // Copy the 10 values from pArray starting at position 0 to srcBuf + * // Now srcBuf's position = 10 + * srcBuf.SetArray(pArray, 0, 10); + * + * // Flip the buffer: The limit is set to the current position + * // and then the position is set to zero + * srcBuf.Flip(); // srcBuf's position = 0 and limit = 10 + * + * + * // Initialize the destination buffer with a capacity of 10 elements. + * destBuf.Construct(10); + * + * // Set the limit of destBuf to 5 + * destBuf.SetLimit(5); + * + * // Read from srcBuf to destBuf + * // destBuf's remaining is 5, smaller than the srcBuf's (10). + * // Therefore, five elements are transferred. + * // srcBuf's position = 5, destBuf's position = 5 + * destBuf.ReadFrom(srcBuf); + * + * + * @endcode + * + * The following example has exactly the same effect as the above %ReadFrom() method. + * + * @code + * + * int copyNum = (destBuf.GetRemaining() < srcBuf.GetRemaing())? destBuf.GetRemaining() : srcBuf.GetRemaining(); + * for (int i = 0; i < copyNum; i++) + * { + * int value; + * + * // Read from source buffer + * srcBuf.Get(value); // srcBuf position is incremented by one. + * + * // Write to destination buffer + * destBuf.Set(value); // destBuf position is incremented by one. + * + * } + * @endcode + */ + result ReadFrom(Buffer& buffer) + { + TryReturn(this != static_cast (&buffer), E_INVALID_ARG, + "[E_INVALID_ARG] The source and target buffers are identical."); + + int copyLength = (GetRemaining() < buffer.GetRemaining()) ? GetRemaining() : buffer.GetRemaining(); + + memcpy(__pArrayStart + _position * sizeof(Type), buffer.__pArrayStart + buffer._position * sizeof(Type), + copyLength * sizeof(Type)); + + _position += copyLength; + buffer._position += copyLength; + + return E_SUCCESS; + } + + + /** + * Writes the specified value into the current buffer instance at the current position, + * and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The value to write to the calling %Buffer + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow. @n + * The current position is not smaller than the limit. + * @see Get() + */ + result Set(Type value) + { + TryReturn(_position < _limit, E_OVERFLOW, "[E_OVERFLOW]"); + + ((Type*) __pArrayStart)[_position++] = value; + return E_SUCCESS; + } + + /** + * Writes the specified value into the current instance of buffer at the given index. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the value is written + * @param[in] value The value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is not smaller than the limit or less than @c 0. + * @see Get() + */ + result Set(int index, Type value) + { + TryReturn(index < _limit && index >= 0, E_OUT_OF_RANGE, + "[E_OUT_OF_RANGE] The index(%d) MUST be greater than or equal to 0, and less then the current limit(%d).", + index, _limit); + + ((Type*) __pArrayStart)[index] = value; + return E_SUCCESS; + } + + /** + * Copies values from the input source array into the calling buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] pArray A pointer to the array from which values are read + * @param[in] index The starting index of the array + * @param[in] length The number of values read from the given array + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c pArray is @c null. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index or length is less than @c 0. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow. @n + * The remainder of this buffer is smaller than @c length. + * @remarks This method copies @c length number of values from the source array, + * starting from the given index in the array, into the calling + * buffer, starting at the current position. + * After the copy operation, the position is incremented by @c length. + * @see GetArray() + */ + result SetArray(const Type* pArray, int index, int length) + { + TryReturn(null != pArray, E_INVALID_ARG, "[E_INVALID_ARG] The pArray is null."); + TryReturn(index >= 0 && length >= 0, E_OUT_OF_RANGE, + "[E_OUT_OF_RANGE] Both of index(%d) and length(%d) MUST be greater than or equal to 0.", index, length); + TryReturn(GetRemaining() >= length, E_OVERFLOW, "[E_OVERFLOW]"); + + memcpy(__pArrayStart + _position * sizeof(Type), pArray + index, length * sizeof(Type)); + _position += length; + + return E_SUCCESS; + } + + /** + * Creates a new %Buffer instance. @n + * Its content is a shared portion of + * the calling %Buffer instance that starts from the current position of calling %Buffer instance. + * + * @since 2.0 + * + * @return A pointer to the new buffer + * @remarks The content of the new buffer starts at the current position of this instance of %Buffer. + * The new buffer's position is @c 0, its capacity and limit is + * the number of bytes remaining in the current instance of %Buffer, + * and it is marked as undefined. + */ + Buffer * SliceN(void) const + { + Buffer * pBuffer = new Buffer (); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining(); + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = (byte*) &((Type*) __pArrayStart)[_position]; + } + + return pBuffer; + } + + /** + * Gets a raw array pointer to calling buffer. + * + * @since 2.0 + * + * @return A raw array pointer to the buffer, @n + * else @c null if the capacity is @c 0 + */ + const Type* GetPointer(void) const + { + return (Type*) __pArrayStart; + } + + /** + * Compares the Object instance with the calling %Buffer instance for equivalence. + * + * @since 2.0 + * + * @return @c true if the input equals the calling %Buffer instance, @n + * else @c false + * @param[in] obj The object to compare with the calling %Buffer + * @remarks This method returns @c true if and only if the specified object is also an instance of %Buffer class, + * the two buffers have the same number of remaining elements, and the two sequences of + * remaining elements are equal (considered independently of their starting positions). + * @see Tizen::Base::BufferBase::GetHashCode() + */ + virtual bool Equals(const Tizen::Base::Object& obj) const + { + bool out = false; + const Buffer * other = static_cast *>(&obj); + if ((other == this) || (*other == *this)) + { + out = true; + } + + return out; + } + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The hash code of a buffer depends only upon its remaining elements. + */ + virtual int GetHashCode(void) const + { + int len = (GetRemaining() * GetTypeSize()) / sizeof(int); + + int hash = 0; + int offset = _position * GetTypeSize(); + for (int i = 0; i < len; ++i) + { + hash = (hash<<5) - hash + (int) __pArrayStart[offset + (i * sizeof(int))]; + } + + return hash; + } + +private: + /** + * This is the copy constructor for this class. + */ + Buffer(const Buffer & buffer) + { + Construct(buffer); + } + + /** + * This is the assignment operator. + */ + Buffer & operator =(const Buffer & buffer); + + /** + * Returns the size of the type of this buffer. + * + * @return The size of the buffer + */ + virtual int GetTypeSize(void) const + { + return sizeof(Type); + } + + friend class ByteBuffer; + +}; // Buffer + + +/** + * The @c double buffer type. + * @since 2.0 + */ +typedef Buffer DoubleBuffer; + +/** +* The @c float buffer type. +* @since 2.0 +*/ +typedef Buffer FloatBuffer; + +/** +* The @c int buffer type. +* @since 2.0 +*/ +typedef Buffer IntBuffer; + +/** +* The @c long buffer type. +* @since 2.0 +*/ +typedef Buffer LongBuffer; + +/** +* The @c long @c long buffer type. +* @since 2.0 +*/ +typedef Buffer LongLongBuffer; + +/** +* The @c wchar_t buffer type. +* @since 2.0 +*/ +typedef Buffer WcharBuffer; + +/** +* The @c short buffer type. +* @since 2.0 +*/ +typedef Buffer ShortBuffer; + + +#ifdef _MSC_VER +template class _OSP_EXPORT_ Buffer ; +template class _OSP_EXPORT_ Buffer ; +template class _OSP_EXPORT_ Buffer ; +template class _OSP_EXPORT_ Buffer ; +template class _OSP_EXPORT_ Buffer ; +template class _OSP_EXPORT_ Buffer ; +template class _OSP_EXPORT_ Buffer ; +#endif + +}} // Tizen::Base + +#endif // _FBASE_BUFFER_H_ diff --git a/inc/FBaseBufferBase.h b/inc/FBaseBufferBase.h new file mode 100644 index 0000000..7db19df --- /dev/null +++ b/inc/FBaseBufferBase.h @@ -0,0 +1,438 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseBufferBase.h + * @brief This is the header file for the %BufferBase class. + * + * This header file contains the declarations of the %BufferBase class. + */ + +#ifndef _FBASE_BUFFER_BASE_H_ +#define _FBASE_BUFFER_BASE_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ + +/** + * @enum PositionTo + * + * Defines position. + * + * @since 2.0 + */ +enum PositionTo +{ + POSITION_TO_ZERO = 0, /**< The position is set to zero */ + POSITION_TO_MARK = 1, /**< The position is set to the mark */ +}; + + +/** + * @class BufferBase + * @brief This class is the abstract base class of all buffer classes. + * + * @since 2.0 + * + * The %BufferBase class is the abstract base class of all buffer classes. + * + * For more information on the class features, see Buffer. + * + * @see Tizen::Base::ByteBuffer, Tizen::Base::Buffer< Type > + */ + +class _OSP_EXPORT_ BufferBase + : public Object +{ + +// Forward declaration +protected: + class _BufferData; + +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~BufferBase(void); + + /** + * Clears the calling %BufferBase object. @n + * The buffer's position is set to @c 0, the limit is set to the capacity, and the mark is discarded. + * + * @since 2.0 + */ + void Clear(void); + + /** + * Copies the elements between the current position and limit (that are also known as remaining + * elements), to the beginning of the calling %BufferBase instance. + * + * @since 2.0 + * + * @remarks After copying, the position is set to the number of elements copied rather than to @c 0, + * so that an invocation of this method can be followed immediately by an invocation + * of another relative set method. The limit is set to the capacity, and the mark is discarded. + */ + void Compact(void); + + /** + * Flips the calling %BufferBase instance. @n + * It sets the limit to the current position + * and sets the position to either @c 0 or the mark, depending on the input value. + * + * @since 2.0 + * + * @param[in] to The value to set the buffer position @n + * The parameter may contain @c POSITION_TO_ZERO or @c POSITION_TO_MARK. + * @remarks If @c to is POSITION_TO_ZERO (or unspecified), the position is set to @c 0 after setting a limit to + * the current position, and the mark is discarded. + * Otherwise, if @c to is POSITION_TO_MARK, the position is set to the mark and + * the mark is not discarded. If the mark is undefined, the position is set to @c 0. + * + * The following example demonstrates how to use the %Flip() method. + * + * @code + * + * ByteBuffer buf; + * buf.Construct(10); // buf's position is zero, limit is 10, and mark is undefined. + * + * buf.SetPosition(7); // Now, buf's position is 7 (limit and mark is unchanged). + * + * buf.Flip(); // equal to "buf.Flip(POSITION_TO_ZERO)" + * // buf's position : 0, limit : 7, mark is still undefined. + * + * buf.SetPosition(3); + * buf.SetMark(); // Both buf's position and mark are 3. + * + * buf.SetPosition(5); // buf's position is 5, limit is 7, and mark is 3. + * + * buf.Flip(POSITION_TO_MARK); // Now, buf's position is 3, and limit and mark are unchanged. + * + * @endcode + */ + void Flip(PositionTo to = POSITION_TO_ZERO); + + /** + * Gets the hash value of the calling object. + * + * @since 2.0 + * + * @return The hash value of the calling object + * @remarks The hash code of a buffer depends only upon its remaining elements. + * @see Tizen::Base::Object::Equals() + */ + virtual int GetHashCode(void) const; + + /** + * Invalidates the mark of the calling instance of %BufferBase (set to @c -1). + * + * @since 2.0 + * + * @see SetMark() + */ + void InvalidateMark(void); + + /** + * Resets the position of the calling %BufferBase object to the previously marked position. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation.@n + * The mark has not been set. + * @remarks Invoking this method neither changes nor discards the mark's value. + */ + result Reset(void); + + /** + * Rewinds the current instance of %BufferBase. @n + * It sets the position to + * @c 0, discards the mark, and leaves the limit unchanged. + * + * @since 2.0 + */ + void Rewind(void); + + /** + * Shifts the limit of the current instance of %BufferBase. @n + * The new limit is the current limit plus the given amount. + * + * @since 2.0 + * + * @return An error code + * @param[in] amount The quantity of shift needed + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method. @n + * The @c amount is larger than the capacity or smaller than @c 0 starting from the current limit. + * @remarks If the position is larger than the new limit, it is set to the new limit. + * If the mark is defined and larger than the new limit, it is discarded. + * @see SetLimit() + */ + result ShiftLimit(int amount); + + /** + * Gets the capacity of the calling %BufferBase instance. + * + * @since 2.0 + * + * @return The capacity of the calling object + */ + int GetCapacity(void) const; + + + /** + * Gets the limit of the calling %BufferBase instance. + * + * @since 2.0 + * + * @return The limit of the calling object + * @see SetLimit() + */ + int GetLimit(void) const; + + + /** + * Gets the mark of the calling %BufferBase instance. @n + * If the mark has not been set, it returns @c -1. + * + * @since 2.0 + * + * @return The mark of the calling %BufferBase instance + * @see SetMark() + */ + int GetMark(void) const; + + + /** + * Gets the current position of the calling %BufferBase instance. + * + * @since 2.0 + * + * @return The current position of the calling %BufferBase instance + * @see SetPosition() + */ + int GetPosition(void) const; + + + /** + * Gets the number of elements between the current position and the limit + * of the calling %BufferBase instance. + * + * @since 2.0 + * + * @return The number of elements between the current position and the limit + * @see HasRemaining() + */ + int GetRemaining(void) const; + + + /** + * Sets the limit of the calling %BufferBase instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] limit The new limit + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method. @n + * The @c limit is larger than the capacity or less than @c 0. + * @remarks If the position is larger than the new limit, it is set to the new limit. + * If the mark is defined and larger than the new limit, it is discarded. + * @see GetLimit() + */ + result SetLimit(int limit); + + + /** + * Sets the mark of the current instance of %BufferBase at the current position. @n + * If this method is called after InvalidateMark(), the mark is set to @c -1. + * + * @since 2.0 + * + * @see GetMark() + */ + void SetMark(void); + + + /** + * Sets the position of the calling %BufferBase instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] position The new position + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method. @n + * The @c position is larger than the current limit or less than @c 0. + * @remarks If the mark is defined and larger than the new position then it is discarded. + * @see GetPosition() + */ + result SetPosition(int position); + + /** + * Returns @c true if there is at least one element between the current position and + * the limit of the current instance of %BufferBase. Otherwise, it returns @c false. + * + * @since 2.0 + * + * @return @c true if there is at least one element between the current position and the limit of the current instance of %BufferBase, @n + * else @c false + * @see GetRemaining() + */ + bool HasRemaining(void) const; + + /** + * Expands the capacity and the limit of the internal buffer with the specified capacity. + * + * @since 2.0 + * + * @return An error code + * @param[in] newCapacity The new capacity of this instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c capacity is less than the current capacity. + * @remarks After calling this method, the address of the internal buffer may be either the same or a new location. + */ + result ExpandCapacity(int newCapacity); + +protected: + /** + * The object is not fully constructed after this constructor is called. For full construction, + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + BufferBase(void); + + /** + * Initializes this instance of %BufferBase with the specified capacity. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The number of elements + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The @c capacity is negative. + */ + result Construct(int capacity); + + /** + * Increments the reference count by one. + * + * @since 2.0 + */ + long AddRef(void) const; + + + /** + * Decrements the reference count by one. + * + * @since 2.0 + * + * @return The reference count after decrement + */ + long Release(void) const; + + /** + * Decreases the reference count. @n + * After that, it frees the resource (memory allocation) if the reference count is zero. + * + * @since 2.0 + */ + virtual void Dispose(void); + + /* + * @class _BufferData + * @brief This class encapsulates the @c byte array used by the buffer classes. + * + * @since 2.0 + * + */ + class _BufferData + { + public: + // + // This is the default constructor for this class. + // + // @since 2.0 + // + _BufferData(void); + + // + // This is the destructor for this class. + // + // @since 2.0 + // + virtual ~_BufferData(void); + + // + // Gets the pointer to the byte array. + // + // @since 2.0 + // @return Pointer to the @c byte array + // + byte* GetArray(void); + + + // Attribute + unsigned long long capacityInByte; + long refCount; + + }; // _BufferData + + + int _capacity; + int _position; + int _limit; + int _mark; + _BufferData* _pData; + byte* __pArrayStart; + + +private: + /** + * Returns the size of the type of the current %BufferBase instance. + * + * @return The size of the type of the current %BufferBase instance + */ + virtual int GetTypeSize(void) const = 0; + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + BufferBase(const BufferBase& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + BufferBase& operator =(const BufferBase& rhs); + + friend class _BufferBaseImpl; + class _BufferBaseImpl * __pBufferBaseImpl; + +}; // BufferBase + +}} // Tizen::Base + +#endif // _FBASE_BUFFER_BASE_H_ diff --git a/inc/FBaseByteBuffer.h b/inc/FBaseByteBuffer.h new file mode 100644 index 0000000..a85c68e --- /dev/null +++ b/inc/FBaseByteBuffer.h @@ -0,0 +1,1303 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseByteBuffer.h + * @brief This is the header file for the %ByteBuffer class. + * + * This header file contains the declarations of the %ByteBuffer class. + */ + +#ifndef _FBASE_BYTE_BUFFER_H_ +#define _FBASE_BYTE_BUFFER_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ + +/** + * @class ByteBuffer + * @brief This class provides a contiguous sequence of the @c byte (@c unsigned @c char) built-in type. + * + * @since 2.0 + * + * The %ByteBuffer class provides a means of encapsulating a sequence of bytes in memory. It defines + * methods to read and write all primitive built-in types (except @c bool), to and from a sequence of + * bytes. These methods read the size of primitive type bytes from a @c byte sequence and + * convert it to the actual primitive type. + * + * For more information on the class features, see Buffer. + * + * @see Tizen::Base::BufferBase + * + * The following example demonstrates how to use the %ByteBuffer class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::ByteBufferSample(void) + * { + * // Defines the maximum buffer size : capacity + * const int BUFFER_SIZE_MAX = 1024; + * + * // Initializes a buf using the Construct method to the capacity + * ByteBuffer buf; + * buf.Construct(BUFFER_SIZE_MAX); + * + * // Copies five values into the buf + * for (int i = 0; i < 5; i++) + * { + * byte b = 'A' + i; + * + * // Writes byte b to the current position of the buf + * buf.SetByte(b); // The position is incremented by one + * } + * // The position is moved to 5 + * + * // Flips the buf + * buf.Flip(); + * // Now, position = 0 and limit = 5 + * + * // Reads bytes from the buf using "relative access method" + * while (buf.HasRemaining()) + * { + * byte b; + * + * // Reads byte b from the current position of the buf + * buf.GetByte(b); // The position is incremented by one + * } + * + * + * // Clears the buf + * buf.Clear(); + * // The buf's position = 0 and limit = capacity + * + * // Writes int values to the buf + * for (int i = 0; i < 5; i++) + * { + * // Writes int value at the current position + * buf.SetInt(i); // The position is incremented by sizeof(int) + * } + * + * // Flips the buf + * buf.Flip(); + * // Now, position = 0 and limit = sizeof(int) * 5 + * + * // Creates a new view, IntBuffer. + * // Capacity of intBuf = 5 + * // The content of intBuf is from the buf's position to the buf's limit + * IntBuffer* pIntBuf = buf.AsIntBufferN(); + * + * // Tests whether the change in view buffer(IntBuffer) is visible in original buffer(ByteBuffer) + * pIntBuf->Set(4, 9); + * + * // Reads int values from the buf using "absolute access method" + * for (int i = 0; i < 5; i++) + * { + * int out; + * + * // Reads int value from the buf with the specified index. + * buf.GetInt((i * sizeof(int)), out); // 0, 1, 2, 3, 9 + * // The position is not changed + * } + * + * delete pIntBuf; + * + * } + * + * @endcode + */ +class _OSP_EXPORT_ ByteBuffer + : public BufferBase +{ + +public: + /** + * The object is not fully constructed after this constructor is called. + * For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @remarks After creating an instance of the %ByteBuffer class, one of the Construct() methods must be called explicitly to initialize this instance. + * @see Construct() + */ + ByteBuffer(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~ByteBuffer(void); + + /** + * Initializes this instance of %ByteBuffer which is a view of the specified buffer. @n + * This is the copy constructor for the %ByteBuffer class. + * + * @since 2.0 + * + * @param[in] buffer The %ByteBuffer instance used to initialize new object + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the source buffer is not constructed. + * @see ByteBuffer() + */ + result Construct(const ByteBuffer& buffer); + + /** + * Initializes this instance of %ByteBuffer with the specified @c capacity. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The number of elements + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c capacity is negative. + * @see ByteBuffer() + */ + result Construct(int capacity); + + /** + * Initializes this instance of %ByteBuffer with the specified @c buffer which is shared with this instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] pBuffer The buffer which is shared + * @param[in] index The starting index of the buffer from where the first @c byte value is read + * @param[in] length The number of bytes to read from the given buffer @n This is a limit of this instance. + * @param[in] capacity The capacity of this instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c pBuffer is @c null. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the @c length. + */ + result Construct(const byte *pBuffer, int index, int length, int capacity); + + /** + * Gets the reference to the byte value at the specified index. + * + * @since 2.0 + * + * @return A reference to the @c byte value + * @param[in] index The index of the @c byte value in the calling %ByteBuffer instance @n + * It must be less than the limit. + */ + byte& operator [](int index); + + /** + * Gets the byte value at the specified index of const object. + * + * @since 2.0 + * + * @return A value to the @c byte value + * @param[in] index The index of the @c byte value in the calling %ByteBuffer instance @n + * It must be less than the limit. + */ + byte operator [](int index) const; + + /** + * Compares the two %ByteBuffer instances. + * + * @since 2.0 + * + * @return @c true if the input buffer is equal to the calling %ByteBuffer instance, @n + * else @c false + * @param[in] buffer The %ByteBuffer instance to compare with the current instance + * @remarks This method returns @c true only if the two buffers have the same number of + * remaining elements, and the two sequences of remaining elements are equal + * (considered independently, irrespective of their starting positions). + * @see Equals() + */ + bool operator ==(const ByteBuffer& buffer) const; + + /** + * Checks whether the current instance and the specified instance of %ByteBuffer are not equal. + * + * @since 2.0 + * + * @return @c true if the two objects are not the same, @n + * else @c false + * @param[in] buffer The buffer to compare with the current instance + * @remarks This method returns @c false only if the two buffers being compared have the same + * number of remaining elements, and the two sequences of remaining elements are equal + * (considered independently, irrespective of their starting positions). + * @see Equals() + */ + bool operator !=(const ByteBuffer& buffer) const; + + /** + * Creates a new @c double buffer view for the content of the byte buffer. + * + * @since 2.0 + * + * @return DoubleBuffer A pointer to the current position of the calling object + * @remarks The content of the view buffer starts at the current position of the calling buffer. + * The new buffer's position is zero, the mark is undefined, and the capacity and limit + * are equal to the remaining part of this buffer divided by the size of @c double. + * Any change to the byte buffer content is visible in the @c double buffer view, and vice versa. + */ + DoubleBuffer* AsDoubleBufferN(void) const; + + /** + * Creates a new @c float buffer view for the content of the byte buffer. + * + * @since 2.0 + * + * @return FloatBuffer A pointer to the current position of the calling buffer + * @remarks The content of the view buffer starts at the current position of the calling buffer. + * The new buffer's position is zero, the mark is undefined, and the capacity and limit + * are equal to the remaining part of the calling buffer divided by the size of @c float. + * Any change to the byte buffer content is visible in the @c float buffer view, and vice versa. + */ + FloatBuffer* AsFloatBufferN(void) const; + + /** + * Creates a new @c int buffer view for the content of the byte buffer. + * + * @since 2.0 + * + * @return IntBuffer A pointer to the current position of the calling buffer + * @remarks The content of the view buffer starts at the current position of the calling buffer. + * The new buffer's position is zero, the mark is undefined, and the capacity and limit + * are equal to the remaining part of calling buffer divided by the size of @c int. + * Any change to the byte buffer content is visible in the Int buffer view, and vice versa. + */ + IntBuffer* AsIntBufferN(void) const; + + /** + * Creates a new @c long buffer view for the content of the byte buffer. + * + * @since 2.0 + * + * @return LongBuffer A pointer to the current position of the calling buffer + * @remarks The content of the view buffer starts at the current position of this buffer. + * The new buffer's position is zero, the mark is undefined, and the capacity and limit + * are equal to the remaining part of calling buffer divided by the size of @c long. + * Any change to the byte buffer content is visible in the @c long buffer view, and vice versa. + */ + LongBuffer* AsLongBufferN(void) const; + + /** + * Creates a new @c long @c long buffer view for the content of the byte buffer. + * + * @since 2.0 + * + * @return LongLongBuffer A pointer to the current position of the calling buffer + * @remarks The content of the view buffer starts at the current position of this buffer. + * The new buffer's position is zero, the mark is undefined, and the capacity and limit + * are equal to the remaining part of calling buffer divided by the size of @c long. + * Any change to the byte buffer content is visible in the @c long @c long buffer view, and vice versa. + */ + LongLongBuffer* AsLongLongBufferN(void) const; + + /** + * @if OSPDEPREC + * Creates a new @c mchar buffer view of the underlying content of the byte buffer. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the AsWcharBufferN() method. + * @since 2.0 + * + * @return McharBuffer A pointer to the current position of the calling buffer + * @remarks The content of the view buffer starts at the current position of this buffer. + * The new buffer's position is zero, the mark is undefined, and the capacity and limit + * are equal to the remaining part of the calling buffer divided by the size of @c long. + * Any change to the byte buffer content is visible in the @c mchar buffer view, and vice versa. + * @endif + */ + McharBuffer* AsMcharBufferN(void) const; + + /** + * Creates a new wchar Buffer view of the underlying content of the byte buffer. + * + * @since 2.0 + * + * @return WcharBuffer pointer to the current position of the calling buffer + * @remarks The content of the view buffer start at the current position of this buffer. @n + * The new buffer's position is zero, the mark is undefined, and the capacity and limit + * are equal to the remaining part of the calling buffer divided by the size of @c long. @n + * Any changes to the calling buffer's content (that is, the content of %ByteBuffer instance) @n + * are visible in the WcharBuffer view, and vice versa. + */ + WcharBuffer* AsWcharBufferN(void) const; + + /** + * Creates a new @c short buffer view for the content of the byte buffer. + * + * @since 2.0 + * + * @return ShortBuffer pointer to the current position of the calling buffer + * @remarks The content of the view buffer starts at the current position of this buffer. + * The new buffer's position is zero, the mark is undefined, and the capacity and limit + * are equal to the remaining part of calling buffer divided by the size of @c long. + * Any change to the byte buffer content is visible in the @c short buffer view, and vice versa. + */ + ShortBuffer* AsShortBufferN(void) const; + + /** + * Copies the remaining bytes of the input %ByteBuffer instance into the calling %ByteBuffer object. @n + * It returns E_OVERFLOW if the remaining bytes in the current instance are less + * than the remaining bytes in the input instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] buffer The source buffer from which bytes are read @n + * It must not be the calling object. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The source buffer is same as destination buffer, + * that is, the current instance of the buffer. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow. @n + * The number of remaining bytes of the current buffer is smaller than + * the number of remaining bytes of the input buffer. + * @remarks After the copy operation, the current (destination) buffer's position and the given + * (source) buffer's positions are incremented by the number of bytes copied (the number of + * remaining bytes of the given buffer). @n + * If the remaining part of the current instance is greater than or equal to the remaining part of the input instance, + * the effect of this method and the ReadFrom(%ByteBuffer) method is the same. But when the remaining part of the + * current instance is less, the ReadFrom() method copies the number of remaining elements of the current + * instance while this method returns E_OVERFLOW and does not copy. + * @see ReadFrom() + * + * The following example demonstrates how to use the %CopyFrom() method. + * + * @code + * + * // Creates instances of ByteBuffer to act as source and destination buffers + * ByteBuffer srcBuf; + * ByteBuffer destBuf; + * + * // Declares an array of byte values + * byte pArray[] = {'A','B','C','D','E','F','G','H','I','J'}; + * + * // Initializes the source array with a capacity of ten elements. + * srcBuf.Construct(10); + * + * // Copies the ten values from pArray starting at position 0 to the srcBuf + * // Now, srcBuf's position = 10 + * srcBuf.SetArray(pArray, 0, 10); + * + * // Flips the buffer: The limit is set to the current position and + * // then the position is set to zero + * srcBuf.Flip(); // srcBuf's position = 0 and limit = 10 + * + * + * destBuf.Construct(20); + * + * // Copies from the srcBuf to the destBuf + * // Now, srcBuf's position = 10, the destBuf's position = 10 + * destBuf.CopyFrom(srcBuf); + * + * @endcode + * + * The following example has exactly the same effect as the above %CopyFrom() method. + * + * @code + * + * int copyNum = srcBuf.GetRemaining(); + * for (int i = 0; i < copyNum; i++) + * { + * byte b; + * + * // Reads from source buffer + * srcBuf.GetByte(b); // The srcBuf position is incremented by 1 + * + * // Writes to destination buffer + * destBuf.SetByte(b); // The destBuf position is incremented by 1 + * + * } + * @endcode + */ + result CopyFrom(ByteBuffer& buffer); + + /** + * Gets the specified number of bytes from the current instance of %ByteBuffer. + * + * @since 2.0 + * + * @return An error code + * @param[out] pArray A pointer to the destination array into which the bytes are written + * @param[in] index The starting index in the array of the first byte to write + * @param[in] length The number of bytes to write to the given array + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c pArray is @c null. + * @exception E_OUT_OF_RANGE A specified input parameter is invalid. @n + * The @c index or @c length is less than @c 0. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than @c length. + * @remarks This method copies @c length bytes from the current instance of %ByteBuffer to the given array, + * starting at the current position and at the given index in the array. + * After the copy operation, the position is incremented by @c length bytes. + * @see SetArray() + */ + result GetArray(byte* pArray, int index, int length); + + /** + * Gets the @c byte value from the buffer at the current position, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The @c byte value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the current position is not smaller than the limit. + * @see SetByte() + */ + result GetByte(byte& value); + + /** + * Gets the @c byte value at the given index. @n + * Provides a way for absolute indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the byte is read + * @param[out] value The @c byte value at the given @c index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is not smaller than the limit or less than @c 0. + * @see SetByte() + */ + result GetByte(int index, byte& value) const; + + /** + * Gets the size of @c double number of bytes from the buffer at the current position, converts + * it to the corresponding @c double equivalent, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The @c double value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than the size of @c double. + * @remarks This method reads the next size of @c double number of bytes at the current position, + * composing it into a @c double value, and then increments the position by the size of @c double. + * @see SetDouble() + */ + result GetDouble(double& value); + + /** + * Gets the size of @c double number of bytes at the given index and converts it to the equivalent @c double value. @n + * Provides a way for absolute indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the bytes are read + * @param[out] value The @c double value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified @c index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c double or less than @c 0. + * @remarks This method reads size of @c double number of bytes at the given index, + * composing them into a @c double value. + * @see SetDouble() + */ + result GetDouble(int index, double& value) const; + + /** + * Gets the size of @c float number of bytes from the buffer at the current position, converts + * it to the corresponding @c float equivalent, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The @c float value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than the size of @c float. + * @remarks This method reads the next size of @c float number of bytes at the current position, + * composing it into a @c float value, and then increments the position by the size of @c float. + * @see SetFloat() + */ + result GetFloat(float& value); + + /** + * Gets the size of @c float number of bytes at the given index and converts it to equivalent @c float value. @n + * Provides a way for absolute indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the bytes are read + * @param[out] value The @c float value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c float or less than @c 0. + * @remarks This method reads the size of @c float number of bytes at the given index, + * composing it into a @c float value. + * @see SetFloat() + */ + result GetFloat(int index, float& value) const; + + /** + * Gets the size of @c int number of bytes from the buffer at the current position, converts + * it to the corresponding @c int equivalent, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The @c int value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than the size of @c int. + * @remarks This method reads the next size of @c int number of bytes at the current position, + * composing them into an @c int value, and then increments the position by the size of @c int. + * @see SetInt() + */ + result GetInt(int& value); + + /** + * Gets the size of @c int number of bytes at the given index and converts it to the equivalent @c int value. @n + * Provides a way for absolute indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the bytes are read + * @param[out] value The @c int value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c int or negative. + * @remarks This method reads the size of @c int number of bytes at the given index, + * composing it into an @c int value. + * @see SetInt() + */ + result GetInt(int index, int& value) const; + + /** + * Gets the size of @c long number of bytes from the buffer at the current position, converts + * it to the corresponding @c long equivalent, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The @c long value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than the size of @c long. + * @remarks This method reads the next size of @c long number of bytes at the current position, + * composing it into a @c long value, and then increments the position by the size of @c long. + * @see SetLong() + */ + result GetLong(long& value); + + /** + * Gets the size of @c long number of bytes at the given index and converts it to equivalent @c long value. @n + * Provides a way for absolute indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the bytes are read + * @param[out] value The @c long value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified @c index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c long or less than @c 0. + * @remarks This method reads the size of @c long number of bytes at the given index, + * composing it into a @c long value. + * @see SetLong() + */ + result GetLong(int index, long& value) const; + + /** + * Gets the size of @c long @c long number of bytes from the buffer at the current position, converts + * it to the corresponding @c long @c long equivalent, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The @c long @c long value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than the size of @c long @c long. + * @remarks This method reads the next size of @c long @c long number of bytes at the current position, + * composing it into a @c long @c long value, and then increments the position by the size of @c long @c long. + * @see SetLongLong() + */ + result GetLongLong(long long& value); + + /** + * Gets the size of @c long @c long number of bytes at the given index and converts it to the equivalent @c long @c long value. @n + * Provides a way for absolute indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the bytes are read + * @param[out] value The @c long @c long value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c long @c long or less than @c 0. + * @remarks This method reads the size of @c long @c long number of bytes at the given index, + * composing it into a @c long @c long value. + * @see SetLongLong() + */ + result GetLongLong(int index, long long& value) const; + + /** + * @if OSPDEPREC + * Gets the size of @c wchar_t number of bytes from the buffer at the current position, converts + * it to the corresponding @c wchar_t equivalent, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the GetWchar(wchar_t& value) method. + * @since 2.0 + * + * @return An error code + * @param[out] value The @c wchar_t value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than the size of @c wchar_t. + * @remarks This method reads the next size of @c wchar_t number of bytes at the current position, + * composing it into a @c wchar_t value, and then increments the position by the size of @c wchar_t. + * @see SetMchar() + * @endif + */ + result GetMchar(wchar_t& value); + + /** + * Gets the size of @c wchar_t number of bytes from the buffer at the current position, converts + * it to the corresponding @c wchar_t equivalent, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The @c wchar_t value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than the size of @c wchar_t. + * @remarks This method reads the next size of @c wchar_t number of bytes at the current position, + * composing it into a @c wchar_t value, and then increments the position by the size of @c wchar_t. + * @see SetWchar() + */ + result GetWchar(wchar_t& value); + + /** + * @if OSPDEPREC + * Provides a way for absolute indexing and reading. @n + * It reads the size of @c wchar_t number of bytes at the given index and converts it to equivalent @c wchar_t value. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the GetWchar(int index, wchar_t& value) method. + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the bytes are read + * @param[out] value The @c wchar_t value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c wchar_t or less than @c 0. + * @remarks This method reads the size of @c wchar_t number of bytes at the given index, + * composing it into a @c wchar_t value. + * @see SetMchar() + * @endif + */ + result GetMchar(int index, wchar_t& value) const; + + /** + * Provides a way for absolute indexing and reading. @n + * It reads the size of @c wchar_t number of bytes at the given index and converts it to equivalent @c wchar_t value. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the bytes are read + * @param[out] value The @c wchar_t value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c wchar_t or less than @c 0. + * @remarks This method reads the size of @c wchar_t number of bytes at the given index, + * composing it into a @c wchar_t value. + * @see SetWchar() + */ + result GetWchar(int index, wchar_t& value) const; + + /** + * Gets the size of @c short number of bytes from the buffer at the current position, converts + * it to the corresponding @c short equivalent, and then increments the position. @n + * Provides a way for relative indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The @c short value at the current position in the %ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * the remaining bytes of this buffer are smaller than the size of @c short. + * @remarks This method reads the next size of @c short number of bytes at the current position, + * composing it into a @c short value, and then increments the position by the size of @c short. + * @see SetShort() + */ + result GetShort(short& value); + + /** + * Gets the size of @c short number of bytes at the given index and converts it to the equivalent @c short value. @n + * Provides a way for absolute indexing and reading. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current %ByteBuffer instance, from which the bytes are read + * @param[out] value The @c short value at the given index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c short or less than @c 0. + * @remarks This method reads the size of @c short number of bytes at the given index, + * composing it into a @c short value. + * @see SetShort() + */ + result GetShort(int index, short& value) const; + + /** + * Copies the remaining bytes of the input %ByteBuffer instance into the calling %ByteBuffer instance + * if the remaining part of the current instance is greater than or equal to the remaining part of the input instance. @n + * Otherwise, the number of bytes copied is equal to the number of remaining elements of the current instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] buffer The source buffer from which bytes are read @n + * It must not be the calling %ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * + * @remarks After the copy operation, the current (destination) buffer's position and the given + * (source) buffer's position are incremented by the number of elements copied (the lesser of + * the number of elements remaining in the current buffer and the given buffer). @n + * If the remaining part of the current instance is greater than or equal to the remaining part of the input instance, + * the effect of this method is the same as the CopyFrom() method. But when the remaining part of the + * current instance is less, the CopyFrom() method returns E_OVERFLOW and does not transfer; + * whereas this method copies the number of remaining elements of the current instance. + * @see CopyFrom() + * + * The following example demonstrates how to use the %ReadFrom() method. + * + * @code + * + * // Creates instances of %ByteBuffer to act as source and destination buffers + * ByteBuffer srcBuf; + * ByteBuffer destBuf; + * + * // Declares an array of byte values + * byte pArray[] = {'A','B','C','D','E','F','G','H','I','J'}; + * + * // Initializes the source array with capacity of ten elements. + * srcBuf.Construct(10); + * + * // Copies the 10 values from pArray starting at position 0 to srcBuf + * // Now, srcBuf's position = 10 + * srcBuf.SetArray(pArray, 0, 10); + * + * // Flips the buffer: The limit is set to the current position and + * // then the position is set to zero + * srcBuf.Flip(); // srcBuf's position = 0 and limit = 10 + * + * // Initializes the destination buffer with capacity of ten elements + * destBuf.Construct(10); + * + * // Sets the limit of destBuf to 5 + * destBuf.SetLimit(5); + * + * // Reads from the srcBuf to the destBuf + * // The destBuf's remaining is 5, smaller than the srcBuf's (10) + * // Therefore, five elements are transferred + * // srcBuf's position = 5, destBuf's position = 5 + * destBuf.ReadFrom(srcBuf); + * + * + * @endcode + * + * The following example has exactly the same effect as the above %ReadFrom() method. + * + * @code + * + * int copyNum = (destBuf.GetRemaining() < srcBuf.GetRemaing())? destBuf.GetRemaining() : srcBuf.GetRemaining(); + * for (int i = 0; i < copyNum; i++) + * { + * byte b; + * + * // Reads from the source buffer + * srcBuf.GetByte(b); // The srcBuf position is incremented by 1 + * + * // Writes to the destination buffer + * destBuf.SetByte(b); // The destBuf position is incremented by 1 + * + * } + * + * @endcode + */ + result ReadFrom(ByteBuffer& buffer); + + /** + * Sets the @c byte values on the specified array to the current instance of %ByteBuffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] pArray The array from which bytes are read + * @param[in] index The starting index of the array from where the first @c byte value is read + * @param[in] length The number of bytes to read from the given array + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c pArray is @c null. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index or length is less than @c 0. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes are smaller than @c length. + * @remarks This method copies the specified number (@c length) of @c byte values into + * the calling object of buffer from the source array, + * starting from the current position, and at the given index in the array. + * After the copy operation, the position is incremented by @c length. + * @see GetArray() + */ + result SetArray(const byte* pArray, int index, int length); + + /** + * Sets the given @c byte value into the calling %ByteBuffer object + * at the current position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The @c byte value to write to the current instance of %ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the current position is not smaller than the limit. + * @see GetByte() + */ + result SetByte(byte value); + + /** + * Sets the given @c byte value into the calling %ByteBuffer object at the specified index. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the current instance of %ByteBuffer at which the byte is written + * @param[in] value The @c byte value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is not smaller than the limit or less than @c 0. + * @see GetByte() + */ + result SetByte(int index, byte value); + + /** + * Sets the given @c double value into the calling %ByteBuffer object + * at the current position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The @c double value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes of this buffer are smaller than the size of @c double. + * @remarks This method writes the size of @c double number of bytes containing the given @c double value + * into the calling buffer, at the current position, and then increments the position by the size of @c double. + * @see GetDouble() + */ + result SetDouble(double value); + + /** + * Sets the given @c float value into the calling %ByteBuffer object + * at the current position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The @c float value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes of this buffer are smaller than the size of @c float. + * @remarks This method writes the size of @c float number of bytes containing the given @c float value + * into this buffer at the current position, and then increments the position by the size of @c float. + * @see GetFloat() + */ + result SetFloat(float value); + + /** + * Sets the given @c int value into the calling %ByteBuffer instance at the current + * position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The @c int value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes of this buffer are smaller than the size of @c int. + * @remarks This method writes the size of @c int number of bytes containing the given @c int value + * into this buffer at the current position, and then increments the position by the size of @c int. + * @see GetInt() + */ + result SetInt(int value); + + /** + * Sets the given @c long value into the calling %ByteBuffer instance at the current + * position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The @c long value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes of this buffer are smaller than size of @c long. + * @remarks This method writes the size of @c long number of bytes containing the given @c long value + * into this buffer at the current position, and then increments the position by the size of @c long. + * @see GetLong() + */ + result SetLong(long value); + + /** + * Sets the given @c long @c long value into the calling %ByteBuffer object at the current + * position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The @c long @c long value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes of this buffer are smaller than the size of @c long @c long. + * @remarks This method writes the size of @c long @c long number of bytes containing the given @c long @c long value + * into this buffer at the current position, and then increments the position by the size of @c long @c long. + * @see GetLongLong() + */ + result SetLongLong(long long value); + + /** + * @if OSPDEPREC + * Sets the given @c wchar_t value into the calling %ByteBuffer object at the current + * position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the SetWchar(wchar_t value) method. + * @since 2.0 + * + * @return An error code + * @param[in] value The @c wchar_t value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes of this buffer are smaller than size of @c wchar_t. + * @remarks This method writes the size of @c wchar_t number of bytes containing the given @c wchar_t value + * into this buffer at the current position, and then increments the position by the size of @c wchar_t. + * @see GetMchar() + * @endif + */ + result SetMchar(wchar_t value); + + /** + * Sets the given @c wchar_t value into the calling %ByteBuffer object at the current + * position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The @c wchar_t value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes of this buffer are smaller than size of @c wchar_t. + * @remarks This method writes the size of @c wchar_t number of bytes containing the given @c wchar_t value + * into this buffer at the current position, and then increments the position by the size of @c wchar_t. + * @see GetWchar() + */ + result SetWchar(wchar_t value); + + /** + * Sets the given @c short value into the current instance of %ByteBuffer at the current + * position, and then increments the position. @n + * Provides a way for relative indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The @c short value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OVERFLOW The operation (arithmetic/casting/conversion) has caused an overflow, or + * the remaining bytes of this buffer are smaller than the size of @c short. + * @remarks This method writes the size of @c short number of bytes containing the given @c short value + * into this buffer at the current position, and then increments the position by the size of @c short. + * @see GetShort() + */ + result SetShort(short value); + + /** + * Sets a @c double value at the specified index of the current instance of %ByteBuffer. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of current instance of %ByteBuffer at which the bytes are written + * @param[in] value The @c double value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus the size of @c double or less than @c 0. + * @remarks This method writes the size of @c double number of bytes containing the given @c double value + * into this buffer at the given index. + * @see GetDouble() + */ + result SetDouble(int index, double value); + + /** + * Sets a @c float value at the specified index of the calling %ByteBuffer object. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of current instance of %ByteBuffer at which the bytes are written + * @param[in] value The @c float value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus the size of @c float or less than @c 0. + * @remarks This method writes the size of @c float number of bytes containing the given @c float value + * into this buffer at the given index. + * @see GetFloat() + */ + result SetFloat(int index, float value); + + /** + * Sets a @c int value at the specified index of the calling %ByteBuffer object. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of current instance of %ByteBuffer at which the bytes are written + * @param[in] value The @c int value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus size of @c int or less than @c 0. + * @remarks This method writes the size of @c int number of bytes containing the given @c int value + * into this buffer at the given index. + * @see GetInt() + */ + result SetInt(int index, int value); + + /** + * Sets a @c long value at the specified index of the calling %ByteBuffer object. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the bytes are written + * @param[in] value The @c long value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus the size of @c long or less than @c 0. + * @remarks This method writes size of @c long number of bytes containing the given @c long value + * into this buffer at the given index. + * @see GetLong() + */ + result SetLong(int index, long value); + + /** + * Sets a @c long @c long value at the specified index of the calling %ByteBuffer object. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the bytes will be written + * @param[in] value The @c long @c long value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus the size of @c long @c long or less than @c 0. + * @remarks This method writes the size of @c long @c long number of bytes containing the given @c long @c long value + * into this buffer at the given index. + * @see GetLongLong() + */ + result SetLongLong(int index, long long value); + + /** + * @if OSPDEPREC + * Sets a @c wchar_t value at the specified index of the calling %ByteBuffer object. @n + * Provides a way for absolute indexing and writing. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the SetWchar(int index, wchar_t value) method. + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the bytes will be written + * @param[in] value The @c wchar_t value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus the size of @c wchar_t or less than @c 0. + * @remarks This method writes the size of @c wchar_t number of bytes containing the given @c wchar_t value + * into this buffer at the given index. + * @see GetMchar() + * @endif + */ + result SetMchar(int index, wchar_t value); + + /** + * Sets a @c wchar_t value at the specified index of the calling %ByteBuffer object. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the bytes will be written + * @param[in] value The @c wchar_t value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus the size of @c wchar_t or less than @c 0. + * @remarks This method writes the size of @c wchar_t number of bytes containing the given @c wchar_t value + * into this buffer at the given index. + * @see GetWchar() + */ + result SetWchar(int index, wchar_t value); + + /** + * Sets a @c short value at the specified index of the calling %ByteBuffer object. @n + * Provides a way for absolute indexing and writing. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of at which the bytes are written + * @param[in] value The @c short value to write + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is larger than the limit minus the size of @c short or less than @c 0. + * @remarks This method writes the size of @c short number of bytes containing the given @c short value + * into this buffer at the given index. + * @see GetShort() + */ + result SetShort(int index, short value); + + /** + * Creates a new %ByteBuffer whose content is a shared portion of + * the content of the calling %ByteBuffer object. + * + * @since 2.0 + * + * @return %ByteBuffer pointer to the current position of the calling object + * @remarks The content of the new buffer starts at the current position of the calling %ByteBuffer object. + * The new buffer's position is zero, its capacity and limit are + * the number of bytes remaining of the current instance of %ByteBuffer, + * and its mark is undefined. + */ + ByteBuffer* SliceN(void) const; + + /** + * Gets the pointer to the raw array of the calling buffer. @n + * If the capacity is zero, it returns @c null. + * + * @since 2.0 + * + * @return A pointer to the raw array of the calling buffer + */ + const byte* GetPointer(void) const; + + /** + * Compares the input Object with the calling %ByteBuffer instance. + * + * @since 2.0 + * + * @return @c true if the input object equals the calling %ByteBuffer instance, @n + * else @c false + * @param[in] obj The object instance to compare with the calling object + * @remarks This method returns @c true only if the specified object is also an instance of + * the %ByteBuffer class, the two buffers have the same number of remaining elements, and the two + * sequences of remaining elements are equal (considered independent of their starting positions). + * @see Tizen::Base::BufferBase::GetHashCode() + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The hash code of a buffer depends only upon its remaining elements. + */ + virtual int GetHashCode(void) const; + +private: + /** + * This copy constructor is intentionally declared as private to prohibit copying of objects by users. + */ + ByteBuffer(const ByteBuffer& buffer) + :__pByteBufferImpl(null) + { + Construct(buffer); + } + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + ByteBuffer& operator =(const ByteBuffer& buffer); + + /** + * Returns the size of byte(1). + * + * @return The size of byte(1) + */ + virtual int GetTypeSize(void) const; + + + friend class _ByteBufferImpl; + class _ByteBufferImpl * __pByteBufferImpl; + +}; // ByteBuffer + +}} // Tizen::Base + +#endif // _FBASE_BYTE_BUFFER_H_ diff --git a/inc/FBaseCharacter.h b/inc/FBaseCharacter.h new file mode 100644 index 0000000..6c65f7f --- /dev/null +++ b/inc/FBaseCharacter.h @@ -0,0 +1,639 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseCharacter.h + * @brief This is the header file for the %Character class. + * + * This header file contains the declarations of the %Character class. + */ +#ifndef _FBASE_CHARACTER_H_ +#define _FBASE_CHARACTER_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @enum UnicodeCategory + * + * Defines the constants used to distinguish the categories of Unicode characters. + * + * @since 2.0 + */ +enum UnicodeCategory +{ + UNICODE_SURROGATE = 1, /**< The surrogate Unicode category */ + UNICODE_MODIFIER, /**< The spacing modifier Unicode category */ + UNICODE_ARROW, /**< @if OSPDEPREC @deprecated This enum value is deprecated because this category is not valid anymore. @endif*/ + UNICODE_SPACE, /**< The space Unicode category */ + UNICODE_PUNCTUATION, /**< The punctuation Unicode category */ + UNICODE_CONTROL, /**< The control Unicode category */ + UNICODE_MATH, /**< The math Unicode category */ + UNICODE_DIGIT, /**< The digit Unicode category */ + UNICODE_HANGUL, /**< @if OSPDEPREC @deprecated This enum value is deprecated because this category is not valid anymore. @endif*/ + UNICODE_HANJA, /**< @if OSPDEPREC @deprecated This enum value is deprecated because this category is not valid anymore. @endif*/ + UNICODE_COMBINING, /**< @if OSPDEPREC @deprecated This enum value is deprecated because this category is not valid anymore. @endif*/ + UNICODE_LANGUAGE, /**< @if OSPDEPREC @deprecated This enum value is deprecated because this category is not valid anymore. @endif*/ + UNICODE_UPPERCASE, /**< The uppercase Unicode category*/ + UNICODE_LOWERCASE, /**< The lowercase Unicode category*/ + UNICODE_TITLECASE, /**< The titlecase Unicode category*/ + UNICODE_LETTER, /**< The letter Unicode category*/ + UNICODE_MARK, /**< The mark Unicode category*/ + UNICODE_CURRENCY, /**< The currency Unicode category*/ + UNICODE_SEPARATOR, /**< The separator Unicode category*/ + UNICODE_OTHER /**< The other Unicode category */ +}; + + +/** + * @class Character + * @brief This class is the wrapper class for the @c wchar_t built-in type. + * + * @since 2.0 + * + * The %Character class wraps a value of the @c wchar_t type. It also provides + * several methods for determining a Unicode character's category, and for + * converting the case of intrinsic characters. The class is useful when + * passing a Unicode character to a method expecting an instance of Object. + * + * The following example demonstrates how to use the %Character class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method converts the first character of the given @c string to the upper case. + * void + * MyClass::CharacterSample(String& str) + * { + * wchar_t chr, upper; + * + * str.GetCharAt(0, chr); + * + * // Converts to upper case + * upper = Character::ToUpper(chr); + * + * str.SetCharAt(upper, 0); + * } + * @endcode + */ +class _OSP_EXPORT_ Character + : public Object +{ +public: + /** + * Initializes this instance of %Character with the specified parameter. + * + * @since 2.0 + * + * @param[in] value A multi-byte character used to initialize the %Character instance + */ + Character(wchar_t value); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %Character + */ + Character(const Character& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Character(void); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %Character + */ + Character& operator =(const Character& rhs); + + /** + * Compares (ordinal comparison) the value of the calling instance + * with the value of the input %Character instance. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @param[in] value The character instance to compare with + * + * @code + * @li < 0 if the value of the current instance is less than the value of the input instance + * @li == 0 if the value of the current instance is equal to the value of the input instance + * @li > 0 if the value of the current instance is greater than the value of the input instance + * @endcode + * + */ + int CompareTo(const Character& value) const; + + /** + * Checks whether the value of the Object parameter is equal + * to the value of the calling object. + * + * @since 2.0 + * @return @c true if the input Object is equal to the calling %Object, @n + * else @c false + * @param[in] obj The object to compare with the calling object + * @see Tizen::Base::Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Returns the value of the current instance as a + * @c wchar_t. + * + * @since 2.0 + * + * @return The value of this instance as + * a @c wchar_t + */ + wchar_t ToMchar(void) const; + + /** + * @if OSPDEPREC + * Converts the Unicode characters of the calling object to its equivalent lowercase. @n + * The Unicode characters other than English alphabets are not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use ToLowerCase() method that supports Unicode characters other than English alphabets. + * + * @since 2.0 + * @endif + */ + void ToLower(void); + + + /** + * Converts the Unicode characters of the calling object to its equivalent lowercase. @n + * The Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + */ + void ToLowerCase(void); + + + /** + * @if OSPDEPREC + * Converts the Unicode characters of the current object to its equivalent uppercase. @n + * The Unicode characters other than English alphabets are not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use ToUpperCase() method that supports the Unicode characters other than English alphabets. + * + * @since 2.0 + * @endif + */ + void ToUpper(void); + + + /** + * Converts the Unicode characters of the current object to its equivalent uppercase. @n + * The Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + */ + void ToUpperCase(void); + + + /** + * Returns a string representing the value of the calling %Character instance. + * + * @since 2.0 + * + * @return An instance of String class that + * contains a Unicode representation of the calling instance + */ + String ToString(void) const; + + /** + * Returns a string representation of the input + * @c wchar_t value. + * + * @since 2.0 + * + * @return An instance of the String class + * that contains the Unicode representation of the + * input value + * @param[in] value The Unicode character to convert + */ + static String ToString(wchar_t value); + + /** + * Categorizes a Unicode character into a group identified by + * one of the UnicodeCategory values. + * + * @since 2.0 + * + * @return A value of type UnicodeCategory that identifies the group that contains the specified @c ch + * @param[in] ch The Unicode character to categorize + * + */ + static UnicodeCategory GetUnicodeCategory(wchar_t ch); + + /** + * @if OSPDEPREC + * Converts the input Unicode character to its equivalent lowercase. @n + * The Unicode characters other than English alphabets are not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use ToLowerCase(wchar_t ch) method that supports the Unicode characters other than English alphabets. + * + * @since 2.0 + * @return An lowercase equivalent of the input Unicode character + * @param[in] ch The Unicode character to convert + * @endif + */ + static wchar_t ToLower(wchar_t ch); + + /** + * Converts the input Unicode character to its equivalent lowercase. @n + * The Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + * + * @return An lowercase equivalent of the input Unicode character + * @param[in] ch The Unicode character to convert + */ + static wchar_t ToLowerCase(wchar_t ch); + + /** + * @if OSPDEPREC + * Converts the input Unicode character to its equivalent uppercase. @n + * The Unicode characters other than English alphabets are not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use ToUpperCase(wchar_t ch) method that supports Unicode characters other than English alphabets. + * + * @since 2.0 + * @return An uppercase equivalent of the input Unicode character + * @param[in] ch The Unicode character to convert + * @endif + */ + static wchar_t ToUpper(wchar_t ch); + + /** + * Converts the input Unicode character to its equivalent uppercase. @n + * The Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + * + * @return An uppercase equivalent of the input Unicode character + * @param[in] ch The Unicode character to convert + */ + static wchar_t ToUpperCase(wchar_t ch); + + /** + * Checks whether the input character is an alphanumeric character (letter or digit). @n + * A character is considered to be an alphanumeric character if either Character::isLetter(wchar_t ch) or Character::isDigit(wchar_t ch) returns true for the character + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompCharacterIsAlphaNumericPage "here". + * @endif + * @return @c true if the input character is alphanumeric, @n + * else @c false + * @param[in] ch The Unicode character + */ + static bool IsAlphaNumeric(wchar_t ch); + + /** + * @if OSPCOMPAT + * @page CompCharacterIsAlphaNumericPage Compatibility for IsAlphaNumeric() + * @section CompCharacterIsAlphaNumericPageIssueSection Issues + * Implementing this method in OSP compatible applications has the following issues: @n + * + * -# The method returns true only if the character is alphabet character and cannot checks other Unicode character in Letter and digit category. + * + * @section CompCharacterIsAlphaNumericPageSolutionSection Resolutions + * + * This issue has been resolved in Tizen. @n + * @endif + */ + + + /** + * Checks whether the input character is a digit. + * + * @since 2.0 + * + * @return @c true if the input character is a digit, @n + * else @c false + * @param[in] ch The Unicode character + */ + static bool IsDigit(wchar_t ch); + + /** + * Checks whether the input character is a Unicode letter. + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompCharacterIsLetterPage "here". + * @endif + * @return @c true if the input character is an alphabet, @n + * else @c false + * @param[in] ch The Unicode character + */ + static bool IsLetter(wchar_t ch); + + /** + * @if OSPCOMPAT + * @page CompCharacterIsLetterPage Compatibility for IsLetter() + * @section CompCharacterIsLetterPageIssueSection Issues + * Implementing this method in OSP compatible applications has the following issues: @n + * + * -# The method returns true only if the character is alphabet character and cannot checks other Unicode character in Letter category. + * + * @section CompCharacterIsLetterPageSolutionSection Resolutions + * + * This issue has been resolved in Tizen. @n + * @endif + */ + + /** + * @if OSPDEPREC + * Checks whether the input character is an lowercase alphabet. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use IsLowerCase(wchar_t ch) method that supports Unicode characters. + * @since 2.0 + * + * @return @c true if the input character is an lowercase English alphabet, @n + * else @c false + * @param[in] ch The Unicode character + * @endif + */ + static bool IsLower(wchar_t ch); + + /** + * Checks whether the input character is an lowercase alphabet. @n + * Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + * + * @return @c true if the input character is an lowercase alphabet, @n + * else @c false + * @param[in] ch The Unicode character + */ + static bool IsLowerCase(wchar_t ch); + + /** + * @if OSPDEPREC + * Checks whether the input character is an uppercase alphabet. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use IsUpperCase(wchar_t ch) method that also supports Unicode characters other than English alphabets. + * @since 2.0 + * + * @return @c true if the input character is an uppercase alphabet, @n + * else @c false + * @param[in] ch The Unicode character + * @endif + */ + static bool IsUpper(wchar_t ch); + + /** + * Checks whether the input character is an uppercase alphabet. @n + * Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + * + * @return @c true if the input character is an uppercase alphabet, @n + * else @c false + * @param[in] ch The Unicode character + */ + static bool IsUpperCase(wchar_t ch); + + /** + * Returns the value of the input character in the supplied radix. @n + * The value of radix must be between RADIX_MIN and RADIX_MAX. + * + * @since 2.0 + * + * @return A integer value of the input character in the supplied radix + * @param[in] ch The character to determine the value + * @param[in] radix The radix + */ + static int ToDigit(wchar_t ch, int radix); + + /** + * Returns the value which represents the input digit with specified radix. @n + * The value of radix must be between RADIX_MIN and RADIX_MAX. + * + * @since 2.0 + * + * @return A Unicode character of the input digit with specified radix; null character (U+0000) otherwise + * @param[in] digit The digit to determine the value + * @param[in] radix The radix + */ + static wchar_t ForDigit(int digit, int radix); + + /** + * Gets the numeric value of the input unicode character. @n + * This is used when some numeric values are fractions, negative, or too large for @c int value. + * + * @since 2.0 + * + * @return A @c double value @n NO_NUMERIC_VALUE for characters without any numeric values in the Unicode %Character. + * @param[in] ch A Unicode character + */ + static double GetNumericValue(wchar_t ch); + + /** + * Checks whether the input character is defined, which usually means that it is assigned a character in the Unicode. + * + * @since 2.0 + * + * @return @c true if the Unicode character is an assigned character, @n + * else @c false + * @param[in] ch A Unicode character + */ + static bool IsDefined(wchar_t ch); + + /** + * Checks whether the input character is a whitespace character. @n + * A character is considered to be a whitespace character if and only if it satisfies one of the following criteria: + * + * @since 2.0 + * + * @return @c true if the Unicode character is a whitespace character, @n + * else @c false + * @param[in] ch A Unicode character + * + * @code + * It is a Unicode Separator character, but is not also a non-breaking space (U+00A0 NBSP or U+2007 Figure Space or U+202F Narrow NBSP). + * It is U+0009 HORIZONTAL TABULATION. + * It is U+000A LINE FEED. + * It is U+000B VERTICAL TABULATION. + * It is U+000C FORM FEED. + * It is U+000D CARRIAGE RETURN. + * It is U+001C FILE SEPARATOR. + * It is U+001D GROUP SEPARATOR. + * It is U+001E RECORD SEPARATOR. + * It is U+001F UNIT SEPARATOR. + * @endcode + */ + static bool IsWhitespace(wchar_t ch); + + + /** + * Checks whether the input character is a title character. + * + * @since 2.0 + * + * @return @c true if the Unicode character is a title character, @n + * else @c false + * @param[in] ch A Unicode character + */ + static bool IsTitleCase(wchar_t ch); + + /** + * Returns the title case equivalent for the input character if it exists. + * + * @since 2.0 + * + * @return A title case character equivalent for the input character. The character itself is returned if none is defined + * @param[in] ch A Unicode character + */ + static wchar_t ToTitleCase(wchar_t ch); + + /** + * Checks whether the input character is an ISO control code or not. + * + * @since 2.0 + * + * @return @c true if the Unicode character is an ISO control character, @n + * else @c false + * @param[in] ch A Unicode character + */ + static bool IsISOControl(wchar_t ch); + + + /** + * A constant holding the largest value of type @c wchar_t, 0xFFFF. + * + * @since 2.0 + */ + static const wchar_t VALUE_MAX = 0x10FFFF; + + /** + * A constant holding the smallest value of type wchar_t, 0x0000. + * + * @since 2.0 + */ + static const wchar_t VALUE_MIN = 0x0000; + + /** + * The minimum radix available for conversion to and from strings.@n + * As value as RADIX_BINARY. + * + * @since 2.0 + */ + static const int RADIX_MIN = 2; + + /** + * The radix for binary number. + * + * @since 2.0 + */ + static const int RADIX_BINARY = 2; + + /** + * The radix for decimal number. + * + * @since 2.0 + */ + static const int RADIX_DECIMAL = 10; + + /** + * The radix for octal number. + * + * @since 2.0 + */ + static const int RADIX_OCTAL = 8; + + /** + * The radix for hexadecimal number. + * + * @since 2.0 + */ + static const int RADIX_HEXADECIMAL = 16; + + /** + * The maximum radix available for conversion to and from strings. Same value as RADIX_HEXADECIMAL. + * + * @since 2.0 + */ + static const int RADIX_MAX = 36; + + /** + * Special value that is returned by GetNumericValue(wchar_t ch) when no numeric value is defined for the unicode character. + * + * @since 2.0 + */ + static const double NO_NUMERIC_VALUE = -123456789; + +private: + friend class Int8; + friend class Short; + friend class Long; + friend class Integer; + + wchar_t __val; + + friend class _CharacterImpl; + class _CharacterImpl * __pCharacterImpl; + +}; // Character + +}} // Tizen::Base + +#endif // _FBASE_CHARACTER_H_ diff --git a/inc/FBaseCol.h b/inc/FBaseCol.h new file mode 100644 index 0000000..ba0cf21 --- /dev/null +++ b/inc/FBaseCol.h @@ -0,0 +1,78 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseCol.h + * @brief This is the header file for the %Collection namespace. + * + * This header file contains the declarations and descriptions of the %Collection namespace. + * + */ + +#ifndef _FBASE_COL_H_ +#define _FBASE_COL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * @namespace Tizen::Base::Collection + * @brief This namespace contains classes and interfaces for various collections. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %Collection namespace contains classes and interfaces for various collections + * (such as lists, maps, stacks, and queues), which are an aggregation of similar objects. + * + * For more information on the %Base::Collection namespace features, see Collection. + * + * The following diagram illustrates the relationships between the classes belonging to the %Collection namespace. + * + * @image html base_collection_namespace_obj_based_classdiagram.png + * + * @image html base_collection_namespace_template_based_classdiagram.png + * + * + * + * + */ + +namespace Tizen { namespace Base { namespace Collection +{ + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_H_ diff --git a/inc/FBaseColAllElementsDeleter.h b/inc/FBaseColAllElementsDeleter.h new file mode 100644 index 0000000..db5288d --- /dev/null +++ b/inc/FBaseColAllElementsDeleter.h @@ -0,0 +1,58 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColAllElementsDeleter.h + * @brief This is the header file for the %AllElementsDeleter struct. + * + * This header file contains the declarations of the %AllElementsDeleter struct. + */ + +#ifndef _FBASE_COL_ALL_ELEMENTS_DELETER_H_ +#define _FBASE_COL_ALL_ELEMENTS_DELETER_H_ + +namespace Tizen { namespace Base { namespace Collection +{ +/** + * @struct AllElementsDeleter + * @brief This function object provides a resource clean-up function for collection + * + * This can be used with unique_ptr as a custom deleter. + * + * @since 2.0 + */ +struct AllElementsDeleter +{ + /** + * Deletes every element of the collection and the collection itself + * + * @since 2.0 + * + * @param[in] c The Collection to clean up + * @remarks Collection should be destructible and support RemoveAll(bool) method. + * IList, IMap and IMultiMap support this concept. + */ + template< typename Collection > + void operator ()(Collection* c) + { + c->RemoveAll(true); + delete c; + } +}; +}}} + +#endif // _FBASE_COL_ALL_ELEMENTS_DELETER_H_ diff --git a/inc/FBaseColArrayList.h b/inc/FBaseColArrayList.h new file mode 100644 index 0000000..429609f --- /dev/null +++ b/inc/FBaseColArrayList.h @@ -0,0 +1,670 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColArrayList.h + * @brief This is the header file for the %ArrayList class. + * + * This header file contains the declarations of the %ArrayList class. + */ +#ifndef _FBASE_COL_ARRAY_LIST_H_ +#define _FBASE_COL_ARRAY_LIST_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class ArrayList + * @brief This class represents a collection of objects that can be individually accessed by an index. + * + * @since 2.0 + * + * + * The %ArrayList class represents a collection of objects that can be individually accessed by an index. + * + * For more information on the class features, see ArrayList and LinkedList. + * + * The following example demonstrates how to use the %ArrayList class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * + * void + * MyClass::ArrayListSample(void) + * { + * ArrayList list(SingleObjectDeleter); + * + * list.Construct(); + * + * list.Add(new Integer(1)); // 1 + * list.Add(new Integer(2)); // 1,2 + * list.Add(new Integer(3)); // 1,2,3 + * + * Integer* pInt = static_cast< Integer* > (list.GetAt(0)); + * + * if (pInt->Equals(Integer(1))) + * { + * // Must be here + * } + * + * list.InsertAt(new Integer(4), 1); // 1,4,2,3 + * + * list.Remove(Integer(3)); // 1,4,2 + * + * list.RemoveAt(0); // 4,2 + * + * list.Sort(IntegerComparer()); // 2,4 + * + * // Uses an enumerator to access elements in the list + * IEnumerator* pEnum = list.GetEnumeratorN(); + * Object* pObj = null; + * while (pEnum->MoveNext() == E_SUCCESS) + * { + * pObj = pEnum->GetCurrent(); + * } + * + * delete pEnum; + * + * + * // Deallocates all objects + * // Because the destructor calls RemoveAll() internally, you don't need to call RemoveAll() to destroy all elements at the end. + * list.RemoveAll(); + * } + * @endcode + */ +class _OSP_EXPORT_ ArrayList + : public IList + , public Object +{ +public: + using IList::Add; + using IList::InsertAt; + using IList::Remove; + using IList::RemoveAt; + using IList::RemoveItems; + using IList::RemoveAll; + using IList::SetAt; + using IList::ContainsAll; + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @param[in] deleter The function pointer to type of the element deleter + * @remarks To create an owing collection, set the element deleter value as @c SingleObjectDeleter. This gives the collection the ownership of elements and the collection will destroy elements. @n + * On the other hand, to create a non-owning collection, you don't need to set the element deleter value, as @c NoOpDeleter is the default element deleter. + * It means that you don't transfer the ownership of elements to the collection. + * @remarks After creating an instance of the %ArrayList class, one of the Construct() methods must be called explicitly to initialize this instance. + * @see NoOpDeleter() + * @see SingleObjectDeleter() + * @see ArrayDeleter() + */ + explicit ArrayList(DeleterFunctionType deleter = NoOpDeleter); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~ArrayList(void); + + /** + * Initializes this instance of %ArrayList with the specified parameter and sets its initial capacity to the + * indicated value. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The number of elements @n + * The default capacity is @c 10. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c capacity is negative. + * @remarks If the number of elements added to the list reaches the current capacity, + * the capacity is automatically increased by memory reallocation. + * Therefore, if the size of the list can be estimated, + * specifying the initial capacity eliminates the need to perform a number of + * resizing operations while adding elements to the list. + * @see ArrayList() + */ + result Construct(int capacity = DEFAULT_CAPACITY); + + + /** + * Initializes this instance of %ArrayList by copying the elements of the specified + * collection. @n + * The capacity of the list is the same as the number of elements copied. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection A collection to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks This method performs a shallow copy. It copies just the pointer; not the element itself. + * @see ArrayList() + */ + result Construct(const ICollection& collection); + + /** + * Adds the specified object to the end of this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj An pointer to object to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see Remove() + */ + virtual result Add(Object* pObj); + + + /** + * Adds the elements of the specified collection to the end of this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection A collection to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see RemoveItems() + */ + virtual result AddItems(const ICollection& collection); + + + /** + * Gets an enumerator (an instance of the IEnumerator-derived class) of this list. + * + * @since 2.0 + * + * @return An instance of the IEnumerator-derived class, @n + * else @c null if some exception occurs + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual IEnumerator* GetEnumeratorN(void) const; + + /** + * Gets a bidirectional enumerator (an instance of the IBidirectionalEnumerator derived class) of this list. + * + * @since 2.0 + * + * @return An instance of the IBidirectionalEnumerator derived class, @n + * else @c null if some exception occurs + * @remarks Use this method to obtain a bidirectional enumerator (an instance of the IBidirectionalEnumerator derived class) + * to iterate over a collection (an instance of the IList derived class). + * The specific error code can be accessed using GetLastResult() method. + * @see Tizen::Base::Collection::IBidirectionalEnumerator + */ + virtual IBidirectionalEnumerator* GetBidirectionalEnumeratorN(void) const; + + /** + * Gets the object at the specified index of this list. + * + * @since 2.0 + * + * @return The object at the specified index of this list, @n + * else @c null if the index is not valid + * @param[in] index The index of the object in the calling list to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified @c index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements or less than @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetAt() + */ + virtual const Object* GetAt(int index) const; + + + /** + * Gets the object at the specified index of this list. + * + * @since 2.0 + * + * @return The object at the specified index of this list, @n + * else @c null if the index is not valid + * @param[in] index The index of the object to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified @c index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements or less than @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetAt() + */ + virtual Object* GetAt(int index); + + /** + * Gets the IList within the specified range of this list. + * + * @since 2.0 + * + * @return A pointer to IList, @n + * else @c null if some exception occurs + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. @n + * - The @c count is greater than the number of elements starting from @c startIndex + * or less than @c 0. + * @remarks The IList stores just the pointers to the elements in the list, not the elements themselves. + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual IList* GetItemsN(int startIndex, int count) const; + + /** + * Searches for an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Object& obj, int& index) const; + + /** + * Searches for an object starting from the specified index. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index for the search @n + * It must be less than the number of elements. + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Object& obj, int startIndex, int& index) const; + + /** + * Searches for an object within the specified range. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. @n + * - The @c count is greater than the number of elements starting from @c startIndex + * or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Object& obj, int startIndex, int count, int& index) const; + + /** + * Searches for the last occurrence of an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the last occurrence of the specified object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see IndexOf() + */ + virtual result LastIndexOf(const Object& obj, int& index) const; + + /** + * Inserts the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj The pointer to object to insert + * @param[in] index The index at which the object must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is greater than the number of elements or less than @c 0. + * @remarks The elements that follow the insertion point move down to accommodate the new element. + * If the @c index equals to the number of elements, then the new element + * is added at the end of this list. + * This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see Add() + * @see RemoveAt() + */ + virtual result InsertAt(Object* pObj, int index); + + /** + * Inserts the elements of the collection at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to insert + * @param[in] startIndex The starting index at which the collection must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c startIndex is greater than the number of elements or less than @c 0. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks The elements that follow the insertion point move down to accommodate the new element. + * If the @c startIndex equals to the number of elements then the new elements + * are added at the end of this list. + * This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see RemoveItems() + * @see AddItems() + */ + virtual result InsertItemsFrom(const ICollection& collection, int startIndex); + + /** + * Removes the first occurrence of the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj An object to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see Add() + * @see RemoveAt() + * @see RemoveAll() + */ + virtual result Remove(const Object& obj); + + /** + * Removes the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the object must be removed + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements or less than @c 0. + * @remarks The elements that follow the deletion point move up to occupy the vacated spot. + * @see InsertAt() + * @see Remove() + */ + virtual result RemoveAt(int index); + + /** + * Removes all the elements within the specified range. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. @n + * - The @c count is greater than the number of elements starting from @c startIndex + * or less than @c 0. + * @remarks The elements that follow the deletion point move up to occupy the vacated spot. + * @see AddItems() + */ + virtual result RemoveItems(int startIndex, int count); + + /** + * Removes all of the elements that are in the intersection of the specified @c collection + * and this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to remove from this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @see Remove() + * @see RemoveAt() + */ + virtual result RemoveItems(const ICollection& collection); + + /** + * Removes all of the object pointers in the collection and also removes all of the objects depending on the specified element deleter. + * This method can be called before the collection is deleted. + * + * @since 2.0 + */ + virtual void RemoveAll(void); + + /** + * Replaces the object at the specified index with the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj An pointer to object to set + * @param[in] index The index at which the object must be set + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements or less than @c 0. + * @see GetAt() + */ + virtual result SetAt(Object* pObj, int index); + + /** + * Sets the capacity of this list to the specified value. + * + * @since 2.0 + * + * @return An error code + * @param[in] newCapacity The new capacity of this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the @c newCapacity is negative. + * @remarks When the new capacity is less than the current capacity, the elements + * within the truncated memory are not destroyed. + * @see Construct() + * @see Trim() + * @see GetCapacity() + */ + virtual result SetCapacity(int newCapacity); + + /** + * Sorts the elements of this list using the comparer provided. + * + * @since 2.0 + * + * @return An error code + * @param[in] comparer The IComparer implementation to use when comparing elements + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + virtual result Sort(const IComparer& comparer); + + /** + * Sets the capacity to the actual number of elements in this list. + * + * @since 2.0 + */ + virtual void Trim(void); + + /** + * Gets the current capacity of this list. + * + * @since 2.0 + * + * @return The current capacity of this list + * @see SetCapacity() + */ + virtual int GetCapacity(void) const; + + /** + * Gets the number of objects currently stored in this list. + * + * @since 2.0 + * + * @return The number of objects currently stored in this list + */ + virtual int GetCount(void) const; + + /** + * Checks whether a list contains the specified object. + * + * @since 2.0 + * + * @return @c true if the object is present in the list, @n + * else @c false + * @param[in] obj The object to locate + * @see ContainsAll() + */ + virtual bool Contains(const Object& obj) const; + + /** + * Checks whether the list contains all the elements of the specified collection. + * + * @since 2.0 + * + * @return @c true if the list contains all the elements of the specified collection, @n + * else @c false + * @param[in] collection The collection to check for in the list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the given @c collection is empty, this method will return @c true. + * @see Contains() + */ + virtual bool ContainsAll(const ICollection& collection) const; + + /** + * Compares the specified Object instance with the calling %ArrayList instance. + * + * @since 2.0 + * + * @return @c true if the given object matches the calling List, @n + * else @c false + * @param[in] obj The object to compare with the calling list + * @remarks This method returns @c true only if the specified object @c obj is also an instance of %ArrayList class, + * both lists have the same size, and all the corresponding pairs of the elements in the two lists are equal. + * In other words, the two lists are equal if they contain the same elements in the same order. + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Distinguish between %ArrayList and LinkedList. + * + * @since 2.0 + * @return @c true if it is an %ArrayList, @n + * else @c false if it is a LinkedList. + */ + virtual bool IsRandomAccessible(void) const + { + return true; + } + + /** + * Gets the element deleter of the collection. + * + * @since 2.0 + * + * @return An function pointer to the existing element deleter + */ + virtual DeleterFunctionType GetDeleter(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] list The instance of the %ArrayList class to copy from + */ + ArrayList(const ArrayList& list); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] list An instance of %ArrayList + */ + ArrayList& operator =(const ArrayList& list); + + /** + * Sorts the specified sub-list. + * + * @return An error code + * @param[in] startIndex The starting point of the sub-list to sort + * @param[in] endIndex The end point of the sub-list to sort + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the elements. + */ + result QuickSort(int startIndex, int endIndex); + + /** + * Sets the element deleter of the collection. + * + * @since 2.0 + * + * @param[in] deleter An function pointer to the element deleter to set + */ + virtual void SetDeleter(DeleterFunctionType deleter); + + int __capacity; + int __count; + Object** __pObjArray; + int __modCount; + IComparer* __pComparer; + static const int DEFAULT_CAPACITY = 10; + DeleterFunctionType __deleter; + + friend class _ArrayListEnumerator; + friend class _ArrayListImpl; + class _ArrayListImpl* __pArrayListImpl; + +}; // ArrayList + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_ARRAY_LIST_H_ diff --git a/inc/FBaseColArrayListT.h b/inc/FBaseColArrayListT.h new file mode 100644 index 0000000..af74afe --- /dev/null +++ b/inc/FBaseColArrayListT.h @@ -0,0 +1,1314 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColArrayListT.h + * @brief This is the header file for the %ArrayListT class. + * + * This header file contains the declarations of the %ArrayListT class. + */ +#ifndef _FBASE_COL_ARRAY_LIST_T_H_ +#define _FBASE_COL_ARRAY_LIST_T_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +template< class Type > class __ArrayListEnumeratorT; + +/** + * @class ArrayListT + * @brief This class provides a template-based collection of objects that can be individually accessed by an index. + * + * @since 2.0 + * + * The %ArrayListT class provides a template-based collection of objects that can be individually accessed by an index. + * + * For more information on the class features, see ArrayList and LinkedList. + * + * The following example demonstrates how to use the %ArrayListT class to create and initialize an %ArrayListT instance and to print out its values. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::ArrayListTSample(void) + * { + * ArrayListT list; + * + * list.Construct(); + * + * int int1 = 1; + * int int2 = 2; + * int int3 = 3; + * int int4 = 4; + * + * list.Add(int1); // 1 + * list.Add(int2); // 1,2 + * list.Add(int3); // 1,2,3 + * + * int temp; + * for (int i = 0; i < list.GetCount(); i++) + * { + * list.GetAt(i, temp); + * } + * + * list.InsertAt(int4, 1); // 1,4,2,3 + * + * ComparerT* pIntComparer = new ComparerT(); + * list.Sort(*pIntComparer); // 1,2,3,4 + * + * delete pIntComparer; + * + * list.Remove(int3); // 1,2,4 + * + * list.RemoveAt(0); // 2,4 + * + * // Uses an enumerator to access elements in the list + * IEnumeratorT* pEnum = list.GetEnumeratorN(); + * while (pEnum->MoveNext() == E_SUCCESS) + * { + * pEnum->GetCurrent(temp); + * } + * + * delete pEnum; + * } + * @endcode + */ +template< class Type > +class ArrayListT + : public IListT< Type > + , public Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks After creating an instance of this class, one of the Construct() methods must be called explicitly to initialize this instance. + */ + ArrayListT(void) + : __capacity(0) + , __count(0) + , __pObjArray(null) + , __modCount(0) + , __pComparer(null) + { + } + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~ArrayListT(void) + { + if (__pObjArray != null) + { + delete[] __pObjArray; + } + } + + /** + * Initializes this instance of %ArrayListT with the specified parameter. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity of the class @n + * The default capacity is @c 10. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c capacity is negative. + * @remarks If the number of elements added to the list reaches its current capacity, + * the capacity is automatically increased by memory reallocation. + * Thus, if the size of the list can be estimated, + * specifying the initial capacity eliminates the need to perform a number of + * resizing operations while adding elements to the list. + * @see ArrayListT() + */ + result Construct(int capacity = DEFAULT_CAPACITY) + { + TryReturn(capacity >= 0, E_INVALID_ARG, "[%s] The capacity(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), capacity); + + result r = SetCapacity(capacity); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; + } + + /** + * Initializes this instance of %ArrayListT with the specified parameter. @n + * The capacity of the list is the same as the number of elements copied to it. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection A collection of elements to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @see ArrayListT() + */ + result Construct(const ICollectionT< Type >& collection) + { + result r = AddItems(collection); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + return r; + +CATCH: + delete[] __pObjArray; + __pObjArray = null; + + return r; + } + + /** + * Adds the specified object to the end of the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj An object to add to the list + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @see Remove() + */ + virtual result Add(const Type& obj) + { + if (__count >= __capacity) + { + result r = SetCapacity(__capacity + DEFAULT_CAPACITY); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + __pObjArray[__count++] = obj; + + __modCount++; + + return E_SUCCESS; + } + + /** + * Adds the elements of the specified collection to the end of the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection A collection of elements to add to the list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @see RemoveItems() + */ + virtual result AddItems(const ICollectionT< Type >& collection) + { + result r = E_SUCCESS; + + IEnumeratorT< Type >* pEnum = null; + int count = collection.GetCount(); + if (count > 0) + { + if (count > (__capacity - __count)) + { + r = SetCapacity(__count + count); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + pEnum = pCol->GetEnumeratorN(); + TryReturn(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + __modCount++; + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + Type item; + r = pEnum->GetCurrent(item); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + __pObjArray[__count++] = item; + } + } + + delete pEnum; + return E_SUCCESS; + +CATCH: + delete pEnum; + return r; + } + + /** + * Gets the elements of the list in an instance of the IEnumeratorT derived class. + * + * @since 2.0 + * + * @return An instance of the IEnumeratorT derived class if successful, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumeratorT + */ + virtual IEnumeratorT< Type >* GetEnumeratorN(void) const + { + result r = E_SUCCESS; + + __ArrayListEnumeratorT< Type >* pEnum = new __ArrayListEnumeratorT< Type >(*this, __modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Gets a bidirectional enumerator (an instance of the IBidirectionalEnumeratorT derived class) of this list. + * + * @since 2.0 + * + * @return An instance of the IBidirectionalEnumeratorT derived class, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks Use this method to obtain a bidirectional enumerator (an instance of the IBidirectionalEnumeratorT derived class) + * to iterate over a collection (an instance of the IListT derived class). + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IBidirectionalEnumeratorT + */ + virtual IBidirectionalEnumeratorT< Type >* GetBidirectionalEnumeratorN(void) const + { + result r = E_SUCCESS; + + __ArrayListEnumeratorT< Type >* pEnum = new __ArrayListEnumeratorT< Type >(*this, __modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Gets the object at the specified index of the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the object to read + * @param[out] obj An object to get from this list + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements or less than @c 0. + * @see SetAt() + */ + virtual result GetAt(int index, Type& obj) const + { + TryReturn(index >= 0 && index < __count, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0 and less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + obj = __pObjArray[index]; + return E_SUCCESS; + } + + /** + * Gets the object at the specified index of the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the object to read + * @param[out] obj An object to get from this list + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements or less than @c 0. + * @see SetAt() + */ + virtual result GetAt(int index, Type& obj) + { + TryReturn(index >= 0 && index < __count, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0 and less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + obj = __pObjArray[index]; + return E_SUCCESS; + } + + /** + * Gets a list of a specified number of elements starting from a specified index. + * + * @since 2.0 + * + * @return An instance of the IListT derived class within the specified range of the list, @n + * else @c null if an exception occurs + * @param[in] startIndex The index to start reading elements from + * @param[in] count The number of elements to read + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either greater than or equal to the number of elements or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual IListT< Type >* GetItemsN(int startIndex, int count) const + { + result r = E_SUCCESS; + + ArrayListT< Type >* pList = null; + + TryCatch(startIndex >= 0 && count >= 0, r = E_OUT_OF_RANGE, + "[%s] Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), startIndex, count); + TryCatch(startIndex < __count, r = E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + TryCatch(count <= __count && (startIndex + count <= __count), r = E_OUT_OF_RANGE, + "[%s] The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count, __count); + + pList = new ArrayListT< Type >(); + + r = pList->Construct(count); + TryCatch(r == E_SUCCESS, delete pList, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = startIndex; i < (startIndex + count); i++) + { + pList->__pObjArray[pList->__count++] = __pObjArray[i]; + } + + SetLastResult(E_SUCCESS); + return pList; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Searches for an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Type& obj, int& index) const + { + return IndexOf(obj, 0, __count, index); + } + + /** + * Searches for an object starting from the specified index. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index for the search @n + * It must be less than the number of elements. + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Type& obj, int startIndex, int& index) const + { + TryReturn(startIndex >= 0 && startIndex < __count, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + + return IndexOf(obj, startIndex, (__count - startIndex), index); + } + + /** + * Searches for an object within the specified range. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either greater than or equal to the number of elements or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Type& obj, int startIndex, int count, int& index) const + { + TryReturn(startIndex >= 0 && count >= 0, E_OUT_OF_RANGE, + "[%s] Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), startIndex, count); + TryReturn(startIndex < __count, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + TryReturn(count <= __count && (startIndex + count <= __count), E_OUT_OF_RANGE, + "[%s] The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count, __count); + + int arrayListCount = startIndex + count; + for (int i = startIndex; i < arrayListCount; i++) + { + if (obj == __pObjArray[i]) + { + index = i; + return E_SUCCESS; + } + } + + return E_OBJ_NOT_FOUND; + } + + /** + * Inserts an object at a specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to insert + * @param[in] index The index at which the object must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is greater than the number of elements or less than @c 0. + * @remarks The elements that follow the insertion point move down to accommodate the new element. + * If the @c index equals the number of elements in the list, the new element + * is added at the end of the list. + * @see Add() + * @see RemoveAt() + */ + virtual result InsertAt(const Type& obj, int index) + { + TryReturn(index >= 0 && index <= __count, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + result r = E_SUCCESS; + + if (__count >= __capacity) + { + r = SetCapacity(__capacity + DEFAULT_CAPACITY); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + for (int i = __count; i > index; i--) + { + __pObjArray[i] = __pObjArray[i - 1]; + } + + __count++; + __modCount++; + __pObjArray[index] = obj; + + return E_SUCCESS; + } + + /** + * Inserts the elements of a collection at a specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to insert + * @param[in] startIndex The index from which the collection must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c startIndex is greater than the number of elements or less than @c 0. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks The elements that follow the insertion point move down to accommodate the new elements. + * If the @c startIndex equals the number of elements in the list, the new elements + * are added at the end of the list. + * @see RemoveItems() + * @see AddItems() + */ + virtual result InsertItemsFrom(const ICollectionT< Type >& collection, int startIndex) + { + TryReturn(startIndex >= 0 && startIndex <= __count, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be greater than or equal to 0, and less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + + result r = E_SUCCESS; + + IEnumeratorT< Type >* pEnum = null; + int count = collection.GetCount(); + + if (count > 0) + { + if (count > (__capacity - __count)) + { + r = SetCapacity(__count + count); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + + __count += count; + for (int i = (__count - 1); i >= (startIndex + count); i--) + { + __pObjArray[i] = __pObjArray[i - count]; + } + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + pEnum = pCol->GetEnumeratorN(); + TryReturn(pEnum != null, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + __modCount++; + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + Type item; + + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(item); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + __pObjArray[startIndex++] = item; + } + } + + delete pEnum; + return E_SUCCESS; + +CATCH: + delete pEnum; + return r; + } + + /** + * Searches for the last occurrence of an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the last occurrence of the specified object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see IndexOf() + */ + virtual result LastIndexOf(const Type& obj, int& index) const + { + for (int i = (__count - 1); i >= 0; i--) + { + if (obj == __pObjArray[i]) + { + index = i; + return E_SUCCESS; + } + } + + return E_OBJ_NOT_FOUND; + } + + /** + * Removes the first occurrence of a specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see Add() + * @see RemoveAt() + * @see RemoveAll() + */ + virtual result Remove(const Type& obj) + { + int index; + result r = IndexOf(obj, index); + if (IsFailed(r)) + { + return E_OBJ_NOT_FOUND; + } + else + { + return RemoveAt(index); + } + } + + /** + * Removes all the elements of a specified collection from the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to remove from this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @see Remove() + * @see RemoveAt() + */ + virtual result RemoveItems(const ICollectionT< Type >& collection) + { + result r = E_SUCCESS; + int oldCount = __count; + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + IEnumeratorT< Type >* pEnum = pCol->GetEnumeratorN(); + TryCatch(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + Type item; + + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(item); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = Remove(item); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + + if (__count < oldCount) + { + Trim(); + } + + delete pEnum; + return E_SUCCESS; + +CATCH: + delete pEnum; + return r; + } + + /** + * Removes an object from a specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the object that is to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is greater than or equal to the number of elements or less than @c 0. + * @remarks The elements that follow the deleted object move up the list to occupy the empty location. + * @see InsertAt() + * @see Remove() + */ + virtual result RemoveAt(int index) + { + TryReturn(index < __count && index >= 0, E_OUT_OF_RANGE, + "[%s] The index MUST be greater than or equal to 0, and less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + __modCount++; + __count--; + + for (int i = index; i < __count; i++) + { + __pObjArray[i] = __pObjArray[i + 1]; + } + + Trim(); + + return E_SUCCESS; + } + + /** + * Removes all the elements within a specified range. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either greater than or equal to the number of elements or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * @remarks The elements that follow the deleted elements move up the list to occupy the empty locations. + * @see AddItems() + * @see InsertItemsFrom() + */ + virtual result RemoveItems(int startIndex, int count) + { + TryReturn(startIndex >= 0 && count >= 0, E_OUT_OF_RANGE, + "[%s] Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), startIndex, count); + TryReturn(startIndex < __count, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + TryReturn(count <= __count && (startIndex + count <= __count), E_OUT_OF_RANGE, + "[%s] The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count, __count); + + if (count > 0) + { + Type* newArray = new Type[__capacity]; + TryReturn(newArray != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + __modCount++; + __count -= count; + + for (int i = 0; i < startIndex; i++) + { + newArray[i] = __pObjArray[i]; + } + for (int i = startIndex; i < __count; i++) + { + newArray[i] = __pObjArray[i + count]; + } + + delete[] __pObjArray; + __pObjArray = newArray; + } + + return E_SUCCESS; + } + + /** + * Removes all elements in the list. + * + * @since 2.0 + */ + virtual void RemoveAll(void) + { + if (__count != 0) + { + delete[] __pObjArray; + __pObjArray = null; + + __count = 0; + __capacity = 0; + + __modCount++; + } + + } + + /** + * Sets the object at a specified index of the current instance of ByteBuffer with the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to set + * @param[in] index The index at which the object must be set + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements or less than @c 0. + * @see GetAt() + */ + virtual result SetAt(const Type& obj, int index) + { + TryReturn(index >= 0 && index < __count, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + __modCount++; + + __pObjArray[index] = obj; + + return E_SUCCESS; + } + + /** + * Sets the capacity of the list to a specified value. + * + * @since 2.0 + * + * @return An error code + * @param[in] newCapacity The new capacity to set for the list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c newCapacity is negative. + * @remarks If the new capacity is less than the current capacity, the memory + * is truncated and the elements within the truncated memory are destroyed. + * @see Construct() + * @see Trim() + * @see GetCapacity() + */ + virtual result SetCapacity(int newCapacity) + { + TryReturn(newCapacity >= 0, E_INVALID_ARG, "[%s] The newCapacity(%d) MUST be greater than or equal to 0.", + GetErrorMessage(E_INVALID_ARG), newCapacity); + + result r = E_SUCCESS; + if (__capacity != newCapacity) + { + Type* newArray = null; + if (newCapacity > 0) + { + newArray = new Type[newCapacity]; + TryCatch(newArray != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + if (__pObjArray != null) + { + int count = __count < newCapacity ? __count : newCapacity; + for (int i = 0; i < count; i++) + { + newArray[i] = __pObjArray[i]; + } + } + } + if (__pObjArray != null) + { + delete[] __pObjArray; + } + if (__count > newCapacity) + { + __modCount++; + __count = newCapacity; + } + __pObjArray = newArray; + __capacity = newCapacity; + } + + return r; + +CATCH: + return r; + } + + /** + * Sorts the elements in the list using a comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] comparer A pointer to IComparerT + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c comparer is not valid. + */ + virtual result Sort(const IComparerT< Type >& comparer) + { + if (0 == __count) + return E_SUCCESS; + + __pComparer = const_cast< IComparerT< Type >* >(&comparer); + result r = QuickSort(0, (__count - 1)); + if (IsFailed(r)) + { + AppLogException("[%s] Propagating.", GetErrorMessage(r)); + __pComparer = null; + + return r; + } + + return E_SUCCESS; + } + + /** + * Trims the capacity of a list to the actual number of elements in the list. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetCapacity() + */ + virtual void Trim(void) + { + if (__capacity == 0) + { + return; + } + + result r = SetCapacity(__count); + if (IsFailed(r)) + { + AppLogException("[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + } + } + + /** + * Gets the current capacity of the list. + * + * @since 2.0 + * + * @return The current capacity of the list + * @see SetCapacity() + */ + int GetCapacity(void) const + { + return __capacity; + } + + /** + * Gets the number of objects currently stored in the list. + * + * @since 2.0 + * + * @return The number of objects stored in the list + */ + virtual int GetCount(void) const + { + return __count; + } + + /** + * Checks whether a list contains the specified object. + * + * @since 2.0 + * + * @return @c true if the object is present in the list, @n + * else @c false + * @param[in] obj The object to locate + * @see ContainsAll() + */ + virtual bool Contains(const Type& obj) const + { + if (__count == 0) + { + return false; + } + + for (int i = 0; i < __count; i++) + { + if (obj == __pObjArray[i]) + { + return true; + } + } + + return false; + } + + /** + * Checks whether the list contains all the elements of the specified collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to check for in the list + * @param[out] out @c true if the list contains all the elements of the specified collection, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks If the given @c collection is empty, the @c out parameter will be set to @c true. + * @see Contains() + */ + virtual result ContainsAll(const ICollectionT< Type >& collection, bool& out) const + { + result r = E_SUCCESS; + out = false; + + if (collection.GetCount() == 0) + { + out = true; + return E_SUCCESS; + } + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + IEnumeratorT< Type >* pEnum = pCol->GetEnumeratorN(); + TryReturn(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + Type item; + + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(item); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + if (false == Contains(item)) + { + delete pEnum; + + return E_SUCCESS; + } + } + + + delete pEnum; + + out = true; + + return E_SUCCESS; + +CATCH: + delete pEnum; + + return r; + } + + /** + * Compares two instances of the %ArrayListT class. + * + * @since 2.0 + * + * @return @c true if the two instances match, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true if and only if the two instances contain the same elements in the same order. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const + { + const ArrayListT< Type >* other = dynamic_cast< const ArrayListT< Type >* >(&obj); + if (null == other) + { + return false; + } + else if (other == this) + { + return true; + } + else if (__count != other->__count) + { + return false; + } + else + { + for (int i = 0; i < __count; i++) + { + if (__pObjArray[i] != other->__pObjArray[i]) + { + return false; + } + } + } + + return true; + } + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const + { + int hash = 0; + for (int i = 0; i < __count; i++) + { + if (&(__pObjArray[i]) != null) + { + hash += reinterpret_cast< int >(&(__pObjArray[i])); + } + } + return hash; + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] list The instance of the %ArrayListT class to copy from + */ + ArrayListT(const ArrayListT< Type >& list); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] list An instance of %ArrayListT + */ + ArrayListT< Type >& operator =(const ArrayListT< Type >& list); + + /** + * Sorts a section of a list using a comparer. + * + * @return An error code + * @param[in] startIndex The start index of the section of the list + * @param[in] endIndex The end index of the section of the list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the elements. + */ + result QuickSort(int startIndex, int endIndex) + { + result r = E_SUCCESS; + + if (startIndex < endIndex) + { + int middleIndex; + int i = startIndex - 1; + int j = endIndex + 1; + while (true) + { + int compareResult = 1; + while ((compareResult > 0) && (j > static_cast< int >(startIndex))) + { + j--; + + r = __pComparer->Compare(__pObjArray[j], __pObjArray[startIndex], compareResult); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + compareResult = -1; + while ((compareResult < 0) && (i < static_cast< int >(endIndex))) + { + i++; + + r = __pComparer->Compare(__pObjArray[i], __pObjArray[startIndex], compareResult); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + if (i < j) + { + Type temp = __pObjArray[j]; + __pObjArray[j] = __pObjArray[i]; + __pObjArray[i] = temp; + } + else + { + middleIndex = j; + break; + } + } + + r = QuickSort(startIndex, middleIndex); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = QuickSort(middleIndex + 1, endIndex); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; + } + + int __capacity; + int __count; + Type* __pObjArray; + int __modCount; + IComparerT< Type >* __pComparer; + static const int DEFAULT_CAPACITY = 10; + + friend class __ArrayListEnumeratorT< Type >; + +}; // ArrayListT + +// +// @class __ArrayListEnumeratorT +// @brief This class is an implementation of the IEnumeratorT interface for the %ArrayListT class. +// @since 2.0 +// +template< class Type > +class __ArrayListEnumeratorT + : public IBidirectionalEnumeratorT< Type > + , public Tizen::Base::Object +{ +public: + __ArrayListEnumeratorT(const ArrayListT< Type >& list, int modCount) + : __list(list) + , __modCount(modCount) + , __position(-1) + { + } + + virtual ~__ArrayListEnumeratorT(void) + { + } + + virtual result GetCurrent(Type& obj) const + { + TryReturn((__modCount == __list.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn((__position > -1) && (__position < static_cast (__list.__count)), E_INVALID_OPERATION, + "[%s] Current position(%d) is before the first element or past the last element.", GetErrorMessage(E_INVALID_OPERATION), __position); + + obj = __list.__pObjArray[__position]; + return E_SUCCESS; + } + + virtual result MoveNext(void) + { + TryReturn((__modCount == __list.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + if ((__position + 1) >= static_cast< int >(__list.__count)) + { + return E_OUT_OF_RANGE; + } + else + { + __position++; + } + + return E_SUCCESS; + } + + virtual result Reset(void) + { + TryReturn((__modCount == __list.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __position = -1; + return E_SUCCESS; + } + + virtual result MovePrevious(void) + { + TryReturn(__modCount == __list.__modCount, E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + TryReturn(__position > 0, E_OUT_OF_RANGE, "[%s] Reached start of the list, no previous element", GetErrorMessage(E_OUT_OF_RANGE)); + + __position--; + + return E_SUCCESS; + } + + virtual result ResetLast(void) + { + TryReturn(__modCount == __list.__modCount, E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __position = __list.__count; + return E_SUCCESS; + } + +private: + const ArrayListT< Type >& __list; + int __modCount; + int __position; + +}; //__ArrayListEnumeratorT + +} } } // Tizen::Base::Collection + +#endif // _FBASE_COL_ARRAY_LIST_T_H_ diff --git a/inc/FBaseColHashMap.h b/inc/FBaseColHashMap.h new file mode 100644 index 0000000..851aade --- /dev/null +++ b/inc/FBaseColHashMap.h @@ -0,0 +1,499 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColHashMap.h + * @brief This is the header file for the %HashMap class. + * + * This header file contains the declarations of the %HashMap class. + */ +#ifndef _FBASE_COL_HASH_MAP_H_ +#define _FBASE_COL_HASH_MAP_H_ + +#include +#include +#include + +namespace Tizen { namespace Base { namespace Collection +{ + +class _HashMapEntry; + +/** + * @class HashMap + * @brief This class represents a collection of associated keys and values that are organized based on the hash code of the key. + * + * @since 2.0 + * + * The %HashMap class contains unique keys and each key maps to one single value. + * The key and value cannot be a @c null reference. + * + * For more information on the class features, see HashMap and MultiHashMap. + * + * The following example demonstrates how to use the %HashMap class to create and initialize a %HashMap instance and to use its methods. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * + * void + * MyClass::HashMapSample(void) + * { + * HashMap map(SingleObjectDeleter); + * + * // Constructs a %HashMap instance with default capacity, load factor, hash code provider, and comparer + * map.Construct(); + * + * map.Add(new String(L"Zero"), new Integer(0)); // map.GetCount() : 1, map : (Zero -> 0) + * map.Add(new String(L"One"), new Integer(1)); // map.GetCount() : 2, map : (Zero -> 0), (one -> 1) + * map.Add(new String(L"Two"), new Integer(2)); // map.GetCount() : 3, map : (Zero -> 0), (one -> 1), (Two -> 2) + * + * // Gets a value with the specified key + * Integer* pValue = static_cast< Integer* > (map.GetValue(String(L"Zero"))); // pValue : 0 + * + * // Removes the value with the specified key + * map.Remove(String(L"Zero")); // map.GetCount() : 2, map : (one -> 1), (Two -> 2) + * + * // Uses an enumerator to access elements in the list + * IMapEnumerator* pMapEnum = map.GetMapEnumeratorN(); + * String* pKey = null; + * while (pMapEnum->MoveNext() == E_SUCCESS) + * { + * pKey = static_cast< String* > (pMapEnum->GetKey()); + * pValue = static_cast< Integer* > (pMapEnum->GetValue()); + * } + * + * delete pMapEnum; + * + * // Deallocates all objects + * // Because the destructor calls RemoveAll() internally, you don't need to call RemoveAll() to destroy all elements at the end. + * map.RemoveAll(); + * + * } + * @endcode + */ +class _OSP_EXPORT_ HashMap + : public IMap + , public Object +{ +public: + using IMap::Add; + using IMap::Remove; + using IMap::RemoveAll; + using IMap::SetValue; + using IMap::ContainsKey; + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @param[in] deleter The function pointer to type of the element deleter + * @remarks To create an owing collection, set the element deleter value as @c SingleObjectDeleter. This gives the collection the ownership of elements and the collection will destroy elements. @n + * On the other hand, to create a non-owning collection, you don't need to set the element deleter value, as @c NoOpDeleter is the default element deleter. + * It means that you don't transfer the ownership of elements to the collection. + * @see NoOpDeleter() + * @see SingleObjectDeleter() + * @see ArrayDeleter() + */ + explicit HashMap(DeleterFunctionType deleter = NoOpDeleter); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~HashMap(void); + + /** + * Initializes an instance of an empty %HashMap class with the initial capacity and load factor. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity + * @param[in] loadFactor The maximum ratio of elements to buckets + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, @n + * the @c capacity or the @c loadFactor is negative. + * @remarks The GetHashCode() method of key objects is used for hashing and + * the Equals() method of key objects is used for comparing keys. + * @see HashMap() + */ + result Construct(int capacity = 16, float loadFactor = 0.75); + + /** + * Initializes an instance of a %HashMap class by copying the elements of the specified map. + * + * @since 2.0 + * + * @return An error code + * @param[in] map The map to copy + * @param[in] loadFactor The maximum ratio of elements to buckets + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c loadFactor is negative. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c map is modified during the operation of this method. + * @remarks This method performs a shallow copy. It copies only the pointer; not the element itself. + * @see HashMap() + */ + result Construct(const IMap& map, float loadFactor = 0.75); + + /** + * Initializes an instance of an empty %HashMap class with the specified initial capacity, load factor, hash code provider, and comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity @n + * If it is @c 0, the default capacity(16) is used. + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor(0.75) is used. + * @param[in] provider An instance of the IHashCodeProvider derived class that supplies the hash codes for all the keys in this map + * @param[in] comparer An instance of the IComparer derived class to use when comparing the keys + * + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c capacity or the @c loadFactor is negative. + * @remarks The instances of hash code provider and comparer will not be deallocated later from this map. + * @see HashMap() + */ + result Construct(int capacity, float loadFactor, const IHashCodeProvider& provider, const IComparer& comparer); + + /** + * Initializes an instance of a %HashMap class by copying the elements of a specified map with a specified load factor, hash code provider, and comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] map The map to copy + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor(0.75) is used. + * @param[in] provider An instance of the IHashCodeProvider derived class that supplies the hash codes for all keys in this map + * @param[in] comparer An instance of the IComparer derived class to use when comparing keys + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c loadFactor is negative. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c map is modified during the operation of this method. + * @remarks This method performs a shallow copy. It copies only the pointer; not the element itself. + * @remarks The instances of hash code provider and comparer will not be deallocated later from this map. + * @see HashMap() + */ + result Construct(const IMap& map, float loadFactor, const IHashCodeProvider& provider, const IComparer& comparer); + + /** + * Adds the specified key-value pair to a map. + * + * @since 2.0 + * + * @return An error code + * @param[in] pKey The pointer to key of the value to add + * @param[in] pValue The pointer to value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_ALREADY_EXIST The specified @c pKey already exists. + * @remarks This method performs a shallow copy. It adds only the pointer; not the element itself. + * @see Remove() + */ + virtual result Add(Object* pKey, Object* pValue); + + /** + * Gets an enumerator (an instance of the IMapEnumerator derived class) of this map. + * + * @since 2.0 + * + * @return An instance of the IMapEnumerator derived class, if successful @n + * else @c null if an exception occurs + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * @see Tizen::Base::Collection::IMapEnumerator + */ + virtual IEnumerator* GetEnumeratorN(void) const; + + /** + * Gets the elements of the map in an instance of the IMapEnumerator derived class. + * + * @since 2.0 + * + * @return An instance of the IMapEnumerator derived class, @n + * else @c null if an exception occurs + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * @see Tizen::Base::Collection::IMapEnumerator + */ + virtual IMapEnumerator* GetMapEnumeratorN(void) const; + + /** + * Gets the value associated with the specified key. + * + * @since 2.0 + * + * @return The value associated with the key, @n + * else @c null if an exception occurs + * @param[in] key The key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetValue() + */ + virtual const Object* GetValue(const Object& key) const; + + /** + * Gets the value associated with the specified key. + * + * @since 2.0 + * + * @return The value associated with the key, @n + * else @c null if an exception occurs + * @param[in] key The key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetValue() + */ + virtual Object* GetValue(const Object& key); + + /** + * Gets a list of all the keys in a map. + * + * @since 2.0 + * + * @return A pointer to an IList object containing all the keys in the map, @n + * else @c null if an exception occurs + * @remarks The order of the keys is the same as the corresponding values in the IList interface returned by the GetValuesN() method. + * The IList stores just the pointers to the elements in the map, not the elements themselves. + * The specific error code can be accessed using the GetLastResult() method. + * @see GetValuesN() + */ + virtual IList* GetKeysN(void) const; + + /** + * Gets all the values in the map. + * + * @since 2.0 + * + * @return A pointer to an IList object containing all the values in the map, @n + * else @c null if an exception occurs + * @remarks The IList stores just the pointers to the elements in the map, not the elements themselves. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetKeysN() + */ + virtual IList* GetValuesN(void) const; + + /** + * Removes the values associated with a specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see Add() + */ + virtual result Remove(const Object& key); + + /** + * Removes all the object pointers in the collection. @n + * This method can be called before deleting a collection. + * + * @since 2.0 + */ + virtual void RemoveAll(void); + + /** + * Sets the value associated with a specified key by allocating it a new value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key whose value is to replace + * @param[in] pValue The pointer to new value to replace + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks To add a new key-value pair, use the Add() method. + * @see Add() + * @see GetValue() + */ + virtual result SetValue(const Object& key, Object* pValue); + + /** + * Gets the number of pairs currently stored in the map. + * + * @since 2.0 + * + * @return The pairs stored in the map + */ + virtual int GetCount(void) const; + + /** + * Checks whether the map contains the specified key. + * + * @since 2.0 + * + * @return @c true if the map contains the specified key, @n + * else @c false + * @param[in] key The key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see ContainsValue() + */ + virtual bool ContainsKey(const Object& key) const; + + /** + * Checks whether the map contains the specified value. + * + * @since 2.0 + * + * @return @c true if the map contains the specified value, @n + * else @c false + * @param[in] value The value to locate + * + * @see ContainsKey() + */ + virtual bool ContainsValue(const Object& value) const; + + /** + * Compares two instances of the %HashMap class. + * + * @since 2.0 + * + * @return @c true if the two instances match, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true if and only if the two instances contain the same number of elements and all the elements contained in each other. + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the element deleter of the collection. + * + * @since 2.0 + * + * @return An function pointer to the existing element deleter + */ + virtual DeleterFunctionType GetDeleter(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] map The instance of the %HashMap class to copy from + */ + HashMap(const HashMap& map); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] map An instance of %HashMap + */ + HashMap& operator =(const HashMap& map); + + /** + * Copies all the pairs from a specified map to this map + * + * @return An error code + * @param[in] map The map to copy + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * The @c map is modified during the operation of this method. + */ + result AddAll(const IMap& map); + + /** + * Gets the hash value for a specified object. + * + * @return The hash value for the specified object + * @param[in] obj + */ + int Hash(const Object& obj) const; + + /** + * Rehashes the content of a map to a new array with a greater capacity. + * + * @return An error code + * @param[in[ newCapacity The new capacity @n + * It must be a power of two and must be greater than the current capacity. + * @exception E_SUCCESS The method is successful. + * @remarks This method is called automatically when the number of keys in a map reaches its threshold. + */ + result Resize(int newCapacity); + + /** + * Clears all key-value pairs in a map. + */ + void Reset(void); + + /** + * Sets the element deleter of the collection. + * + * @since 2.0 + * + * @param[in] deleter An function pointer to the element deleter to set + */ + virtual void SetDeleter(DeleterFunctionType deleter); + + _HashMapEntry** __pTable; + int __count; + int __capacity; + float __loadFactor; + int __threshold; + IHashCodeProvider* __pProvider; + IComparer* __pComparer; + bool __needToRemoveProviderComparer; + int __modCount; + DeleterFunctionType __deleter; + static const int DEFAULT_CAPACITY = 16; + static const float DEFAULT_LOAD_FACTOR; + + friend class _HashMapEnumerator; + friend class _HashMapImpl; + class _HashMapImpl* __pHashMapImpl; + +}; // HashMap + +}}} // Tizen::Base::Collection + +#endif //_FBASE_COL_HASH_MAP_H_ diff --git a/inc/FBaseColHashMapT.h b/inc/FBaseColHashMapT.h new file mode 100644 index 0000000..1b609e2 --- /dev/null +++ b/inc/FBaseColHashMapT.h @@ -0,0 +1,1334 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColHashMapT.h + * @brief This is the header file for the %HashMapT class. + * + * This header file contains the declarations of the %HashMapT class. + */ +#ifndef _FBASE_COL_HASH_MAP_T_H_ +#define _FBASE_COL_HASH_MAP_T_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +template< class KeyType, class ValueType > class __HashMapEntryT; +template< class KeyType, class ValueType > class __HashMapEnumeratorT; +template< class KeyType > class __HashMapDefaultProviderT; + +/** + * @class HashMapT + * @brief This class provides a template-based collection of associated keys and values + * that are organized based on the hash code of the key. + * + * @since 2.0 + * + * The %HashMapT class provides a template-based collection of associated keys and values + * that are organized based on the hash code of the key. + * It contains unique keys and each key maps to one single value. + * The key and value cannot be a null reference. Several methods in the %HashMapT class need assignment (=) operators of KeyType and ValueType. + * @n + * For more information on the class features, see HashMap and MultiHashMap. + * + * The following example demonstrates how to use the %HashMapT class. + + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::HashMapTSample(void) + * { + * HashMapT map; + * + * // Constructs a %HashMapT instance with default capacity, load factor, hash code provider, and comparer + * map.Construct(); + * + * map.Add(1, 100); // map.GetCount() : 1 + * map.Add(2, 200); // map.GetCount() : 2 + * map.Add(3, 300); // map.GetCount() : 3 + * + * int key; + * int value; + * + * // Gets a value with the specified key + * key = 1; + * map.GetValue(key, value); // value : 100 + * + * // Removes the value with the specified key + * map.Remove(key); + * + * // Uses an enumerator to access elements in the map + * IMapEnumeratorT* pMapEnum = map.GetMapEnumeratorN(); + * while (pMapEnum->MoveNext() == E_SUCCESS) + * { + * pMapEnum->GetKey(key); + * pMapEnum->GetValue(value); + * } + * + * delete pMapEnum; + * } + * @endcode + */ +template< class KeyType, class ValueType > +class HashMapT + : public IMapT< KeyType, ValueType > + , public Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + HashMapT(void) + : __pTable(null) + , __count(0) + , __capacity(0) + , __loadFactor(0) + , __threshold(0) + , __pProvider(null) + , __pComparer(null) + , __defaultConstruct(false) + , __modCount(0) + { + } + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~HashMapT(void) + { + if (null != __pTable) + { + Reset(); + delete[] __pTable; + } + + if (__defaultConstruct) + { + delete __pProvider; + delete __pComparer; + } + + } + + /** + * Initializes this instance of %HashMapT with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity + * @param[in] loadFactor The maximum ratio of elements to buckets + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c capacity or the @c loadFactor is negative. + * @remarks To work properly, the key type must be of a primitive number type. + * @see HashMapT() + */ + result Construct(int capacity = 16, float loadFactor = 0.75) + { + TryReturn(capacity >= 0, E_INVALID_ARG, "[%s] The capacity(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), capacity); + TryReturn(loadFactor >= 0, E_INVALID_ARG, "[%s] The loadFactor(%f) MUST be greater than or equal to 0.0.", GetErrorMessage(E_INVALID_ARG), loadFactor); + + result r = E_SUCCESS; + + if (capacity == 0) + { + __capacity = DEFAULT_CAPACITY; + } + else + { + __capacity = 1; + while (__capacity < capacity) + { + __capacity <<= 1; + } + } + + if (Float::Compare(loadFactor, 0) == 0) + { + __loadFactor = DEFAULT_LOAD_FACTOR; + } + else + { + __loadFactor = loadFactor; + } + + __threshold = static_cast< int >(__capacity * __loadFactor); + + __pProvider = new __HashMapDefaultProviderT< KeyType >(); + TryCatch(__pProvider != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + __pComparer = new Tizen::Base::ComparerT< KeyType >(); + TryCatch(__pComparer != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + __defaultConstruct = true; + + __pTable = new __HashMapEntryT< KeyType, ValueType >*[__capacity]; + TryCatch(__pTable != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(__pTable, null, sizeof(__HashMapEntryT< KeyType, ValueType >*) * __capacity); + + return r; + +CATCH: + __capacity = 0; + delete __pProvider; + delete __pComparer; + + return r; + } + + /** + * Initializes this instance of %HashMapT by copying the elements of a specified map. + * + * @since 2.0 + * + * @return An error code + * @param[in] map The map to copy + * @param[in] loadFactor The maximum ratio of elements to buckets + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c loadFactor is negative. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c map is modified during the operation of this method. + * @see HashMapT() + */ + result Construct(const IMapT< KeyType, ValueType >& map, float loadFactor = 0.75) + { + TryReturn(loadFactor >= 0, E_INVALID_ARG, "[%s] The loadFactor(%f) MUST be greater than or equal to 0.0.", GetErrorMessage(E_INVALID_ARG), loadFactor); + + result r = E_SUCCESS; + + if (Float::Compare(loadFactor, 0) == 0) + { + loadFactor = DEFAULT_LOAD_FACTOR; + } + + int capacity = static_cast< int >(map.GetCount() / loadFactor) + 1; + + r = Construct(capacity, loadFactor); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = AddAll(map); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + return r; + +CATCH: + Reset(); + delete[] __pTable; + __pTable = null; + + __capacity = 0; + + delete __pProvider; + __pProvider = null; + + delete __pComparer; + __pComparer = null; + + return r; + } + + /** + * Initializes this instance of an empty %HashMapT class, with the specified initial capacity, load factor, hash code provider, and comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity @n + * If it is @c 0, the default capacity (16) is used. + * @param[in] loadFactor The maximum ratio of the elements to buckets @n + * If it is @c 0, the default load factor (0.75) is used. + * @param[in] provider An instance of the IHashCodeProviderT-derived class that supplies the hash codes + * for all keys in this map + * @param[in] comparer An instance of the IComparerT-derived class to use when comparing keys + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The specified @c capacity is negative. @n + * - The @c loadFactor is negative. + * @remarks The instances of hash code provider and comparer will not be deallocated later from this map. + * @see HashMapT() + */ + result Construct(int capacity, float loadFactor, const IHashCodeProviderT< KeyType >& provider, + const IComparerT< KeyType >& comparer) + { + TryReturn(capacity >= 0, E_INVALID_ARG, "[%s] The capacity(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), capacity); + TryReturn(loadFactor >= 0, E_INVALID_ARG, "[%s] The loadFactor(%f) MUST be greater than or equal to 0.0.", GetErrorMessage(E_INVALID_ARG), loadFactor); + + result r = E_SUCCESS; + + if (capacity == 0) + { + __capacity = DEFAULT_CAPACITY; + } + else + { + __capacity = 1; + while (__capacity < capacity) + { + __capacity <<= 1; + } + } + + if (Float::Compare(loadFactor, 0) == 0) + { + __loadFactor = DEFAULT_LOAD_FACTOR; + } + else + { + __loadFactor = loadFactor; + } + + __threshold = static_cast< int >(__capacity * __loadFactor); + + __pProvider = const_cast< IHashCodeProviderT< KeyType >* >(&provider); + + __pComparer = const_cast< IComparerT< KeyType >* >(&comparer); + + __pTable = new __HashMapEntryT< KeyType, ValueType >*[__capacity]; + TryCatch(__pTable != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(__pTable, null, sizeof(__HashMapEntryT< KeyType, ValueType >*) * __capacity); + + return r; + +CATCH: + __capacity = 0; + __pProvider = null; + __pComparer = null; + + return r; + } + + /** + * Initializes this instance of %HashMapT by copying the elements of a specified map, + * with a specified load factor, hash code provider, and comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] map The map to copy + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor (0.75) is used. + * @param[in] provider An instance of the IHashCodeProviderT-derived class that supplies the hash codes + * for all keys in this map + * @param[in] comparer An instance of the IComparerT-derived class to use when comparing keys + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The @c loadFactor is negative. @n + * - The @c provider is a @c null or the @c comparer is a @c null. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c map is modified during the operation of this method. + * @remarks The instances of hash code provider and comparer will not be deallocated later from this map. + * @see HashMapT() + */ + result Construct(const IMapT< KeyType, ValueType >& map, float loadFactor, const IHashCodeProviderT< KeyType >& provider, + const IComparerT< KeyType >& comparer) + { + TryReturn((loadFactor >= 0), E_INVALID_ARG, "[%s] The loadFactor(%f) MUST be greater than or equal to 0.0.", GetErrorMessage(E_INVALID_ARG), loadFactor); + + result r = E_SUCCESS; + if (Float::Compare(loadFactor, 0) == 0) + { + loadFactor = DEFAULT_LOAD_FACTOR; + } + + int capacity = static_cast< int >(map.GetCount() / loadFactor) + 1; + r = Construct(capacity, loadFactor, provider, comparer); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = AddAll(map); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + return r; + +CATCH: + Reset(); + delete[] __pTable; + __pTable = null; + + __capacity = 0; + __pProvider = null; + __pComparer = null; + + return r; + } + + /** + * Adds the specified key-value pair to a map. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key of the value to add + * @param[in] value The value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_ALREADY_EXIST The specified @c key already exists. + * @see Remove() + */ + virtual result Add(const KeyType& key, const ValueType& value) + { + __HashMapEntryT< KeyType, ValueType >* pNewEntry; + + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + bool out = false; + + r = ContainsKey(key, out); + TryReturn((!out), E_OBJ_ALREADY_EXIST, "[%s] The key is already exist in this collection.", GetErrorMessage(E_OBJ_ALREADY_EXIST)); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = E_SUCCESS; + pNewEntry = new __HashMapEntryT< KeyType, ValueType >(key, value, __pTable[i], hash); + TryReturn(pNewEntry != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + __pTable[i] = pNewEntry; + __modCount++; + + if (__count++ >= __threshold) + { + r = Resize(__capacity * 2); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return E_SUCCESS; + } + + /** + * Gets the elements of a map in an instance of the IMapEnumeratorT-derived class. + * + * @since 2.0 + * + * @return An instance of the IMapEnumeratorT-derived class if successful, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * @see Tizen::Base::Collection::IMapEnumerator + */ + virtual IEnumeratorT< MapEntryT< KeyType, ValueType > >* GetEnumeratorN(void) const + { + result r = E_SUCCESS; + + __HashMapEnumeratorT< KeyType, ValueType >* pEnum = new __HashMapEnumeratorT< KeyType, ValueType >(*this, __modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Gets the elements of a map in an instance of the IMapEnumeratorT class. + * + * @since 2.0 + * + * @return An instance of the IMapEnumeratorT class if successful, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * @see Tizen::Base::Collection::IMapEnumerator + */ + virtual IMapEnumeratorT< KeyType, ValueType >* GetMapEnumeratorN(void) const + { + return dynamic_cast< IMapEnumeratorT< KeyType, ValueType >* >(GetEnumeratorN()); + } + + /** + * Gets the value associated with a specified key. + * + * @since 2.0 + * + * @return The value associated with the key, @n + * else @c null if an exception occurs + * @param[in] key The key to locate + * @param[out] value The value associated with the key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * The comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see SetValue() + */ + virtual result GetValue(const KeyType& key, ValueType& value) const + { + result r = E_OBJ_NOT_FOUND; + + int hash = Hash(key); + int i = hash & (__capacity - 1); + + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (cmpResult == 0) + { + value = pEntry->value; + return E_SUCCESS; + } + } + } + + return E_OBJ_NOT_FOUND; + } + + /** + * Gets the value associated with a specified key. + * + * @since 2.0 + * + * @return The value associated with the key, @n + * else @c null if an exception occurs + * @param[in] key The key to locate + * @param[out] value The value associated with the key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see SetValue() + */ + virtual result GetValue(const KeyType& key, ValueType& value) + { + return (static_cast< const HashMapT< KeyType, ValueType >* >(this))->GetValue(key, value); + } + + /** + * Gets a list of all the keys in a map. + * + * @since 2.0 + * + * @return A pointer to an IListT object containing all the keys in the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The order of the keys is the same as the corresponding values in the IListT interface returned by the GetValuesN() method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetValuesN() + */ + virtual IListT< KeyType >* GetKeysN(void) const + { + result r = E_SUCCESS; + + ArrayListT< KeyType >* pList = new ArrayListT< KeyType >(); + TryCatch(pList != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pList->Construct(__count); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < __capacity; i++) + { + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + r = pList->Add(pEntry->key); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + } + + SetLastResult(E_SUCCESS); + return pList; + +CATCH: + delete pList; + + SetLastResult(r); + return null; + } + + /** + * Gets all the values in a map. + * + * @since 2.0 + * + * @return A pointer to an IListT object containing all the values in the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetKeysN() + */ + virtual IListT< ValueType >* GetValuesN(void) const + { + result r = E_SUCCESS; + + ArrayListT< ValueType >* pList = new ArrayListT< ValueType >(); + TryCatch(pList != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pList->Construct(__count); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < __capacity; i++) + { + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + r = pList->Add(pEntry->value); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + } + + SetLastResult(E_SUCCESS); + return pList; + +CATCH: + delete pList; + + SetLastResult(r); + return null; + } + + /** + * Removes the value associated with a specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see Add() + */ + virtual result Remove(const KeyType& key) + { + result r = E_OBJ_NOT_FOUND; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + __HashMapEntryT< KeyType, ValueType >* pPrev = __pTable[i]; + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (cmpResult == 0) + { + __modCount++; + if (pPrev == pEntry) + { + __pTable[i] = pEntry->pNext; + } + else + { + pPrev->pNext = pEntry->pNext; + } + + delete pEntry; + __count--; + + return E_SUCCESS; + } + } + pPrev = pEntry; + } + + return E_OBJ_NOT_FOUND; + } + + /** + * Removes all key-value pairs in the map. + * + * @since 2.0 + */ + virtual void RemoveAll(void) + { + if (__count > 0) + { + __modCount++; + Reset(); + __count = 0; + } + } + + /** + * Replaces the value associated with a specified key with a new value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the value is to replace + * @param[in] value The new value to replace + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks Use the Add() method to add a new key-value pair. + * @see Add() + * @see GetValue() + */ + virtual result SetValue(const KeyType& key, const ValueType& value) + { + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + int cmpResult = -1; + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + if (cmpResult == 0) + { + pEntry->value = value; + break; + } + } + } + + if (cmpResult != 0) + { + r = E_OBJ_NOT_FOUND; + } + + __modCount++; + + return r; + } + + /** + * Gets the number of pairs currently stored in a map. + * + * @since 2.0 + * + * @return The pairs stored in the map + */ + virtual int GetCount(void) const + { + return __count; + } + + /** + * Checks whether a map contains the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[out] out Set to @c true if the map contains the specified key, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @see ContainsValue() + */ + virtual result ContainsKey(const KeyType& key, bool& out) const + { + out = false; + + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (cmpResult == 0) + { + out = true; + break; + } + } + } + + return E_SUCCESS; + } + + /** + * Checks whether a map contains the specified value. + * + * @since 2.0 + * + * @return @c true if the map contains the specified value, @n + * else @c false + * @param[in] value The value to locate + * + * @see ContainsKey() + */ + virtual bool ContainsValue(const ValueType& value) const + { + for (int i = 0; i < __capacity; i++) + { + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (value == pEntry->value) + { + return true; + } + } + } + + return false; + } + + /** + * Compares two instances of the %HashMapT class. + * + * @since 2.0 + * + * @return @c true if the two instances match, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true if and only if the two instances contain the same number of elements and all the elements of each other. + */ + virtual bool Equals(const Object& obj) const + { + const HashMapT< KeyType, ValueType >* other = dynamic_cast< const HashMapT< KeyType, ValueType >* >(&obj); + if (null == other) + { + return false; + } + else if (other == this) + { + return true; + } + else if (__count != other->__count) + { + return false; + } + else + { + for (int i = 0; i < __capacity; i++) + { + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + ValueType otherValue; + result r = other->GetValue(pEntry->key, otherValue); + if (IsFailed(r)) + { + return false; + } + if (pEntry->value != otherValue) + { + return false; + } + } + } + } + + return true; + } + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const + { + int hash = 0; + for (int i = 0; i < __capacity; i++) + { + for (__HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + hash += reinterpret_cast< int >(&pEntry->key); + hash += reinterpret_cast< int >(&pEntry->value); + } + } + return hash; + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] map The instance of the %HashMapT class to copy from + */ + HashMapT(const HashMapT< KeyType, ValueType >& map); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] map An instance of %HashMapT + */ + HashMapT< KeyType, ValueType >& operator =(const HashMapT< KeyType, ValueType >& map); + + /** + * Copies all the pairs from a specified map to this map. + * + * @return An error code + * @param[in] map The map to copy + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation.@n + * The @c map is modified during the operation of this method. + */ + result AddAll(const IMapT< KeyType, ValueType >& map) + { + result r = E_SUCCESS; + + IMapT< KeyType, ValueType >* pMap = const_cast< IMapT< KeyType, ValueType >* >(&map); + IMapEnumeratorT< KeyType, ValueType >* pMapEnum = pMap->GetMapEnumeratorN(); + + TryCatch(pMapEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pMapEnum->MoveNext()) != E_OUT_OF_RANGE) + { + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + KeyType key; + ValueType value; + + r = pMapEnum->GetKey(key); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pMapEnum->GetValue(value); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + int hash = Hash(key); + int i = hash & (__capacity - 1); + __HashMapEntryT< KeyType, ValueType >* pNewEntry = new __HashMapEntryT< KeyType, ValueType >(key, value, __pTable[i], hash); + + TryCatch(pNewEntry != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + __pTable[i] = pNewEntry; + __count++; + } + + if (null != pMapEnum) + { + delete pMapEnum; + } + + return E_SUCCESS; + +CATCH: + if (null != pMapEnum) + { + delete pMapEnum; + } + + return r; + } + + /** + * Gets the hash value for a specified object. + * + * @return The hash value for the specified object + * @param[in] obj The object to get hash value + */ + int Hash(const KeyType& obj) const + { + int h = __pProvider->GetHashCode(obj); + + h ^= (h >> 20) ^ (h >> 12); + + return h ^ (h >> 7) ^ (h >> 4); + } + + /** + * Resizes the content of a map to a new array with a greater capacity. + * + * @return An error code + * @param[in] newCapacity The new capacity @n + * It must be a power of two and greater than the current capacity. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks This method is called automatically when the number of keys in a map reaches its threshold. + */ + result Resize(int newCapacity) + { + result r = E_SUCCESS; + __HashMapEntryT< KeyType, ValueType >** pNewTable = new __HashMapEntryT< KeyType, ValueType >*[newCapacity]; + TryReturn(pNewTable != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(pNewTable, null, sizeof(__HashMapEntryT< KeyType, ValueType >*) * newCapacity); + + for (int i = 0; i < __capacity; i++) + { + __HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; + while (null != pEntry) + { + __HashMapEntryT< KeyType, ValueType >* pNext = pEntry->pNext; + int i = pEntry->hash & (newCapacity - 1); + pEntry->pNext = pNewTable[i]; + pNewTable[i] = pEntry; + pEntry = pNext; + } + } + + delete[] __pTable; + __pTable = pNewTable; + __capacity = newCapacity; + __threshold = static_cast< int >(__capacity * __loadFactor); + + return r; + } + + /** + * Clears all key-value pairs in this map. + */ + void Reset(void) + { + for (int i = 0; i < __capacity; i++) + { + __HashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; + while (null != pEntry) + { + __HashMapEntryT< KeyType, ValueType >* pNext = pEntry->pNext; + delete pEntry; + pEntry = pNext; + } + __pTable[i] = null; + } + } + + __HashMapEntryT< KeyType, ValueType >** __pTable; + int __count; + int __capacity; + float __loadFactor; + int __threshold; + IHashCodeProviderT< KeyType >* __pProvider; + IComparerT< KeyType >* __pComparer; + bool __defaultConstruct; + int __modCount; + + static const int DEFAULT_CAPACITY = 16; + static const float DEFAULT_LOAD_FACTOR; + + friend class __HashMapEnumeratorT< KeyType, ValueType >; + +}; // HashMapT + +// +// @class __HashMapEntryT +// @brief This is an entry for the %HashMapT class. +// @since 2.0 +// +template< class KeyType, class ValueType > +class __HashMapEntryT + : public Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + * + * @param[in] k The key to include in this entry + * @param[in] v The value to include in this entry + * @param[in] next A pointer to the next entry + * @param[in] h A hash value of the key + */ + __HashMapEntryT(const KeyType& k, const ValueType& v, __HashMapEntryT< KeyType, ValueType >* next, int h) + : key(k) + , value(v) + , hash(h) + , pNext(next) + { + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__HashMapEntryT(void) + { + } + + /** + * Internal variable. + * + * @since 2.0 + */ + KeyType key; + + /** + * Internal variable. + * + * @since 2.0 + */ + ValueType value; + + /** + * Internal variable. + * + * @since 2.0 + */ + int hash; + + /** + * Internal variable. + * + * @since 2.0 + */ + __HashMapEntryT< KeyType, ValueType >* pNext; + +}; // __HashMapEntryT + +// +// @class __HashMapEnumeratorT +// @brief This is an implementation of the IMapEnumeratorT interface for the %HashMapT class. +// @since 2.0 +// +template< class KeyType, class ValueType > +class __HashMapEnumeratorT + : public IMapEnumeratorT< KeyType, ValueType > + , public Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + * + * @param[in] map The map to enumerate + * @param[in] modCount The modification count to detect the change in the map + */ + __HashMapEnumeratorT(const HashMapT< KeyType, ValueType >& map, int modCount) + : __map(map) + , __modCount(modCount) + , __pEntry(null) + , __index(-1) + { + + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__HashMapEnumeratorT(void) + { + + } + + /** + * Gets the current object in the map. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The current object + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * This enumerator is currently positioned before the first element or + * past the last element or the map is modified after this enumerator is created. + */ + virtual result GetCurrent(MapEntryT< KeyType, ValueType >& obj) const + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn((__pEntry != null), E_INVALID_OPERATION, "[%s] Invalid position(pEntry is null).", GetErrorMessage(E_INVALID_OPERATION)); + + obj = MapEntryT< KeyType, ValueType >(__pEntry->key, __pEntry->value); + return E_SUCCESS; + } + + /** + * Moves this enumerator to the next elements of the map. + * When this enumerator is first created, or when the Reset() method is called, or when the MoveNext() method is first called, the enumerator positions itself to the first element in the map. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the map is modified after this enumerator is created. + * @exception E_OUT_OF_RANGE The enumerator has passed the end of the map. + * @see Reset() + */ + virtual result MoveNext(void) + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + if ((null != __pEntry) && (null != __pEntry->pNext)) + { + __pEntry = __pEntry->pNext; + return E_SUCCESS; + } + else + { + while (++__index < __map.__capacity) + { + __pEntry = __map.__pTable[__index]; + if (null != __pEntry) + { + return E_SUCCESS; + } + } + } + + return E_OUT_OF_RANGE; + } + + /** + * Positions the enumerator before the first element in a map. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the map is modified after this enumerator is created. + */ + virtual result Reset(void) + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __index = -1; + __pEntry = null; + return E_SUCCESS; + } + + /** + * Gets the current key in a map. + * + * @since 2.0 + * + * @return An error code + * @param[out] key The current key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * This enumerator is currently positioned before the first element or + * past the last element or the map is modified after this enumerator is created. + */ + virtual result GetKey(KeyType& key) const + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn((__pEntry != null), E_INVALID_OPERATION, "[%s] Invalid position(pEntry is null).", GetErrorMessage(E_INVALID_OPERATION)); + + key = __pEntry->key; + return E_SUCCESS; + } + + /** + * Gets the current value in a map. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The current value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * This enumerator is currently positioned before the first element or + * past the last element or the map is modified after the enumerator is created. + */ + virtual result GetValue(ValueType& value) const + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn((__pEntry != null), E_INVALID_OPERATION, "[%s] Invalid position(pEntry is null).", GetErrorMessage(E_INVALID_OPERATION)); + + value = __pEntry->value; + return E_SUCCESS; + } + +private: + const HashMapT< KeyType, ValueType >& __map; + int __modCount; + __HashMapEntryT< KeyType, ValueType >* __pEntry; + int __index; + +}; // __HashMapEnumeratorT + +// +// @class __HashMapDefaultProviderT +// @brief This is an implementation of the IHashCodeProviderT interface for the HashMap class. +// @since 2.0 +// +template< class KeyType > +class __HashMapDefaultProviderT + : public IHashCodeProviderT< KeyType > + , public Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + __HashMapDefaultProviderT(void) {} + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__HashMapDefaultProviderT(void) {} + + /** + * Gets the hash code of the specified object. + * + * @since 2.0 + * + * @return The hash code of the specified object + * @see Tizen::Base::Object::GetHashCode + */ + virtual int GetHashCode(const KeyType& obj) const + { + return (int) obj; + } + +}; // __HashMapDefaultProviderT + +template< class KeyType, class ValueType > +const float HashMapT< KeyType, ValueType >::DEFAULT_LOAD_FACTOR = 0.75; + +}}} // Tizen::Base::Collection + +#endif //_FBASE_COL_HASH_MAP_T_H_ diff --git a/inc/FBaseColIBidirectionalEnumerator.h b/inc/FBaseColIBidirectionalEnumerator.h new file mode 100644 index 0000000..52b7277 --- /dev/null +++ b/inc/FBaseColIBidirectionalEnumerator.h @@ -0,0 +1,115 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIBidirectionalEnumerator.h + * @brief This is the header file for the %IBidirectionalEnumerator interface. + * + * This header file contains the declarations of the %IBidirectionalEnumerator interface. + * + */ +#ifndef _FBASE_COL_IBIDIRECTIONAL_ENUMERATOR_H_ +#define _FBASE_COL_IBIDIRECTIONAL_ENUMERATOR_H_ + +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IBidirectionalEnumerator + * @brief This interface supports a bidirectional iteration over a collection. + * + * @since 2.0 + * + * @remarks + * An enumerator remains valid as long as the collection remains unchanged. + * If changes are made to the collection, such as adding, modifying, or + * deleting elements, the enumerator is irrecoverably invalidated. The next call to GetCurrent(), MoveNext(), MovePrevious(), Reset(), or ResetLast() fails (E_INVALID_OPERATION). + * + * The %IBidirectionalEnumerator interface supports a bidirectional iteration over a collection. + * One can only access the elements in a collection through %IBidirectionalEnumerator. The elements cannot be modified through this interface. + */ +class _OSP_EXPORT_ IBidirectionalEnumerator + : public virtual IEnumerator +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IBidirectionalEnumerator(void) {} + + /** + * Moves %IBidirectionalEnumerator to the previous element of the collection. @n + * A call to the MovePrevious() method after the ResetLast() method positions the enumerator to the last element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The enumerator has passed the front of the collection. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the collection is modified after the enumerator is created. + * @see Tizen::Base::Collection::IEnumerator::MoveNext() + * @see ResetLast() + */ + virtual result MovePrevious(void) = 0; + + /** + * Positions the enumerator after the last element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the collection is modified after the enumerator is created. + * @see Tizen::Base::Collection::IEnumerator::Reset() + * @see MovePrevious() + */ + virtual result ResetLast(void) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IBidirectionalEnumerator_Reserved1(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IBidirectionalEnumerator_Reserved2(void) { } + +}; // IBidirectionalEnumerator + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IBIDIRECTIONAL_ENUMERATOR_H_ diff --git a/inc/FBaseColIBidirectionalEnumeratorT.h b/inc/FBaseColIBidirectionalEnumeratorT.h new file mode 100644 index 0000000..546e136 --- /dev/null +++ b/inc/FBaseColIBidirectionalEnumeratorT.h @@ -0,0 +1,96 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIBidirectionalEnumeratorT.h + * @brief This is the header file for the %IBidirectionalEnumeratorT interface. + * + * This header file contains the declarations of the %IBidirectionalEnumeratorT interface. + * + */ +#ifndef _FBASE_COL_IBIDIRECTIONAL_ENUMERATOR_T_H_ +#define _FBASE_COL_IBIDIRECTIONAL_ENUMERATOR_T_H_ + +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IBidirectionalEnumeratorT + * @brief This interface supports a bidirectional iteration over a collection. + * + * @since 2.0 + * + * @remarks + * An enumerator remains valid as long as the collection remains unchanged. + * If changes are made to the collection, such as adding, modifying, or + * deleting elements, the enumerator is irrecoverably invalidated. The next call to GetCurrent(), MoveNext(), MovePrevious(), Reset(), or ResetLast() fails (E_INVALID_OPERATION). + * + * The %IBidirectionalEnumeratorT interface supports a bidirectional iteration over a collection. + * One can only access the elements in a collection through %IBidirectionalEnumeratorT. The elements cannot be modified through this interface. + * + */ +template< class Type > +class IBidirectionalEnumeratorT + : public virtual IEnumeratorT< Type > +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IBidirectionalEnumeratorT(void) {} + + /** + * Moves %IBidirectionalEnumeratorT to the previous element of the collection. @n + * A call to the MovePrevious() method after the ResetLast() method positions the enumerator to the last element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The enumerator has passed the front of the collection. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the collection is modified after the enumerator is created. + * @see Tizen::Base::Collection::IEnumeratorT< Type >::MoveNext() + * @see ResetLast() + */ + virtual result MovePrevious(void) = 0; + + /** + * Positions the enumerator after the last element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the collection is modified after the enumerator is created. + * @see Tizen::Base::Collection::IEnumeratorT< Type >::Reset() + * @see MovePrevious() + */ + virtual result ResetLast(void) = 0; + +}; // IBidirectionalEnumeratorT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_I_BIDIRECTIONAL_ENUMERATOR_T_H_ diff --git a/inc/FBaseColICollection.h b/inc/FBaseColICollection.h new file mode 100644 index 0000000..1570f45 --- /dev/null +++ b/inc/FBaseColICollection.h @@ -0,0 +1,115 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColICollection.h + * @brief This is the header file for the %ICollection interface. + * + * This header file contains the declarations of the %ICollection interface. + * + */ +#ifndef _FBASE_COL_ICOLLECTION_H_ +#define _FBASE_COL_ICOLLECTION_H_ + +#ifdef ICollection +#undef ICollection +#endif + +#include +#include +#include + + +#ifdef ICollection +#undef ICollection +#endif + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface ICollection + * @brief This interface represents a collection of objects. + * It defines the size, enumerators, and the synchronization mechanism of a collection. + * + * @since 2.0 + * + * The %ICollection interface represents a collection of objects. It defines the size, enumerators, and the synchronization mechanism of a collection. + * + */ +class _OSP_EXPORT_ ICollection +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ICollection(void) {} + + /** + * Gets the number of objects currently stored in the collection. + * + * @since 2.0 + * + * @return An integer value indicating the number of objects currently stored in the collection + */ + virtual int GetCount(void) const = 0; + + /** + * Gets the enumerator of the %ICollection derived class, + * or returns @c null if some exception occurs. + * + * @since 2.0 + * + * @return A pointer to an enumerator interface of the %ICollection derived class, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks Use this method to obtain an enumerator (an instance of the IEnumerator derived class) + * to iterate over a collection (an instance of the %ICollection derived class). + * @remarks The specific error code can be accessed using GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * + */ + virtual IEnumerator* GetEnumeratorN(void) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICollection_Reserved1(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICollection_Reserved2(void) { } + +}; // ICollection + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_ICOLLECTION_H_ diff --git a/inc/FBaseColICollectionT.h b/inc/FBaseColICollectionT.h new file mode 100644 index 0000000..e0a0a97 --- /dev/null +++ b/inc/FBaseColICollectionT.h @@ -0,0 +1,88 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColICollectionT.h + * @brief This is the header file for the %ICollectionT interface. + * + * This header file contains the declarations of the %ICollectionT interface. + * + */ +#ifndef _FBASE_COL_BASE_ICOLLECTION_T_H_ +#define _FBASE_COL_BASE_ICOLLECTION_T_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface ICollectionT + * @brief This interface represents a template-based collection of objects. + * It defines the size, and enumerators. + * + * @since 2.0 + * + * The %ICollectionT interface represents a template-based collection of objects. + * It defines the size, and enumerators. + */ +template< class Type > +class ICollectionT +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ICollectionT(void) {} + + /** + * Gets the number of objects currently stored in the collection. + * + * @since 2.0 + * + * @return The number of objects currently stored in the collection + */ + virtual int GetCount(void) const = 0; + + /** + * Gets the enumerator of the %ICollectionT derived class, + * or returns @c null if an exception occurs. + * + * @since 2.0 + * + * @return A pointer to an enumerator interface of the %ICollectionT derived class, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks Use this method to obtain an enumerator (an instance of the IEnumeratorT derived class) + * to iterate over a collection (an instance of the %ICollectionT derived class). + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + */ + virtual IEnumeratorT< Type >* GetEnumeratorN(void) const = 0; + +}; // ICollectionT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_ICOLLECTION_T_H_ diff --git a/inc/FBaseColIComparer.h b/inc/FBaseColIComparer.h new file mode 100644 index 0000000..a01b19e --- /dev/null +++ b/inc/FBaseColIComparer.h @@ -0,0 +1,96 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIComparer.h + * @brief This is the header file for the %IComparer interface. + * + * This header file contains the declarations of the %IComparer interface. + */ +#ifndef _FBASE_COL_ICOMPARER_H_ +#define _FBASE_COL_ICOMPARER_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ +/** + * @interface IComparer + * @brief This interface allows a derived class to compare 2 objects of the same type. + * + * @since 2.0 + * + * The %IComparer interface allows a derived class to compare 2 objects of the same type. + */ +class _OSP_EXPORT_ IComparer +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IComparer(void) { } + +public: + /** + * Compares two given instances of the same type. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 The first object to compare + * @param[in] obj2 The second object to compare + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IComparer_Reserved1(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IComparer_Reserved2(void) { } + +}; // IComparer +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_ICOMPARER_H_ diff --git a/inc/FBaseColIComparerT.h b/inc/FBaseColIComparerT.h new file mode 100644 index 0000000..34b2a88 --- /dev/null +++ b/inc/FBaseColIComparerT.h @@ -0,0 +1,78 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIComparerT.h + * @brief This is the header file for the %IComparerT interface. + * + * This header file contains the declarations of the %IComparerT interface. + */ +#ifndef _FBASE_COL_ICOMPARER_T_H_ +#define _FBASE_COL_ICOMPARER_T_H_ + +#include + + +namespace Tizen { namespace Base { namespace Collection +{ +/** + * @interface IComparerT + * @brief This interface allows derived classes to compare 2 template-based objects of the same type. + * + * @since 2.0 + * + * The %IComparerT interface allows derived classes to compare 2 template-based objects of the + * same type. + */ +template< class Type > +class IComparerT +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IComparerT(void) { } + +public: + /** + * Compares two given instances of the same type. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 The first object to compare + * @param[in] obj2 The second object to compare + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Type& obj1, const Type& obj2, int& cmp) const = 0; + +}; // IComparerT +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_ICOMPARER_T_H_ diff --git a/inc/FBaseColIEnumerator.h b/inc/FBaseColIEnumerator.h new file mode 100644 index 0000000..04d440f --- /dev/null +++ b/inc/FBaseColIEnumerator.h @@ -0,0 +1,135 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIEnumerator.h + * @brief This is the header file for the %IEnumerator interface. + * + * This header file contains the declarations of the %IEnumerator interface. + * + */ +#ifndef _FBASE_COL_IENUMERATOR_H_ +#define _FBASE_COL_IENUMERATOR_H_ + +#include + +namespace Tizen {namespace Base +{ +class Object; +}} + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IEnumerator + * @brief This interface supports simple iteration over a collection. + * + * @since 2.0 + * + * @remarks + * An enumerator remains valid as long as the collection remains unchanged. + * If changes are made to the collection, such as adding, modifying, or + * deleting elements, the enumerator is irrecoverably invalidated. The next call to GetCurrent(), MoveNext(), or Reset() fails and returns + * E_INVALID_OPERATION. + * + * The %IEnumerator interface supports simple iteration over a collection. + * One can only access the elements in a collection through %IEnumerator. The elements cannot be modified through this interface. + * + */ +class _OSP_EXPORT_ IEnumerator +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IEnumerator(void) {} + + /** + * Gets the current object in the collection. + * + * @since 2.0 + * + * @return The current object in the collection, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - The enumerator is currently positioned before the first element + * or after the last element. @n + * - The collection is modified after the enumerator is created. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetLastResult() + */ + virtual Tizen::Base::Object* GetCurrent(void) const = 0; + + /** + * Moves %IEnumerator to the next element of the collection. @n + * After the enumerator is first created or reset using the Reset() method, + * the first call to this method positions the enumerator to the first element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The enumerator has passed the end of the collection. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the collection is modified after the enumerator is created. + * @see Reset() + */ + virtual result MoveNext(void) = 0; + + /** + * Positions the enumerator before the first element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the collection is modified after the enumerator is created. + */ + virtual result Reset(void) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IEnumerator_Reserved1(void) { } + + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IEnumerator_Reserved2(void) { } + +}; // IEnumerator + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IENUMERATOR_H_ diff --git a/inc/FBaseColIEnumeratorT.h b/inc/FBaseColIEnumeratorT.h new file mode 100644 index 0000000..ad6c2f2 --- /dev/null +++ b/inc/FBaseColIEnumeratorT.h @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIEnumeratorT.h + * @brief This is the header file for the %IEnumeratorT interface. + * + * This header file contains the declarations of the %IEnumeratorT interface. + * + */ +#ifndef _FBASE_COL_IENUMERATOR_T_H_ +#define _FBASE_COL_IENUMERATOR_T_H_ + +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IEnumeratorT + * @brief This interface supports simple iteration over a template-based collection. + * + * @since 2.0 + * + * @remarks + * An enumerator remains valid as long as the collection remains unchanged. + * If changes are made to the collection, such as adding, modifying, or + * deleting elements, the enumerator is irrecoverably invalidated. The next call to GetCurrent(), MoveNext(), or Reset() fails and returns + * E_INVALID_OPERATION. + * + * The %IEnumeratorT interface supports simple iteration over a template-based collection. + * One can only access the elements in a collection through %IEnumeratorT. The elements cannot be modified through this interface. + * + */ +template< class Type > +class IEnumeratorT +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IEnumeratorT(void) {} + + /** + * Gets the current object in the collection. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj A pointer to the current object + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * The enumerator is currently positioned before the first element or + * after the last element or the collection is modified after the enumerator is created. + */ + virtual result GetCurrent(Type& obj) const = 0; + + /** + * Moves %IEnumeratorT to the next element of the collection. @n + * After the enumerator is first created or reset using the Reset() method, + * the first call to this method positions the enumerator to the first element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The enumerator has passed the end of the collection. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the collection is modified after the enumerator is created. + * @see Reset() + */ + virtual result MoveNext(void) = 0; + + /** + * Positions the enumerator before the first element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the collection is modified after the enumerator is created. + */ + virtual result Reset(void) = 0; + +}; // IEnumeratorT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IENUMERATOR_T_H_ diff --git a/inc/FBaseColIHashCodeProvider.h b/inc/FBaseColIHashCodeProvider.h new file mode 100644 index 0000000..ee9c7f3 --- /dev/null +++ b/inc/FBaseColIHashCodeProvider.h @@ -0,0 +1,91 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIHashCodeProvider.h + * @brief This is the header file for the %IHashCodeProvider interface. + * + * This header file contains the declarations of the %IHashCodeProvider interface. + */ +#ifndef _FBASE_COL_IHASH_CODE_PROVIDER_H_ +#define _FBASE_COL_IHASH_CODE_PROVIDER_H_ + +namespace Tizen {namespace Base +{ +class Object; +}} + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IHashCodeProvider + * @brief This interface represents classes that can provide the hash code of a specific type of object. + * + * @since 2.0 + * + * The %IHashCodeProvider interface represents classes that can provide the hash code of a specific type of object. + */ +class _OSP_EXPORT_ IHashCodeProvider +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IHashCodeProvider(void) {} + + /** + * Gets the hash code of the specified object. + * + * @since 2.0 + * + * @return The hash code of the specified object + * @param[in] obj A pointer to the object whose hash code is required + * @remarks The hash algorithm is usually specific to a type. + * Two equal instances must return the same hash value. + * For better performance, the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(const Tizen::Base::Object& obj) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IHashCodeProvider_Reserved1(void) { } + + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IHashCodeProvider_Reserved2(void) { } + +}; // IHashCodeProvider + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IHASH_CODE_PROVIDER_H_ diff --git a/inc/FBaseColIHashCodeProviderT.h b/inc/FBaseColIHashCodeProviderT.h new file mode 100644 index 0000000..3408536 --- /dev/null +++ b/inc/FBaseColIHashCodeProviderT.h @@ -0,0 +1,68 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIHashCodeProviderT.h + * @brief This is the header file for the %IHashCodeProviderT interface. + * + * This header file contains the declarations of the %IHashCodeProviderT interface. + */ +#ifndef _FBASE_COL_IHASH_CODE_PROVIDER_T_H_ +#define _FBASE_COL_IHASH_CODE_PROVIDER_T_H_ + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IHashCodeProviderT + * @brief This interface represents classes that can provide the hash code of a specific type of template-based object. + * + * @since 2.0 + * + * The %IHashCodeProviderT interface represents classes that can provide the hash code of a specific type of template-based object. + * + */ +template< class Type > +class IHashCodeProviderT +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IHashCodeProviderT(void) {} + + /** + * Gets the hash code of the specified object. + * + * @since 2.0 + * + * @return The hash code of the specified object + * @param[in] obj A pointer to the object for which the hash code is required + * @remarks The hash algorithm is usually specific to a type. @n + * Two equal instances must return the same hash value. + * For better performance, the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(const Type& obj) const = 0; + +}; // IHashCodeProviderT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IHASH_CODE_PROVIDER_T_H_ diff --git a/inc/FBaseColIList.h b/inc/FBaseColIList.h new file mode 100644 index 0000000..c6e3a0f --- /dev/null +++ b/inc/FBaseColIList.h @@ -0,0 +1,824 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIList.h + * @brief This is the header file for the %IList interface. + * + * This header file contains the declarations of the %IList interface. + */ +#ifndef _FBASE_COL_ILIST_H_ +#define _FBASE_COL_ILIST_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IList + * @brief This interface represents a collection of objects that can be individually accessed by an index. + * + * @since 2.0 + * + * The %IList interface represents a collection of objects that can be individually accessed by an index. + * + */ +class _OSP_EXPORT_ IList + : public virtual ICollection +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IList(void) {} + + /** + * @if OSPDEPREC + * Adds the specified object to the list. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it has a problem of const reference argument. + * Instead of using this method, use Add(Object* pObj). + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks In a collection of contiguous elements, such as a list, the elements + * that follow the insertion point move down to accommodate the new element. + * If the collection is indexed, the indexes of the elements that are moved + * are also updated. This behavior does not apply to collections where + * elements are conceptually grouped into buckets, such as a hashtable. + * This method performs a shallow copy. It adds the pointer only; not the element itself. + * @see Remove() + * @endif + */ + result Add(const Object& obj) + { + return Add(const_cast< Object* >(&obj)); + } + + /** + * Adds the specified object to the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj The pointer to object to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @remarks In a collection of contiguous elements, such as a list, the elements + * that follow the insertion point move down to accommodate the new element. + * If the collection is indexed, the indexes of the elements that are moved + * are also updated. This behavior does not apply to collections where + * elements are conceptually grouped into buckets, such as a hashtable. + * This method performs a shallow copy. It adds the pointer only; not the element itself. + * @see Remove() + */ + virtual result Add(Object* pObj) = 0; + + /** + * Adds the elements of the specified collection to the end of the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to add to the list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks This method performs a shallow copy. It adds the pointer only; not the element itself. + * @see RemoveItems() + */ + virtual result AddItems(const ICollection& collection) = 0; + + /** + * Searches for an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + */ + virtual result IndexOf(const Object& obj, int& index) const = 0; + + /** + * @if OSPDEPREC + * Inserts an object at the specified location in the list. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it has a problem of const reference argument. + * Instead of using this method, use InsertAt(const Object* pObj, int index). + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to insert + * @param[in] index The index at which the object must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is greater than the number of elements in the list or less than @c 0. + * @remarks If the @c index equals the number of elements in the list, the new element + * is added at the end of the list. + * This method performs a shallow copy. It inserts the pointer only; not the element itself. + * @see Add() + * @see RemoveAt() + * @endif + */ + result InsertAt(const Object& obj, int index) + { + return InsertAt(const_cast< Object* >(&obj), index); + } + + /** + * Inserts an object at the specified location in the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj The pointer to object to insert + * @param[in] index The index at which the object must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is greater than the number of elements in the list or less than @c 0. + * @remarks If the @c index equals the number of elements in the list, the new element + * is added at the end of the list. + * This method performs a shallow copy. It inserts the pointer only; not the element itself. + * @see Add() + * @see RemoveAt() + */ + virtual result InsertAt(Object* pObj, int index) = 0; + + /** + * Searches for an object starting from the specified index. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index for the search @n + * It must be less than the number of elements. + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Object& obj, int startIndex, int& index) const = 0; + + /** + * Searches for an object within the specified range. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The @c count is greater than the number of elements starting from @c startIndex + * or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Object& obj, int startIndex, int count, int& index) const = 0; + + /** + * Searches for the last occurrence of an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the last occurrence of the specified object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see IndexOf() + */ + virtual result LastIndexOf(const Object& obj, int& index) const = 0; + + /** + * Inserts the elements of a collection in the list at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to insert + * @param[in] startIndex The starting index at which the collection must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c startIndex is greater than the number of elements in the list or less than @c 0. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks If the @c startIndex equals the number of elements in the list, the new elements + * are added at the end of the list. + * This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see RemoveItems() + * @see AddItems() + */ + virtual result InsertItemsFrom(const ICollection& collection, int startIndex) = 0; + + /** + * Gets the object at the specified location. + * + * @since 2.0 + * + * @return The object at the specified location, @n + * else @c null if the @c index is not valid + * @param[in] index The index of the object to get + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetAt() + */ + virtual const Object* GetAt(int index) const = 0; + + /** + * Gets the object at the specified location. + * + * @since 2.0 + * + * @return The object at the specified location, @n + * else @c null if the @c index is not valid + * @param[in] index The index of the object to get + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetAt() + */ + virtual Object* GetAt(int index) = 0; + + /** + * Gets all the elements of the list within the specified range. + * + * @since 2.0 + * + * @return A pointer to an %IList with elements lying within the specified range, @n + * else @c null if an exception occurs + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The @c count is greater than the number of elements in the list starting from @c startIndex + * or less than @c 0. + * @remarks The %IList stores just the pointers to the elements in the list, not the elements themselves. + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual IList* GetItemsN(int startIndex, int count) const = 0; + + /** + * Removes the first occurrence of the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to remove + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks Remove(obj, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * Remove(obj); + * SetDeleter(deleter); + * @endcode + * @remarks Remove(obj, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * Remove(obj); + * SetDeleter(deleter); + * @endcode + * @see Add() + * @see RemoveAt() + */ + result Remove(const Object& obj, bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = Remove(obj); + SetDeleter(deleter); + return r; + } + + /** + * Removes the first occurrence of the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see Add() + * @see RemoveAt() + */ + virtual result Remove(const Object& obj) = 0; + + /** + * Removes the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the object must be removed + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks RemoveAt(index, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * RemoveAt(index); + * SetDeleter(deleter); + * @endcode + * @remarks RemoveAt(index, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * RemoveAt(index); + * SetDeleter(deleter); + * @endcode + */ + result RemoveAt(int index, bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = RemoveAt(index); + SetDeleter(deleter); + return r; + } + + /** + * Removes the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the object must be removed + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + */ + virtual result RemoveAt(int index) = 0; + + /** + * Removes all the elements within the specified range. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements in the range + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The @c count is greater than the number of elements starting from @c startIndex + * or less than @c 0. + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks RemoveItems(startIndex, count, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * RemoveItems(startIndex, count); + * SetDeleter(deleter); + * @endcode + * @remarks RemoveItems(startIndex, count, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * RemoveItems(startIndex, count); + * SetDeleter(deleter); + * @endcode + * @see AddItems() + */ + result RemoveItems(int startIndex, int count, bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = RemoveItems(startIndex, count); + SetDeleter(deleter); + return r; + } + + /** + * Removes all the elements within the specified range. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements in the range + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The @c count is greater than the number of elements starting from @c startIndex + * or less than @c 0. + * @see AddItems() + */ + virtual result RemoveItems(int startIndex, int count) = 0; + + /** + * Removes all the elements from the list that are common to the specified collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to be removed from this list + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks RemoveItems(collection, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * RemoveItems(collection); + * SetDeleter(deleter); + * @endcode + * @remarks RemoveItems(collection, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * RemoveItems(collection); + * SetDeleter(deleter); + * @endcode + * @see Remove() + * @see RemoveAt() + */ + result RemoveItems(const ICollection& collection, bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = RemoveItems(collection); + SetDeleter(deleter); + return r; + } + + /** + * Removes all the elements from the list that are common to the specified collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to remove from this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @see Remove() + * @see RemoveAt() + */ + virtual result RemoveItems(const ICollection& collection) = 0; + + /** + * Removes all the object pointers in the collection. @n + * If the deallocate param is set to @c true, it removes all the objects in the collection. @n + * This method can be called just before deleting the collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] forceDeletion Set to @c true to deallocate all the objects, @n + * else @c false + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks RemoveAll(@b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * RemoveAll(); + * SetDeleter(deleter); + * @endcode + * @remarks RemoveAll(@b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * RemoveAll(); + * SetDeleter(deleter); + * @endcode + */ + void RemoveAll(bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + RemoveAll(); + SetDeleter(deleter); + } + + /** + * Removes all the object pointers in the collection. @n + * This method can be called just before deleting the collection. + * + * @since 2.0 + */ + virtual void RemoveAll(void) = 0; + + /** + * Replaces the object at the specified index with the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The new object + * @param[in] index The index at which the new object must be set + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + * @remarks Based on the specified element deleter, the set operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the set method.@n + * If both an element deleter and forceDeleteion are set, the set operation follows @c forceDeletion setting. + * @remarks SetAt(obj, index, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * SetAt(const_cast< Object* >(&obj), index); + * SetDeleter(deleter); + * @endcode + * @remarks SetAt(obj, index, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * SetAt(const_cast< Object* >(&obj), index); + * SetDeleter(deleter); + * @endcode + * @see GetAt() + */ + result SetAt(const Object& obj, int index, bool forceDeletion = false) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = SetAt(const_cast< Object* >(&obj), index); + SetDeleter(deleter); + return r; + } + + /** + * Replaces the object at the specified index with the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj The pointer to new object + * @param[in] index The index at which the new object must be set + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + * @see GetAt() + */ + virtual result SetAt(Object* pObj, int index) = 0; + + /** + * Sorts the elements of this list using the comparer provided. + * + * @since 2.0 + * + * @return An error code + * @param[in] comparer The IComparer implementation to use when comparing elements + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + virtual result Sort(const IComparer& comparer) = 0; + + /** + * Checks whether the list contains the specified object. + * + * @since 2.0 + * + * @return @c true if the list contains the specified object, @n + * else @c false + * @param[in] obj The object to locate + */ + virtual bool Contains(const Object& obj) const = 0; + + /** + * @if OSPDEPREC + * Checks whether the list contains all the elements of the specified collection. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it transfers a result of comparison in out-parameter form. + * The return type will be changed into boolean type and this method will return the result. + * Instead of using this method, use bool ContainsAll(const ICollection& collection). + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to check for containment in this list + * @param[out] out Set to @c true if the list contains all the elements of the specified collection, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks If the given @c collection is empty, the @c out parameter is set to @c true. + * @see Contains() + * @endif + */ + result ContainsAll(const ICollection& collection, bool& out) const + { + out = ContainsAll(collection); + result r = GetLastResult(); + return r; + } + + /** + * Checks whether the list contains all the elements of the specified collection. + * + * @since 2.0 + * + * @return @c true if the list contains all the elements of the specified collection, @n + * else @c false + * @param[in] collection The collection to check for containment in this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the given @c collection is empty, this method will return @c true. + * @see Contains() + */ + virtual bool ContainsAll(const ICollection& collection) const = 0; + + /** + * Gets a bidirectional enumerator (an instance of the IBidirectionalEnumerator derived class) of this list. + * + * @since 2.0 + * + * @return A pointer to a bidirectional enumerator interface of the %IList derived class, @n + * else @c null if an exception occurs + * @remarks Use this method to obtain a bidirectional enumerator (an instance of the IBidirectionalEnumerator derived class) + * to iterate over a collection (an instance of the %IList derived class). + * The specific error code can be accessed using GetLastResult() method. + * @see Tizen::Base::Collection::IBidirectionalEnumerator + */ + virtual IBidirectionalEnumerator* GetBidirectionalEnumeratorN(void) const = 0; + + /** + * This method is for distinguishing between ArrayList and LinkedList. + * + * @since 2.0 + * + * @return @c true if it is an ArrayList, @n + * else @c false if it is a LinkedList. + */ + virtual bool IsRandomAccessible(void) const + { + return false; + } + + /** + * Gets the element deleter of the collection. + * + * @since 2.0 + * + * @return An function pointer to the existing element deleter + */ + virtual DeleterFunctionType GetDeleter(void) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IList_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IList_Reserved2(void) {} + +private: + /** + * Sets the element deleter of the collection. + * + * @since 2.0 + * + * @param[in] deleter A function pointer to the element deleter to set + */ + virtual void SetDeleter(DeleterFunctionType deleter) = 0; + +}; // IList + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_ILIST_H_ diff --git a/inc/FBaseColIListT.h b/inc/FBaseColIListT.h new file mode 100644 index 0000000..6c857ea --- /dev/null +++ b/inc/FBaseColIListT.h @@ -0,0 +1,387 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIListT.h + * @brief This is the header file for the %IListT interface. + * + * This header file contains the declarations of the %IListT interface. + */ +#ifndef _FBASE_COL_ILIST_T_H_ +#define _FBASE_COL_ILIST_T_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IListT + * @brief This interface represents a template-based collection of objects that can be individually accessed by an index. + * + * @since 2.0 + * + * The %IListT interface represents a template-based collection of objects that can be individually accessed by an index. + * + */ +template< class Type > +class IListT + : public virtual ICollectionT< Type > +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IListT(void) {} + + /** + * Adds the specified object to the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks In a collection of contiguous elements, such as a list, the elements + * that follow the insertion point move down to accommodate the new element. + * If the collection is indexed, the indexes of the elements that are moved + * are also updated. This behavior does not apply to collections where + * elements are conceptually grouped into buckets, such as a hashtable. + * @see Remove() + */ + virtual result Add(const Type& obj) = 0; + + /** + * Adds the elements of the specified collection to the end of the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @see RemoveItems() + */ + virtual result AddItems(const ICollectionT< Type >& collection) = 0; + + /** + * Searches for an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + */ + virtual result IndexOf(const Type& obj, int& index) const = 0; + + /** + * Searches for an object starting from the specified index. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index for the search @n + * It must be less than the number of elements. + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Type& obj, int startIndex, int& index) const = 0; + + /** + * Searches for an object within the specified range. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The @c count is greater than the number of elements starting from @c startIndex + * or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Type& obj, int startIndex, int count, int& index) const = 0; + + /** + * Searches for the last occurrence of an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the last occurrence of the specified object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see IndexOf() + */ + virtual result LastIndexOf(const Type& obj, int& index) const = 0; + + /** + * Inserts an object at the specified location in the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to insert + * @param[in] index The index at which the object must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c index is greater than the number of elements in the list or less than @c 0. + * @remarks If the @c index equals the number of elements in the list, the new element + * is added at the end of the list. + * @see Add() + * @see RemoveAt() + */ + virtual result InsertAt(const Type& obj, int index) = 0; + + /** + * Inserts the elements of a collection in the list at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to insert + * @param[in] startIndex The starting index at which the collection must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the @c startIndex is greater than the number of elements in the list or less than @c 0. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks If the @c startIndex equals the number of elements in the list, the new elements + * are added at the end of the list. + * @see RemoveItems() + * @see AddItems() + */ + virtual result InsertItemsFrom(const ICollectionT< Type >& collection, int startIndex) = 0; + + /** + * Gets the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the object to get + * @param[out] obj The object obtained from the list + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + * @see SetAt() + */ + virtual result GetAt(int index, Type& obj) const = 0; + + /** + * Gets the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the object to get + * @param[out] obj The object obtained from the list + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + * @see SetAt() + */ + virtual result GetAt(int index, Type& obj) = 0; + + /** + * Gets all the elements of the list within the specified range. + * + * @since 2.0 + * + * @return A pointer to %IListT with elements lying within the specified range, @n + * else @c null if an exception occurs + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The @c count is greater than the number of elements in the list starting from @c startIndex + * or less than @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual IListT< Type >* GetItemsN(int startIndex, int count) const = 0; + + /** + * Removes the first occurrence of the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The object is not found. + */ + virtual result Remove(const Type& obj) = 0; + + /** + * Removes the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the object must be removed + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + */ + virtual result RemoveAt(int index) = 0; + + /** + * Removes all the elements from the list that are common to the specified collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to remove from this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @see Remove() + * @see RemoveAt() + */ + virtual result RemoveItems(const ICollectionT< Type >& collection) = 0; + + /** + * Removes all the elements within the specified range. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements in the range + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The @c count is greater than the number of elements starting from @c startIndex + * or less than @c 0. + * @see AddItems() + * @see InsertItemsFrom() + */ + virtual result RemoveItems(int startIndex, int count) = 0; + + /** + * Removes all the elements in the list. + * + * @since 2.0 + */ + virtual void RemoveAll(void) = 0; + + /** + * Sets the object at the specified index with the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The new object + * @param[in] index The index at which the new object must be set + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is either equal to or greater than the number of elements in the list or less than @c 0. + * @see GetAt() + */ + virtual result SetAt(const Type& obj, int index) = 0; + + /** + * Sorts the elements of this list using the comparer provided. + * + * @since 2.0 + * + * @return An error code + * @param[in] comparer The IComparerT implementation to use when comparing elements + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + virtual result Sort(const IComparerT< Type >& comparer) = 0; + + /** + * Checks whether the list contains the specified object. + * + * @since 2.0 + * + * @return @c true if the list contains the specified object, @n + * else @c false + * @param[in] obj The object to locate + */ + virtual bool Contains(const Type& obj) const = 0; + + /** + * Checks whether the list contains all the elements of the specified collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to check for containment in this list + * @param[out] out Set to @c true if the list contains all the elements of the specified collection, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks If the given @c collection is empty, the @c out parameter is set to @c true. + * @see Contains() + */ + virtual result ContainsAll(const ICollectionT< Type >& collection, bool& out) const = 0; + + /** + * Gets a bidirectional enumerator (an instance of the IBidirectionalEnumeratorT derived class) of this list. + * + * @since 2.0 + * + * @return A pointer to a bidirectional enumerator interface of the %IListT derived class, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks Use this method to obtain a bidirectional enumerator (an instance of the IBidirectionalEnumeratorT derived class) + * to iterate over a collection (an instance of the %IListT derived class). + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IBidirectionalEnumeratorT + */ + virtual IBidirectionalEnumeratorT< Type >* GetBidirectionalEnumeratorN(void) const = 0; + +}; // IListT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_ILIST_T_H_ diff --git a/inc/FBaseColIMap.h b/inc/FBaseColIMap.h new file mode 100644 index 0000000..5500393 --- /dev/null +++ b/inc/FBaseColIMap.h @@ -0,0 +1,492 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIMap.h + * @brief This is the header file for the %IMap interface. + * + * This header file contains the declarations of the %IMap interface. + */ +#ifndef _FBASE_COL_IMAP_H_ +#define _FBASE_COL_IMAP_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +class IList; +class MapEntry; + +/** + * @interface IMap + * @brief This interface represents a collection of key-value pairs. + * + * @since 2.0 + * + * The %IMap interface abstracts a collection of key-value pairs. An %IMap instance + * contains unique keys and each key maps to a single value. + * The key and value cannot be a @c null reference. + * + * For more information on the class features, see HashMap and MultiHashMap. + */ +class _OSP_EXPORT_ IMap + : public virtual ICollection +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMap(void) {} + + /** + * @if OSPDEPREC + * Adds the specified key-value pair to the map. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it has a problem of const reference argument. + * Instead of using this method, use Add(Object* pKey, Object* pValue). + * @since 2.0 + * + * @return An error code + * @param[in] key The key to add + * @param[in] value The corresponding value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_ALREADY_EXIST The specified @c key already exists. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see Remove() + * @endif + */ + result Add(const Object& key, const Object& value) + { + return Add(const_cast< Object* >(&key), const_cast< Object* >(&value)); + } + + /** + * Adds the specified key-value pair to the map. + * + * @since 2.0 + * + * @return An error code + * @param[in] pKey The pointer to key to add + * @param[in] pValue The pointer to corresponding value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_ALREADY_EXIST The specified @c pKey already exists. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see Remove() + */ + virtual result Add(Object* pKey, Object* pValue) = 0; + + /** + * Checks if the key exists. If the key doesn't exist, Add() is called. Unless, SetValue() is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] pKey The pointer to key to add + * @param[in] pValue The pointer to corresponding value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see Add() + * @see SetValue() + */ + result AddIfNotExistOrSet(Object* pKey, Object* pValue) + { + if (!ContainsKey(*pKey)) + { + return Add(pKey, pValue); + } + else + { + return SetValue(*pKey, pValue); + } + } + + /** + * Gets the value associated with the specified key. + * + * @since 2.0 + * + * @return The value associated with the specified key, @n + * else @c null if an exception occurs + * @param[in] key The key to find the associated value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetValue() + */ + virtual const Object* GetValue(const Object& key) const = 0; + + /** + * Gets the value associated with the specified key. + * + * @since 2.0 + * + * @return The value associated with the specified key, @n + * else @c null if an exception occurs + * @param[in] key The key to find the associated value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetValue() + */ + virtual Object* GetValue(const Object& key) = 0; + + /** + * Gets a list of all the keys in the map. + * + * @since 2.0 + * + * @return A pointer to a list of all the keys in the map, @n + * else @c null if an exception occurs + * @remarks The order of the keys is the same as the corresponding values in the IList interface returned by the GetValuesN() method. + * @remarks The %IList interface stores just the pointers to the elements in the map, not the elements themselves. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetValuesN() + */ + virtual IList* GetKeysN(void) const = 0; + + /** + * Gets a list of all the values in the map. + * + * @since 2.0 + * + * @return A pointer to a list of all the values in the map, @n + * else @c null if an exception occurs + * @remarks The IList stores just the pointers to the elements in the map, not the elements themselves. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetKeysN() + */ + virtual IList* GetValuesN(void) const = 0; + + /** + * Removes the value associated with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to remove + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks Remove(key, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * Remove(key); + * SetDeleter(deleter); + * @endcode + * @remarks Remove(key, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * Remove(key); + * SetDeleter(deleter); + * @endcode + * @see Add() + */ + result Remove(const Object& key, bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = Remove(key); + SetDeleter(deleter); + return r; + } + + /** + * Removes the value associated with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the value is to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see Add() + */ + virtual result Remove(const Object& key) = 0; + + /** + * Removes all the object pointers in the collection. @n + * If the @c forceDeletion parameter is set to @c true, the method also removes all the objects. This method can be called before deleting the collection. + * + * @since 2.0 + * + * @param[in] forceDeletion Set to @c true to deallocate all the objects, @n + * else @c false + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks RemoveAll(@b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * RemoveAll(); + * SetDeleter(deleter); + * @endcode + * @remarks RemoveAll(@b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * RemoveAll(); + * SetDeleter(deleter); + * @endcode + */ + void RemoveAll(bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + RemoveAll(); + SetDeleter(deleter); + } + + /** + * Removes all the object pointers in the collection. @n + * + * @since 2.0 + */ + virtual void RemoveAll(void) = 0; + + /** + * Replaces the value associated with the specified key with the specified value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the value is to replace + * @param[in] value The new value + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks Use the Add() method to add a new key-value pair. + * @remarks Based on the specified element deleter, the set operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the set method.@n + * If both an element deleter and forceDeleteion are set, the set operation follows @c forceDeletion setting. + * @remarks SetValue(key, value, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * SetValue(key, const_cast< Object* >(&value)); + * SetDeleter(deleter); + * @endcode + * @remarks SetValue(key, value, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * SetValue(key, const_cast< Object* >(&value)); + * SetDeleter(deleter); + * @endcode + * @see Add() + * @see GetValue() + */ + result SetValue(const Object& key, const Object& value, bool forceDeletion = false) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = SetValue(key, const_cast< Object* >(&value)); + SetDeleter(deleter); + return r; + } + + /** + * Replaces the value associated with the specified key with the specified value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the value is to replace + * @param[in] pValue The pointer to new value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks Use the Add() method to add a new key-value pair. + * @see Add() + * @see GetValue() + */ + virtual result SetValue(const Object& key, Object* pValue) = 0; + + /** + * @if OSPDEPREC + * Checks whether the map contains the specified key. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it transfers a result of comparison in out-parameter form. + * The return type will be changed into boolean type and this method will return the result. + * Instead of using this method, use bool ContainsKey(const Object& key). + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[out] out Set to @c true if the map contains the specified key, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @see ContainsValue() + * @endif + */ + result ContainsKey(const Object& key, bool& out) const + { + out = ContainsKey(key); + result r = GetLastResult(); + return r; + } + + /** + * Checks whether the map contains the specified key. + * + * @since 2.0 + * + * @return @c true if the map contains the specified key, @n + * else @c false + * @param[in] key The key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see ContainsValue() + */ + virtual bool ContainsKey(const Object& key) const = 0; + + /** + * Checks whether the map contains the specified value. + * + * @since 2.0 + * + * @return @c true if the map contains the specified value, @n + * else @c false + * @param[in] value The value to locate + * + * @see ContainsKey() + */ + virtual bool ContainsValue(const Object& value) const = 0; + + /** + * Gets an instance of the IMapEnumerator for the map. + * + * @since 2.0 + * + * @return IMapEnumerator object of this map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see IEnumerator + * @see IMapEnumerator + */ + virtual IMapEnumerator* GetMapEnumeratorN(void) const = 0; + + /** + * Gets the element deleter of the collection. + * + * @since 2.0 + * + * @return An function pointer to the existing element deleter + */ + virtual DeleterFunctionType GetDeleter(void) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMap_Reserved1(void) { } + + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMap_Reserved2(void) { } + +private: + /** + * Sets the element deleter of the collection. + * + * @since 2.0 + * + * @param[in] deleter A function pointer to the element deleter to set + */ + virtual void SetDeleter(DeleterFunctionType deleter) = 0; + +}; // IMap + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IMAP_H_ diff --git a/inc/FBaseColIMapEnumerator.h b/inc/FBaseColIMapEnumerator.h new file mode 100644 index 0000000..29c90ee --- /dev/null +++ b/inc/FBaseColIMapEnumerator.h @@ -0,0 +1,120 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIMapEnumerator.h + * @brief This is the header file for the %IMapEnumerator interface. + * + * This header file contains the declarations of the %IMapEnumerator interface. + */ +#ifndef _FBASE_COL_IMAP_ENUMERATOR_H_ +#define _FBASE_COL_IMAP_ENUMERATOR_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +class MapEntry; + +/** + * @interface IMapEnumerator + * @brief This interface supports simple iteration over a map. + * + * @since 2.0 + * + * @remarks + * An enumerator remains valid as long as the map remains unchanged. + * If changes are made to the map, such as adding, modifying, or + * deleting elements, the enumerator is irrecoverably invalidated. The next call to any method returns an E_INVALID_OPERATION message. + * + * The %IMapEnumerator interface supports simple iteration over a map. + * One can only access the elements in a collection through %IMapEnumerator. The elements cannot be modified through this interface. + * + * For more information on the class features, see HashMap and MultiHashMap. + * + */ +class _OSP_EXPORT_ IMapEnumerator + : public virtual IEnumerator +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMapEnumerator(void) {} + + /** + * Gets the current object from the collection. + * + * @since 2.0 + * + * @return A pointer to the current object in the collection, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - The enumerator is currently positioned before the first element or after the last element. @n + * - The collection is modified after the enumerator is created. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetLastResult() + */ + virtual Object* GetCurrent(void) const = 0; + + /** + * Gets the current key in the map. + * + * @since 2.0 + * + * @return A pointer to the current key in the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - The enumerator is currently positioned before the first element or after the last element. @n + * - The collection is modified after the enumerator is created. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetLastResult() + */ + virtual Object* GetKey(void) const = 0; + + /** + * Gets the current value in the map. + * + * @since 2.0 + * + * @return A pointer to the current value in the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - The enumerator is currently positioned before the first element or after the last element. @n + * - The collection is modified after the enumerator is created. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetLastResult() + */ + virtual Object* GetValue(void) const = 0; + +}; // IMapEnumerator + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IMAP_ENUMERATOR_H_ diff --git a/inc/FBaseColIMapEnumeratorT.h b/inc/FBaseColIMapEnumeratorT.h new file mode 100644 index 0000000..4c9263a --- /dev/null +++ b/inc/FBaseColIMapEnumeratorT.h @@ -0,0 +1,95 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIMapEnumeratorT.h + * @brief This is the header file for the %IMapEnumeratorT interface. + * + * This header file contains the declarations of the %IMapEnumeratorT interface. + */ +#ifndef _FBASE_COL_IMAP_ENUMERATOR_T_H_ +#define _FBASE_COL_IMAP_ENUMERATOR_T_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @interface IMapEnumeratorT + * @brief This interface supports simple iteration over a template-based map. + * Using this method, you can only access the elements in the map. You cannot modify the elements. + * + * @since 2.0 + * + * @remarks + * An enumerator remains valid as long as the map remains unchanged. + * If changes are made to the map, such as adding, modifying, or + * deleting elements, the enumerator is irrecoverably invalidated. The next call to any method returns an E_INVALID_OPERATION message. + * + * The %IMapEnumeratorT interface supports simple iteration over a template-based map. + * Using this method, you can only access the elements in the map. You cannot modify the elements. + * + * For more information on the class features, see HashMap and MultiHashMap. + * + */ +template< class KeyType, class ValueType > +class IMapEnumeratorT + : public virtual IEnumeratorT< MapEntryT< KeyType, ValueType > > +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMapEnumeratorT(void) {} + + /** + * Gets the current key in the map. + * + * @since 2.0 + * + * @return An error code + * @param[out] key The current key + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * The enumerator is currently positioned before the first element or after the last element or the collection is modified after the enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + virtual result GetKey(KeyType& key) const = 0; + + /** + * Gets the current value in the map. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The current value + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * The enumerator is currently positioned before the first element or after the last element or the collection is modified after the enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + virtual result GetValue(ValueType& value) const = 0; + +}; // IMapEnumeratorT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IMAP_ENUMERATOR_H_ diff --git a/inc/FBaseColIMapT.h b/inc/FBaseColIMapT.h new file mode 100644 index 0000000..252674f --- /dev/null +++ b/inc/FBaseColIMapT.h @@ -0,0 +1,230 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIMapT.h + * @brief This is the header file for the %IMapT interface. + * + * This header file contains the declarations of the %IMapT interface. + */ +#ifndef _FBASE_COL_IMAP_T_H_ +#define _FBASE_COL_IMAP_T_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +template< class Type > class IListT; + +/** + * @interface IMapT + * @brief This interface abstracts a template-based collection of key-value pairs. + * + * @since 2.0 + * + * The %IMapT interface abstracts a template-based collection of key-value pairs. An %IMapT + * contains unique keys and each key maps to a single value. + * The key and value cannot be a @c null reference. + * + * For more information on the class features, see HashMap and MultiHashMap. + * + */ +template< class KeyType, class ValueType > +class IMapT + : public virtual ICollectionT< MapEntryT< KeyType, ValueType > > +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMapT(void) {} + + /** + * Adds the specified key-value pair to the map. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to add + * @param[in] value The corresponding value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_ALREADY_EXIST The specified @c key already exists. + * @see Remove() + */ + virtual result Add(const KeyType& key, const ValueType& value) = 0; + + /** + * Gets the value associated with the specified key. + * + * @since 2.0 + * + * @return The value associated with the specified key, @n + * else @c null if an exception occurs + * @param[in] key The key to find the associated value + * @param[out] value The value associated with the key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see SetValue() + */ + virtual result GetValue(const KeyType& key, ValueType& value) const = 0; + + /** + * Gets the value associated with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to find the associated value + * @param[out] value The value associated with the key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see SetValue() + */ + virtual result GetValue(const KeyType& key, ValueType& value) = 0; + + /** + * Gets a list of all the keys in the map. + * + * @since 2.0 + * + * @return A pointer to a list of all the keys in the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The order of the keys is the same as the corresponding values in the IListT interface returned by the GetValuesN() method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetValuesN() + */ + virtual IListT< KeyType >* GetKeysN(void) const = 0; + + /** + * Gets a list of all the values in the map. + * + * @since 2.0 + * + * @return A pointer to a list of all values in the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetKeysN() + */ + virtual IListT< ValueType >* GetValuesN(void) const = 0; + + /** + * Removes the value associated with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the value is to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see Add() + */ + virtual result Remove(const KeyType& key) = 0; + + /** + * Removes all key-value pairs in the map. + * + * @since 2.0 + */ + virtual void RemoveAll(void) = 0; + + /** + * Replaces the value associated with the specified key with the specified value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key whose value is to replace + * @param[in] value The new value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks Use the Add() method to add a new key-value pair. + * @see Add() + * @see GetValue() + */ + virtual result SetValue(const KeyType& key, const ValueType& value) = 0; + + /** + * Checks whether the map contains the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[out] out Set to @c true if the map contains the specified key, @n + * else @c false + * @exception E_SUCCESS The method is successful. @n + * The map contains the specified key. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @see ContainsValue() + */ + virtual result ContainsKey(const KeyType& key, bool& out) const = 0; + + /** + * Checks whether the map contains the specified value. + * + * @since 2.0 + * + * @return @c true if the map contains the specified value, @n + * else @c false + * @param[in] value The value to locate + * + * @see ContainsKey() + */ + virtual bool ContainsValue(const ValueType& value) const = 0; + + /** + * Gets an instance of the IMapEnumeratorT class for the map. + * + * @since 2.0 + * + * @return An object of this map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * @see Tizen::Base::Collection::IMapEnumerator + */ + virtual IMapEnumeratorT< KeyType, ValueType >* GetMapEnumeratorN(void) const = 0; + +}; // IMapT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IMAP_T_H_ diff --git a/inc/FBaseColIMultiMap.h b/inc/FBaseColIMultiMap.h new file mode 100644 index 0000000..eb97e67 --- /dev/null +++ b/inc/FBaseColIMultiMap.h @@ -0,0 +1,596 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIMultiMap.h + * @brief This is the header file for the %IMultiMap interface. + * + * This header file contains the declarations of the %IMultiMap interface. + */ +#ifndef _FBASE_COL_IMULTI_MAP_H_ +#define _FBASE_COL_IMULTI_MAP_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +class IList; +class MapEntry; + +/** + * @interface IMultiMap + * @brief This interface represents a collection of key-value pairs. + * + * @since 2.0 + * + * The %IMultiMap interface abstracts a collection of key-value pairs. + * There is no limit on the number of elements with the same key, but duplicated elements with the same key are not allowed. + * The key and value cannot be a @c null reference. + * @n + * For more information on the class features, see HashMap and MultiHashMap. + * + */ +class _OSP_EXPORT_ IMultiMap + : public virtual ICollection +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMultiMap(void) {} + + /** + * @if OSPDEPREC + * Adds the specified key-value pair to the map. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it has a problem of const reference argument. + * Instead of using this method, use Add(Object* pKey, Object* pValue). + * @since 2.0 + * + * @return An error code + * @param[in] key The key to add + * @param[in] value The corresponding value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_ALREADY_EXIST The specified @c key and @c value already exist. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see Remove() + * @endif + */ + result Add(const Object& key, const Object& value) + { + return Add(const_cast< Object* >(&key), const_cast< Object* >(&value)); + } + + /** + * Adds the specified key-value pair to the map. + * + * @since 2.0 + * + * @return An error code + * @param[in] pKey The pointer to key to add + * @param[in] pValue The pointer to corresponding value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_ALREADY_EXIST The specified @c pKey and @c pValue already exist. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see Remove() + */ + virtual result Add(Object* pKey, Object* pValue) = 0; + + /** + * Gets the number of values stored in the map. + * + * @since 2.0 + * + * @return The number of values currently stored in the map + */ + virtual int GetCount(void) const = 0; + + /** + * Gets the number of values with keys matching the specified key. + * + * @since 2.0 + * + * @return The number of values with keys matching the specified key + * @param[in] key The key to locate in the map + * @param[out] count The number of values with keys matching the specified key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + */ + virtual result GetCount(const Object& key, int& count) const = 0; + + /** + * Gets an enumerator of the values associated with the specified key. + * + * @since 2.0 + * + * @return An instance of the IEnumerator derived class with the values associated with the specified key, @n + * else @c null if an exception occurs + * @param[in] key The key to locate in the map + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual IEnumerator* GetValuesN(const Object& key) const = 0; + + /** + * Gets a list of all the keys in the map. + * + * @since 2.0 + * + * @return A pointer to a list of all the keys in the map, @n + * else @c null if an exception occurs + * @remarks The order of the keys is the same as the corresponding values in the IList interface returned by the GetValuesN() method. + * @remarks The %IList stores just the pointers to the elements in the map, not the elements themselves. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetValuesN() + */ + virtual IList* GetKeysN(void) const = 0; + + /** + * Gets a list of all the values in the map. + * + * @since 2.0 + * + * @return A pointer to a list of all the values in the map, @n + * else @c null if an exception occurs + * @remarks The IList stores just the pointers to the elements in the map, not the elements themselves. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetValue() + */ + virtual IList* GetValuesN(void) const = 0; + + /** + * Removes all the values associated with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the associated values need to remove + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks Remove(key, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * Remove(key); + * SetDeleter(deleter); + * @endcode + * @remarks Remove(key, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * Remove(key); + * SetDeleter(deleter); + * @endcode + * @see Add() + */ + result Remove(const Object& key, bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = Remove(key); + SetDeleter(deleter); + return r; + } + + /** + * Removes all the values associated with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the associated values need to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see Add() + */ + virtual result Remove(const Object& key) = 0; + + /** + * Removes the specified value associated with the specified key. @n + * The key is also removed if there are no more values associated with it. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the mapping is to remove from the map + * @param[in] value The value to remove + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The @c key and @c value pair is not found in the map. + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks Remove(key, value, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * Remove(key, value); + * SetDeleter(deleter); + * @endcode + * @remarks Remove(key, value, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * Remove(key, value); + * SetDeleter(deleter); + * @endcode + * @see Add() + */ + result Remove(const Object& key, const Object& value, bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = Remove(key, value); + SetDeleter(deleter); + return r; + } + + /** + * Removes the specified value associated with the specified key. @n + * The key is also removed if there are no more values associated with it. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the mapping is to remove from the map + * @param[in] value The value to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The @c key and @c value pair is not found in the map. + * @see Add() + */ + virtual result Remove(const Object& key, const Object& value) = 0; + + /** + * Removes all the object pointers in the collection. @n + * If the @c forceDeletion parameter is set to @c true, the method also removes all the objects. This method can be called before deleting the collection. + * + * @since 2.0 + * + * @param[in] forceDeletion Set to @c true to deallocate all objects, @n + * else @c false + * @remarks Based on the specified element deleter, the remove operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the remove method.@n + * If both an element deleter and forceDeleteion are set, the remove operation follows @c forceDeletion setting. + * @remarks RemoveAll(@b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * RemoveAll(); + * SetDeleter(deleter); + * @endcode + * @remarks RemoveAll(@b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * RemoveAll(); + * SetDeleter(deleter); + * @endcode + */ + void RemoveAll(bool forceDeletion) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + RemoveAll(); + SetDeleter(deleter); + } + + /** + * Removes all the object pointers in the collection. @n + * This method can be called before deleting the collection. + * + * @since 2.0 + */ + virtual void RemoveAll(void) = 0; + + /** + * Replaces the specified value associated with the specified key with a new value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the associated value needs to replace + * @param[in] value The value associated with the key + * @param[in] newValue The new value + * @param[in] forceDeletion Set to @c true to deallocate the object, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The key-value pair is not found in the map. + * @remarks Use the Add() method to add a new key-value pair. + * @remarks Based on the specified element deleter, the set operation not only gets rid of an element from a list, but also deletes its object instance.@n + * The element deleter style is recommended rather than using the @c forceDeletetion argument in the set method.@n + * If both an element deleter and forceDeleteion are set, the set operation follows @c forceDeletion setting. + * @remarks SetValue(key, value, newValue, @b true) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(SingleObjectDeleter); + * SetValue(key, value, const_cast< Object* >(&newValue)); + * SetDeleter(deleter); + * @endcode + * @remarks SetValue(key, value, newValue, @b false) internally works as the below code: + * @code + * DeleterFunctionType deleter = GetDeleter(); + * SetDeleter(NoOpDeleter); + * SetValue(key, value, const_cast< Object* >(&newValue)); + * SetDeleter(deleter); + * @endcode + * @see Add() + * @see GetValuesN() + */ + result SetValue(const Object& key, const Object& value, const Object& newValue, bool forceDeletion = false) + { + DeleterFunctionType deleter = GetDeleter(); + + if (forceDeletion) + { + SetDeleter(SingleObjectDeleter); + } + else + { + SetDeleter(NoOpDeleter); + } + + result r = SetValue(key, value, const_cast< Object* >(&newValue)); + SetDeleter(deleter); + return r; + } + + /** + * Replaces the specified value associated with the specified key with a new value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the associated value needs to replace + * @param[in] value The value associated with the key + * @param[in] pNewValue The pointer to new value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The key-value pair is not found in the map. + * @remarks Use the Add() method to add a new key-value pair. + * @see Add() + * @see GetValuesN() + */ + virtual result SetValue(const Object& key, const Object& value, Object* pNewValue) = 0; + + /** + * @if OSPDEPREC + * Checks whether the map contains the specified key-value pair. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it transfers a result of comparison in out-parameter form. + * The return type will be changed into boolean type and this method will return the result. + * Instead of using this method, use bool Contains(const Object& key, const Object& value). + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[in] value The value to locate + * @param[out] out Set to @c true if the map contains the specified key-value pair, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @see ContainsKey() + * @see ContainsValue() + * @endif + */ + result Contains(const Object& key, const Object& value, bool& out) const + { + out = Contains(key, value); + result r = GetLastResult(); + return r; + } + + /** + * Checks whether the map contains the specified key-value pair. + * + * @since 2.0 + * + * @return @c true if the map contains the specified key-value pair, @n + * else @c false + * @param[in] key The key to locate + * @param[in] value The value to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see ContainsKey() + * @see ContainsValue() + */ + virtual bool Contains(const Object& key, const Object& value) const = 0; + + /** + * @if OSPDEPREC + * Checks whether the map contains the specified key. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it transfers a result of comparison in out-parameter form. + * The return type will be changed into boolean type and this method will return the result. + * Instead of using this method, use bool ContainsKey(const Object& key). + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[out] out Set to @c true if the map contains the specified key, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @see ContainsValue() + * @see Contains() + * @endif + */ + result ContainsKey(const Object& key, bool& out) const + { + out = ContainsKey(key); + result r = GetLastResult(); + return r; + } + + /** + * Checks whether the map contains the specified key. + * + * @since 2.0 + * + * @return @c true if the map contains the specified key, @n + * else @c false + * @param[in] key The key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see ContainsValue() + * @see Contains() + */ + virtual bool ContainsKey(const Object& key) const = 0; + + /** + * Checks whether the map contains the specified value. + * + * @since 2.0 + * + * @return @c true if the map contains the specified value, @n + * else @c false + * @param[in] value The value to locate + * + * @see ContainsKey() + * @see Contains() + */ + virtual bool ContainsValue(const Object& value) const = 0; + + /** + * Gets an enumerator of the map. + * + * @since 2.0 + * + * @return An instance of the IMapEnumerator class for the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @remarks If a key has multiple values, the enumeration proceeds as follows: @n + * {A: a}, {B: b}, {B: c}, {B, d}, {C: e}, ... + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see IEnumerator + * @see IMapEnumerator + */ + virtual IMapEnumerator* GetMapEnumeratorN(void) const = 0; + + /** + * Gets the element deleter of the collection. + * + * @since 2.0 + * + * @return An function pointer to the existing element deleter + */ + virtual DeleterFunctionType GetDeleter(void) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMultiMap_Reserved1(void) { } + + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMultiMap_Reserved2(void) { } + +private: + /** + * Sets the element deleter of the collection. + * + * @since 2.0 + * + * @param[in] deleter A function pointer to the element deleter to set + */ + virtual void SetDeleter(DeleterFunctionType deleter) = 0; + +}; // IMultiMap + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IMULTI_MAP_H_ diff --git a/inc/FBaseColIMultiMapT.h b/inc/FBaseColIMultiMapT.h new file mode 100644 index 0000000..ef1c2e1 --- /dev/null +++ b/inc/FBaseColIMultiMapT.h @@ -0,0 +1,280 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColIMultiMapT.h + * @brief This is the header file for the %IMultiMapT interface. + * + * This header file contains the declarations of the %IMultiMapT interface. + */ +#ifndef _FBASE_COL_IMULTI_MAP_T_H_ +#define _FBASE_COL_IMULTI_MAP_T_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +template< class Type > class IListT; + +/** + * @interface IMultiMapT + * @brief This interface represents a template-based collection of key-value pairs. + * + * @since 2.0 + * + * The %IMultiMapT interface abstracts a template-based collection of key-value pairs. + * There is no limit on the number of elements with the same key, but duplicated elements with the same key are not allowed. + * The key and value cannot be a @c null reference. + * @n + * For more information on the class features, see HashMap and MultiHashMap. + * + */ +template< class KeyType, class ValueType > +class IMultiMapT + : public virtual ICollectionT< MapEntryT< KeyType, ValueType > > +{ +public: + /** + * This polymorphic destructor should be overridden if required. @n + * This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMultiMapT(void) {} + + /** + * Adds the specified key-value pair to the map. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to add + * @param[in] value The corresponding value to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_ALREADY_EXIST The specified @c key and @c value already exists. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @see Remove() + */ + virtual result Add(const KeyType& key, const ValueType& value) = 0; + + /** + * Gets the number of values stored in the map. + * + * @since 2.0 + * + * @return The number of values currently stored in the map + */ + virtual int GetCount(void) const = 0; + + /** + * Gets the number of values whose key matches the specified key. + * + * @since 2.0 + * + * @return The number of values whose key matches the specified key + * @param[in] key The key to locate in the map + * @param[out] count The number of values whose key matches the specified key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + */ + virtual result GetCount(const KeyType& key, int& count) const = 0; + + /** + * Gets an enumerator of the values associated with the specified key. + * + * @since 2.0 + * + * @return An instance of the IEnumeratorT derived class with the values associated with the specified key, @n + * else @c null if an exception occurs + * @param[in] key The key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetValue() + */ + virtual IEnumeratorT< ValueType >* GetValuesN(const KeyType& key) const = 0; + + /** + * Gets a list of all the keys in the map. + * + * @since 2.0 + * + * @return A pointer to a list of all the keys in the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The order of the keys is the same as the corresponding values in the IListT interface returned by the GetValuesN() method. + * The specific error code can be accessed using the GetLastResult() method. + * @see GetValuesN() + */ + virtual IListT< KeyType >* GetKeysN(void) const = 0; + + /** + * Gets a list of all the values in the map. + * + * @since 2.0 + * + * @return A pointer to a list of all the values in the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetKeysN() + */ + virtual IListT< ValueType >* GetValuesN(void) const = 0; + + /** + * Removes all the values associated with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key whose associated values need to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see Add() + */ + virtual result Remove(const KeyType& key) = 0; + + /** + * Removes the specified value associated with the specified key. @n + * The key is also removed if there are no more values associated with it. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key whose mapping is to remove from the map + * @param[in] value The value to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key and @c value pair is not found in the map. + * @see Add() + */ + virtual result Remove(const KeyType& key, const ValueType& value) = 0; + + /** + * Removes all the key-value pairs in the map. + * + * @since 2.0 + */ + virtual void RemoveAll(void) = 0; + + /** + * Replaces the specified value associated with the specified key with a new value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key whose associated value needs to replace + * @param[in] value The value associated with the key + * @param[in] newValue The new value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key and @c value pair is not found in the map. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks Use the Add() method to add a new key-value pair. + * @see Add() + * @see GetValuesN() + */ + virtual result SetValue(const KeyType& key, const ValueType& value, const ValueType& newValue) = 0; + + /** + * Checks whether the map contains the specified key-value pair. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[in] value The value to locate + * @param[out] out Set to @c true if the map contains the specified key-value pair, @n + * else @c false + * @exception E_SUCCESS The method is successful. @n + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @see ContainsKey() + * @see ContainsValue() + */ + virtual result Contains(const KeyType& key, const ValueType& value, bool& out) const = 0; + + /** + * Checks whether the map contains the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[out] out Set to @c true if the map contains the specified key, @n + * else @c false + * @exception E_SUCCESS The method is successful. @n + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @see ContainsValue() + * @see Contains() + */ + virtual result ContainsKey(const KeyType& key, bool& out) const = 0; + + /** + * Checks whether the map contains the specified value. + * + * @since 2.0 + * + * @return Set to @c true if the map contains the specified value, @n + * else @c false + * @param[in] value The value to locate + * + * @see ContainsKey() + * @see Contains() + */ + virtual bool ContainsValue(const ValueType& value) const = 0; + + /** + * Gets an enumerator of the map. + * + * @since 2.0 + * + * @return An instance of the IMapEnumeratorT class for the map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks If a key has multiple values, the enumeration proceeds as follows: @n + * {A: a}, {B: b}, {B: c}, {B, d}, {C: e}, ... @n + * The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * @see Tizen::Base::Collection::IMapEnumerator + */ + virtual IMapEnumeratorT< KeyType, ValueType >* GetMapEnumeratorN(void) const = 0; + +}; // IMultiMapT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_IMULTI_MAP_T_H_ diff --git a/inc/FBaseColLinkedList.h b/inc/FBaseColLinkedList.h new file mode 100644 index 0000000..29e8f41 --- /dev/null +++ b/inc/FBaseColLinkedList.h @@ -0,0 +1,627 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColLinkedList.h + * @brief This is the header file for the %LinkedList class. + * + * This header file contains the declarations of the %LinkedList class. + */ +#ifndef _FBASE_COL_LINKED_LIST_H_ +#define _FBASE_COL_LINKED_LIST_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +class _ListNode; + +/** + * @class LinkedList + * @brief This class represents a collection of objects that can be individually accessed by index. + * + * @since 2.0 + * + * The %LinkedList class represents a collection of objects that can be individually accessed by index. + * + * For more information on the class features, see ArrayList and LinkedList. + * + * The following example demonstrates how to use the %LinkedList class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::LinkedListSample(void) + * { + * LinkedList list(SingleObjectDeleter); + * + * list.Add(new Integer(1)); // 1 + * list.Add(new Integer(2)); // 1,2 + * list.Add(new Integer(3)); // 1,2,3 + * + * Integer* pInt = static_cast (list.GetAt(0)); + * + * if (pValue->Equals(Integer(1)) + * { + * // Must be here + * } + * + * list.InsertAt(new Integer(4), 1); // 1,4,2,3 + * + * list.Remove(Integer(3)); // 1,4,2 + * + * list.RemoveAt(0); // 4,2 + * + * list.Sort(IntegerComparer()); // 2,4 + * + * // Uses an enumerator to access elements in the list + * IEnumerator* pEnum = list.GetEnumeratorN(); + * Object* pObj = null; + * while (pEnum->MoveNext() == E_SUCCESS) + * { + * pObj = pEnum->GetCurrent(); + * } + * + * delete pEnum; + * + * // Deallocates all objects + * // Because the destructor calls RemoveAll() internally, you don't need to call RemoveAll() to destroy all elements at the end. + * list.RemoveAll(); + * } + * @endcode + */ +class _OSP_EXPORT_ LinkedList + : public IList + , public Object +{ +public: + using IList::Add; + using IList::InsertAt; + using IList::Remove; + using IList::RemoveAt; + using IList::RemoveItems; + using IList::RemoveAll; + using IList::SetAt; + using IList::ContainsAll; + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @param[in] deleter The function pointer to type of the element deleter + * @remarks To create an owing collection, set the element deleter value as @c SingleObjectDeleter. This gives the collection the ownership of elements and the collection will destroy elements. @n + * On the other hand, to create a non-owning collection, you don't need to set the element deleter value, as @c NoOpDeleter is the default element deleter. + * It means that you don't transfer the ownership of elements to the collection. + * @see NoOpDeleter() + * @see SingleObjectDeleter() + * @see ArrayDeleter() + */ + explicit LinkedList(DeleterFunctionType deleter = NoOpDeleter); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~LinkedList(void); + + /** + * Adds the given object to the end of this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj An pointer to object to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see Remove() + */ + virtual result Add(Object* pObj); + + /** + * Adds the elements of the given collection to the end of this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection A collection to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see RemoveItems() + */ + virtual result AddItems(const ICollection& collection); + + /** + * Gets an enumerator (an instance of the IEnumerator derived class) to the list. + * + * @since 2.0 + * + * @return An enumerator of the calling list object, @n + * else @c null if an exception occurs + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + */ + virtual IEnumerator* GetEnumeratorN(void) const; + + /** + * Gets a bidirectional enumerator (an instance of the IBidirectionalEnumerator derived class) of this list. + * + * @since 2.0 + * + * @return An instance of the IBidirectionalEnumerator derived class, @n + * else @c null if some exception occurs + * @remarks Use this method to obtain a bidirectional enumerator (an instance of the IBidirectionalEnumerator derived class) + * to iterate over a collection (an instance of the IList derived class). + * The specific error code can be accessed using GetLastResult() method. + * @see Tizen::Base::Collection::IBidirectionalEnumerator + */ + virtual IBidirectionalEnumerator* GetBidirectionalEnumeratorN(void) const; + + /** + * Gets the object at the specified index of the calling list. + * + * @since 2.0 + * + * @return A pointer to the object at the specified index of the list, @n + * else @c null if the index is not valid + * @param[in] index The index of the object to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is equal to or greater than the number of elements or less than @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetAt() + */ + virtual const Object* GetAt(int index) const; + + /** + * Gets the object at the specified index of the calling list. + * + * @since 2.0 + * + * @return A pointer to the object at the specified index of the list, @n + * else @c null if the index is not valid + * @param[in] index The index of the object to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is equal to or greater than the number of elements or less than @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetAt() + */ + virtual Object* GetAt(int index); + + /** + * Gets an IList with the specified range from the calling list object. + * + * @since 2.0 + * + * @return An IList pointer if successful, @n + * else @c null if an exception occurs + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * @remarks The IList stores just the pointers to the elements in the list, not the elements themselves. + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual IList* GetItemsN(int startIndex, int count) const; + + /** + * Searches for an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + */ + virtual result IndexOf(const Object& obj, int& index) const; + + /** + * Searches for an object starting from the specified index. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index for the search @n + * It must be less than the number of elements. + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Object& obj, int startIndex, int& index) const; + + /** + * Searches for an object within the specified range. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Object& obj, int startIndex, int count, int& index) const; + + /** + * Searches for the last occurrence of an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the last occurrence of the specified object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see IndexOf() + */ + virtual result LastIndexOf(const Object& obj, int& index) const; + + /** + * Inserts the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj The pointer to object to insert + * @param[in] index The index at which the object must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is greater than the number of elements or less than @c 0. + * @remarks If the @c index equals to the number of elements, then the new element + * is added at the end of this list. + * This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see Add() + * @see RemoveAt() + */ + virtual result InsertAt(Object* pObj, int index); + + /** + * Inserts the elements of the collection at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to insert elements from + * @param[in] startIndex The starting index at which the elements must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c startIndex is either greater than the number of elements or less than @c 0. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks If the @c startIndex equals to the number of elements then the new elements + * are added at the end of this list. + * This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see RemoveItems() + * @see AddItems() + */ + virtual result InsertItemsFrom(const ICollection& collection, int startIndex); + + /** + * Removes the first occurrence of the specified object from the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj An object to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see Add() + * @see RemoveAt() + */ + virtual result Remove(const Object& obj); + + /** + * Removes the object at the specified location in the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the object must be removed + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * The specified @c index is equal to or greater than the number of elements or less than @c 0. + * @see InsertAt() + */ + virtual result RemoveAt(int index); + + /** + * Removes all elements within the specified range from the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting index of the range + * @param[in] count The number of element to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * @see AddItems() + * @see InsertItemsFrom() + */ + virtual result RemoveItems(int startIndex, int count); + + /** + * Removes all the elements that are common in the specified @c collection + * and the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to remove from this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @see Remove() + * @see RemoveAt() + */ + virtual result RemoveItems(const ICollection& collection); + + + /** + * Removes all of the object pointers in the collection and also removes all of the objects depending on the specified element deleter. + * This method can be called before deleting the objects in a collection. + * + * @since 2.0 + * + */ + virtual void RemoveAll(void); + + /** + * Replaces the object at the specified index with the given object. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj The pointer to object to set + * @param[in] index The index at which the object must be set + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is equal to or greater than the number of elements or less than @c 0. + * @see GetAt() + */ + virtual result SetAt(Object* pObj, int index); + + /** + * Sorts the elements of this list using the comparer provided. + * + * @since 2.0 + * + * @return An error code + * @param[in] comparer The IComparer implementation to use when comparing elements + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the @c comparer is not valid. + */ + virtual result Sort(const IComparer& comparer); + + /** + * Gets the number of objects currently stored in this list. + * + * @since 2.0 + * + * @return The number of objects currently stored in this list + */ + virtual int GetCount(void) const; + + /** + * Checks whether the list contains the specified object. + * + * @since 2.0 + * + * @return @c true if the list contains the specified object, @n + * else @c false + * @param[in] obj The object to locate + * @see ContainsAll() + */ + virtual bool Contains(const Object& obj) const; + + /** + * Checks whether the list contains all the elements of the specified collection. + * + * @since 2.0 + * + * @return @c true if this list contains all of the elements in the specified collection, @n + * else @c false + * @param[in] collection The collection to check for containment in this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the given @c collection is empty, this method will return @c true. + * @see Contains() + */ + virtual bool ContainsAll(const ICollection& collection) const; + + /** + * Compares the given object with the calling %LinkedList object. + * + * @since 2.0 + * + * @return @c true if the specified instance equals the current instance, @n + * else @c false + * @param[in] obj The object to compare with the calling object + * @remarks This method returns @c true only if the specified object is also an instance of the %LinkedList class, + * both lists have the same size, and all corresponding pairs of elements in the two lists are equal. + * In other words, two lists are equal if they contain the same elements in the same order. + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the element deleter of the collection. + * + * @since 2.0 + * + * @return An function pointer to the existing element deleter + */ + virtual DeleterFunctionType GetDeleter(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] list The %LinkedList object to initialize the new object + */ + LinkedList(const LinkedList& list); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] list An instance of %LinkedList + */ + LinkedList& operator =(const LinkedList& list); + + /** + * Allocates and adds a memory block. + * + * @return An error code + * @param[in] blockSize The size of block to allocate + * @exception E_SUCCESS The method is successful. + */ + result AddBlock(int blockSize = DEFAULT_CAPACITY); + + /** + * Frees memory blocks of the list. + * + */ + void DeleteBlock(void); + + /** + * Inserts an object to the beginning of the %LinkedList. + * + * @return An error code + * @param[in] pObj The pointer to object to insert + * @exception E_SUCCESS The method is successful. + */ + result InsertFirst(Object* pObj); + + /** + * Inserts an object to the end of the %LinkedList. + * + * @return An error code + * @param[in] pObj The pointer to object to insert + * @exception E_SUCCESS The method is successful. + */ + result InsertLast(Object* pObj); + + /** + * Inserts an object after the specified node. + * + * @return An error code + * @param[in] pObj The pointer to object to insert + * @param[in] pPrevNode The node after which the object must inserted + * @exception E_SUCCESS The method is successful. + */ + result InsertNext(Object* pObj, _ListNode* pPrevNode); + + /** + * Gets a node from Available node list. + * + * @return A pointer to a new List Node if successful, @n + * else @c null if no node is available + */ + _ListNode* GetNewNode(void); + + /** + * Gets the node at the specified index. + * + * @return A node at the specified index + * @param[in] index The index of the node to read + */ + _ListNode* GetNode(int index) const; + + /** + * Removes the specified node. + * + * @param[in] pNode The pointer of the node to remove + */ + void RemoveNode(_ListNode* pNode); + + /** + * Sets the element deleter of the collection. + * + * @since 2.0 + * + * @param[in] deleter A function pointer to the element deleter to set + */ + virtual void SetDeleter(DeleterFunctionType deleter); + + _ListNode* __pListHead; + _ListNode* __pListTail; + _ListNode* __pAvailableHead; + _ListNode* __pAvailableTail; + _ListNode* __pBlocks; + int __count; + int __capacity; + int __modCount; + static const int DEFAULT_CAPACITY = 10; + DeleterFunctionType __deleter; + + friend class _LinkedListEnumerator; + friend class _LinkedListImpl; + class _LinkedListImpl* __pLinkedListImpl; + +}; // LinkedList + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_LINKED_LIST_H_ diff --git a/inc/FBaseColLinkedListT.h b/inc/FBaseColLinkedListT.h new file mode 100644 index 0000000..7d0ea43 --- /dev/null +++ b/inc/FBaseColLinkedListT.h @@ -0,0 +1,1529 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColLinkedListT.h + * @brief This is the header file for the %LinkedListT class. + * + * This header file contains the declarations of the %LinkedListT class. + */ +#ifndef _FCOL_LINKED_LIST_T_H_ +#define _FCOL_LINKED_LIST_T_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +template< class Type > class __LinkedListEnumeratorT; +template< class Type > class __LinkedListNodeT; + +/** + * @class LinkedListT + * @brief This class represents a template-based collection of objects that can be individually accessed by index. + * + * @since 2.0 + * + * The %LinkedListT class represents a template-based collection of objects that can be individually accessed by index. + * + * For more information on the class features, see ArrayList and LinkedList. + * + * The following example demonstrates how to use the %LinkedListT class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::LinkedListTSample(void) + * { + * LinkedListT list; + * + * int int1 = 1; + * int int2 = 2; + * int int3 = 3; + * int int4 = 4; + * + * list.Add(int1); // 1 + * list.Add(int2); // 1,2 + * list.Add(int3); // 1,2,3 + * + * int temp; + * for (int i = 0; i < list.GetCount(); i++) + * { + * list.GetAt(i, temp); + * } + * + * list.InsertAt(int4, 1); // 1,4,2,3 + * + * ComparerT* pIntComparer = new ComparerT(); + * list.Sort(*pIntComparer); // 1,2,3,4 + * + * delete pIntComparer; + * + * list.Remove(int3); // 1,2,4 + * list.RemoveAt(0); // 2,4 + * + * // Uses an enumerator to access elements in the list + * IEnumeratorT* pEnum = list.GetEnumeratorN();; + * while (pEnum->MoveNext() == E_SUCCESS) + * { + * pEnum->GetCurrent(temp); + * } + * + * delete pEnum; + * } + * @endcode + */ +template< class Type > +class LinkedListT + : public IListT< Type > + , public Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + LinkedListT(void) + : __pListHead(null) + , __pListTail(null) + , __count(0) + , __modCount(0) + { + } + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~LinkedListT(void) + { + __modCount++; + + RemoveAll(); + } + + /** + * Adds the specified object to the end of this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj An object to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @see Remove() + */ + virtual result Add(const Type& obj) + { + result r = E_SUCCESS; + + if (null == __pListHead) + { + r = InsertFirst(obj); + } + else + { + r = InsertLast(obj); + } + if (r != E_SUCCESS) + { + AppLogException("[%s] Propagating.", GetErrorMessage(r)); + } + + return r; + } + + /** + * Adds the elements of the specified collection to the end of this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection A collection to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @see RemoveItems() + */ + virtual result AddItems(const ICollectionT< Type >& collection) + { + result r = InsertItemsFrom(collection, __count); + if (r != E_SUCCESS) + { + AppLogException("[%s] Propagating.", GetErrorMessage(r)); + } + + return r; + } + + /** + * Gets an enumerator to this list. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IEnumeratorT derived class) of this list, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumeratorT + */ + virtual IEnumeratorT< Type >* GetEnumeratorN(void) const + { + ClearLastResult(); + + result r = E_SUCCESS; + + __LinkedListEnumeratorT< Type >* pEnum = new __LinkedListEnumeratorT< Type >(*this, __modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Gets a bidirectional enumerator (an instance of the IBidirectionalEnumeratorT derived class) of this list. + * + * @since 2.0 + * + * @return An instance of the IBidirectionalEnumeratorT derived class if successful, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks Use this method to obtain a bidirectional enumerator (an instance of the IBidirectionalEnumeratorT derived class) + * to iterate over a collection (an instance of the IListT derived class). + * The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IBidirectionalEnumeratorT + */ + virtual IBidirectionalEnumeratorT< Type >* GetBidirectionalEnumeratorN(void) const + { + ClearLastResult(); + + result r = E_SUCCESS; + + __LinkedListEnumeratorT< Type >* pEnum = new __LinkedListEnumeratorT< Type >(*this, __modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Gets the object at the specified index of this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the object to read + * @param[out] obj An object to get from this list + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is equal to or greater than the number of elements or less than @c 0. + * @see SetAt() + */ + virtual result GetAt(int index, Type& obj) const + { + TryReturn(index >= 0 && index < __count, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + __LinkedListNodeT< Type >* pNode = GetNode(index); + if (pNode != null) + { + obj = pNode->pObj; + } + return E_SUCCESS; + } + + /** + * Gets the object at the specified index of this list. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index of the object to read + * @param[out] obj An object to get from this list + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is equal to or greater than the number of elements or less than @c 0. + * @see SetAt() + */ + virtual result GetAt(int index, Type& obj) + { + TryReturn(index >= 0 && index < __count, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + __LinkedListNodeT< Type >* pNode = GetNode(index); + if (pNode != null) + { + obj = pNode->pObj; + } + return E_SUCCESS; + } + + /** + * Gets an IListT-derived instance with the specified range from the calling list object. + * + * @since 2.0 + * + * @return A pointer to the IListT derived instance, @n + * else @c null if an exception occurs. + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual IListT< Type >* GetItemsN(int startIndex, int count) const + { + ClearLastResult(); + + result r = E_SUCCESS; + LinkedListT< Type >* pList = null; + __LinkedListNodeT< Type >* pNode = null; + __LinkedListNodeT< Type >* pPrevNode = null; + + TryCatch(startIndex >= 0 && count >= 0, r = E_OUT_OF_RANGE, + "[%s] Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count); + TryCatch(startIndex < __count, r = E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + TryCatch(count <= __count && (startIndex + count <= __count), r = E_OUT_OF_RANGE, + "[%s] The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count, __count); + + pList = new LinkedListT< Type >(); + + pNode = GetNode(startIndex); + if ((pList != null) && (pNode != null)) + { + r = pList->InsertFirst(pNode->pObj); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + pNode = pNode->pNext; + pPrevNode = pList->__pListTail; + + for (int i = 0; i < (count - 1); i++) + { + if (pNode != null) + { + pPrevNode = pList->InsertNext(pPrevNode, pNode->pObj); + TryCatch(pPrevNode != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + pNode = pNode->pNext; + } + } + } + + return pList; + +CATCH: + SetLastResult(r); + delete pList; + + return null; + } + + /** + * Searches for an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + */ + virtual result IndexOf(const Type& obj, int& index) const + { + result r = E_SUCCESS; + if (__count == 0) + { + r = E_OBJ_NOT_FOUND; + } + else + { + r = IndexOf(obj, 0, __count, index); + } + + return r; + } + + /** + * Searches for an object starting from the specified index. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index for the search @n + * It must be less than the number of elements. + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Type& obj, int startIndex, int& index) const + { + TryReturn((startIndex >= 0 && startIndex < __count), E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + + return IndexOf(obj, startIndex, (__count - startIndex), index); + } + + /** + * Searches for an object within the specified range. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @param[out] index The index of the object + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements in the list or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see LastIndexOf() + */ + virtual result IndexOf(const Type& obj, int startIndex, int count, int& index) const + { + TryReturn(startIndex >= 0 && count >= 0, E_OUT_OF_RANGE, + "[%s] Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count); + TryReturn(startIndex < __count, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + TryReturn(count <= __count && (startIndex + count <= __count), E_OUT_OF_RANGE, + "[%s] The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count, __count); + + result r = E_OBJ_NOT_FOUND; + __LinkedListNodeT< Type >* pNode = GetNode(startIndex); + for (int i = 0; i < count; i++) + { + if (pNode != null) + { + if (obj == pNode->pObj) + { + index = (startIndex + i); + r = E_SUCCESS; + break; + } + pNode = pNode->pNext; + } + } + + return r; + } + + /** + * Inserts the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj An object to insert + * @param[in] index The index at which the object must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is greater than the number of elements or less than @c 0. + * @remarks If the @c index equals to the number of elements then the new element + * is added at the end of this list. + * @see Add() + * @see RemoveAt() + */ + virtual result InsertAt(const Type& obj, int index) + { + TryReturn(index >= 0 && index <= __count, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + result r = E_SUCCESS; + + __LinkedListNodeT< Type >* pPrevNode = null; + if (index == 0) + { + r = InsertFirst(obj); + } + else if (index == __count) + { + r = InsertLast(obj); + } + else + { + pPrevNode = GetNode(index - 1); + if (pPrevNode != null) + { + InsertNext(pPrevNode, obj); + } + r = GetLastResult(); + } + if (r != E_SUCCESS) + { + AppLogException("[%s] Propagating.", GetErrorMessage(r)); + } + + return r; + } + + + /** + * Inserts the elements of the @c collection at the location specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to insert + * @param[in] startIndex The starting index at which the collection must be inserted + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c startIndex is either greater than the number of elements or less than @c 0. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks If the @c startIndex equals to the number of elements then the new elements + * are added at the end of this list. + * @see RemoveItems() + * @see AddItems() + */ + virtual result InsertItemsFrom(const ICollectionT< Type >& collection, int startIndex) + { + TryReturn(startIndex >= 0 && startIndex <= __count, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be greater than or equal to 0, and less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + + result r = E_SUCCESS; + + IEnumeratorT< Type >* pEnum = null; + int count = collection.GetCount(); + if (count > 0) + { + __LinkedListNodeT< Type >* pPrevNode = null; + ; + if (startIndex == __count) + { + pPrevNode = __pListTail; + } + else if (startIndex > 0) + { + pPrevNode = GetNode(startIndex - 1); + } + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + pEnum = pCol->GetEnumeratorN(); + TryCatch(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (true) + { + Type obj; + r = pEnum->MoveNext(); + + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + break; + } + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(obj); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + if (null == pPrevNode) + { + r = InsertFirst(obj); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + pPrevNode = __pListHead; + } + else + { + pPrevNode = InsertNext(pPrevNode, obj); + TryCatch(pPrevNode != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + } + } + } + + if (null != pEnum) + { + delete pEnum; + } + + return r; + +CATCH: + if (null != pEnum) + { + delete pEnum; + } + return r; + } + + /** + * Searches for the last occurrence of an object in this list. @n + * Gets the index of the object if found. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to locate + * @param[out] index The index of the last occurrence of the specified object + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see IndexOf() + */ + virtual result LastIndexOf(const Type& obj, int& index) const + { + result r = E_OBJ_NOT_FOUND; + __LinkedListNodeT< Type >* pNode = __pListTail; + for (int i = (__count - 1); i >= 0; i--) + { + if (obj == pNode->pObj) + { + index = i; + r = E_SUCCESS; + break; + } + pNode = pNode->pPrev; + } + + return r; + } + + /** + * Removes the first occurrence of the specified object from the list. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj An object to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c obj is not found. + * @see Add() + * @see RemoveAt() + * @see RemoveAll() + */ + virtual result Remove(const Type& obj) + { + result r = E_OBJ_NOT_FOUND; + __LinkedListNodeT< Type >* pNode = __pListHead; + while (null != pNode) + { + if (pNode->pObj == obj) + { + RemoveNode(pNode); + r = E_SUCCESS; + break; + } + pNode = pNode->pNext; + } + + return r; + } + + /** + * Removes all the elements in the specified @c collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to remove from this list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @see Remove() + * @see RemoveAt() + */ + virtual result RemoveItems(const ICollectionT< Type >& collection) + { + result r = E_SUCCESS; + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + IEnumeratorT< Type >* pEnum = pCol->GetEnumeratorN(); + TryCatch(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (true) + { + Type temp; + r = pEnum->MoveNext(); + + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + break; + } + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(temp); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = Remove(temp); + TryLog(r == E_SUCCESS, "[%s] Remove() failed.", GetErrorMessage(r)); + } + + if (null != pEnum) + { + delete pEnum; + } + return r; + +CATCH: + if (null != pEnum) + { + delete pEnum; + } + return r; + } + + /** + * Removes the object at the specified location. + * + * @since 2.0 + * + * @return An error code + * @param[in] index The index at which the object must be removed + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is equal to or greater than the number of elements or less than @c 0. + * @see InsertAt() + */ + virtual result RemoveAt(int index) + { + TryReturn(index < __count && index >= 0, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + RemoveNode(GetNode(index)); + return E_SUCCESS; + } + + /** + * Removes all elements within the specified range. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting index of the range + * @param[in] count The number of elements to read + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is outside the bounds of the data structure. @n + * - The specified @c startIndex is either equal to or greater than the number of elements or less than @c 0. @n + * - The specified @c count is either greater than the number of elements starting from @c startIndex or less than @c 0. + * @see AddItems() + * @see InsertItemsFrom() + */ + virtual result RemoveItems(int startIndex, int count) + { + TryReturn(startIndex >= 0 && count >= 0, E_OUT_OF_RANGE, + "[%s] Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count); + TryReturn(startIndex < __count, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + TryReturn(count <= __count && (startIndex + count <= __count), E_OUT_OF_RANGE, + "[%s] The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, count, __count); + + if (count > 0) + { + __LinkedListNodeT< Type >* pNode = GetNode(startIndex); + for (int i = 0; i < count; i++) + { + if (pNode != null) + { + __LinkedListNodeT< Type >* pNextNode = pNode->pNext; + RemoveNode(pNode); + pNode = pNextNode; + } + } + } + return E_SUCCESS; + } + + /** + * Removes all the elements from this list. + * + * @since 2.0 + */ + virtual void RemoveAll(void) + { + if (__count > 0) + { + __modCount++; + __LinkedListNodeT< Type >* pNode = __pListHead; + __LinkedListNodeT< Type >* pTemp; + while (null != pNode) + { + pTemp = pNode->pNext; + delete pNode; + pNode = pTemp; + __count--; + } + __pListHead = null; + __pListTail = null; + } + } + + /** + * Sets the object at the specified index with the specified object. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj An object to set + * @param[in] index The index at which the object must be set + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is outside the bounds of the data structure, or + * the specified @c index is equal to or greater than the number of elements or less than @c 0. + * @see GetAt() + */ + virtual result SetAt(const Type& obj, int index) + { + TryReturn(index >= 0 && index < __count, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, less than the number of elements(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + __modCount++; + __LinkedListNodeT< Type >* pNode = GetNode(index); + if (pNode != null) + { + pNode->pObj = obj; + } + + return E_SUCCESS; + } + + /** + * Sorts the elements of this list using the comparer provided. + * + * @since 2.0 + * + * @return An error code + * @param[in] comparer The IComparerT implementation to use when comparing the elements + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c comparer is not valid. + */ + virtual result Sort(const IComparerT< Type >& comparer) + { + if (0 == __count) + { + return E_SUCCESS; + } + + result r = QuickSort(0, (__count - 1), comparer); + if (r != E_SUCCESS) + { + AppLogException("[%s] Propagating.", GetErrorMessage(r)); + } + + return r; + } + + /** + * Gets the number of objects currently stored in this list. + * + * @since 2.0 + * + * @return The number of objects currently stored in this list + */ + virtual int GetCount(void) const + { + return __count; + } + + /** + * Checks whether the list contains the specified object. + * + * @since 2.0 + * + * @return @c true if the list contains the specified object, @n + * else @c false + * @param[in] obj The object to locate + * @see ContainsAll() + */ + virtual bool Contains(const Type& obj) const + { + if (__count == 0) + { + return false; + } + + __LinkedListNodeT< Type >* pNode = GetNode(0); + for (int i = 0; i < __count; i++) + { + if (pNode != null) + { + if (obj == pNode->pObj) + { + return true; + } + pNode = pNode->pNext; + } + } + + return false; + } + + /** + * Checks whether the list contains all the elements of the specified collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to check for containment in this list + * @param[out] out Set to @c true if this list contains all of the elements in the specified collection, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @remarks If the given @c collection is empty, the @c out parameter is set to @c true. + * @see Contains() + */ + virtual result ContainsAll(const ICollectionT< Type >& collection, bool& out) const + { + result r = E_SUCCESS; + out = false; + + if (collection.GetCount() == 0) + { + out = true; + return E_SUCCESS; + } + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + IEnumeratorT< Type >* pEnum = pCol->GetEnumeratorN(); + TryCatch(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (true) + { + Type temp; + + r = pEnum->MoveNext(); + + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + out = true; + break; + } + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(temp); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + if (false == Contains(temp)) + { + out = false; + break; + } + } + + if (null != pEnum) + { + delete pEnum; + } + return r; + +CATCH: + if (null != pEnum) + { + delete pEnum; + } + return r; + } + + /** + * Compares the given object with the calling LinkedList object. + * + * @since 2.0 + * + * @return @c true if the specified instance equals to the current instance, @n + * else @c false + * @param[in] obj The object to compare with the calling object + * @remarks This method returns @c true only if the specified object is also an instance of LinkedList class, + * both lists have the same size, and all corresponding pairs of elements in the two lists are equal. + * In other words, two lists are equal if they contain the same elements in the same order. + */ + virtual bool Equals(const Object& obj) const + { + bool out = true; + + const LinkedListT< Type >* other = dynamic_cast< const LinkedListT< Type >* >(&obj); + if (null == other) + { + out = false; + } + else if (other == this) + { + out = true; + } + else if (__count != other->__count) + { + out = false; + } + else + { + __LinkedListNodeT< Type >* pNode = __pListHead; + __LinkedListNodeT< Type >* pOtherNode = other->__pListHead; + for (int i = 0; i < __count; i++) + { + if (!(pNode->pObj == pOtherNode->pObj)) + { + out = false; + break; + } + pNode = pNode->pNext; + pOtherNode = pOtherNode->pNext; + } + } + + return out; + } + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const + { + int hash = 0; + if (__count > 0) + { + __LinkedListNodeT< Type >* pNode = __pListHead; + while (pNode != null) + { + hash += reinterpret_cast< int >(pNode); + pNode = pNode->pNext; + } + } + + return hash; + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] list The %LinkedListT object to initialize the new object + */ + LinkedListT(const LinkedListT< Type >& list); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] list An instance of %LinkedListT + */ + LinkedListT< Type >& operator =(const LinkedListT< Type >& list); + + /** + * Gets the node at the specified index. + * + * @return A node at the specified index + * @param[in] index The index of the node to read + */ + __LinkedListNodeT< Type >* GetNode(int index) const + { + if (index >= __count) + { + return null; + } + + __LinkedListNodeT< Type >* pNode = __pListHead; + for (int i = 0; i < index; i++) + { + pNode = pNode->pNext; + } + + return pNode; + } + + /** + * Inserts an object to the beginning of the %LinkedList. + * + * @return An error code + * @param[in] obj The object to insert + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SUCCESS The method is successful. + */ + result InsertFirst(const Type& obj) + { + result r = E_SUCCESS; + __LinkedListNodeT< Type >* pNode = new __LinkedListNodeT< Type >(obj); + TryCatch(pNode != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + __modCount++; + __count++; + if (null == __pListHead) + { + __pListHead = pNode; + __pListTail = pNode; + } + else + { + pNode->pNext = __pListHead; + __pListHead->pPrev = pNode; + __pListHead = pNode; + } + + return r; + +CATCH: + return r; + } + + /** + * Inserts an object to the end of the LinkedList. + * + * @return An error code + * @param[in] obj The object to insert + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SUCCESS The method is successful. + */ + result InsertLast(const Type& obj) + { + __LinkedListNodeT< Type >* pNode = InsertNext(__pListTail, obj); + if (pNode == null) + { + AppLogException("[%s] Propagating.", GetErrorMessage(GetLastResult())); + } + + return GetLastResult(); + } + + /** + * Inserts an object after the specified node. + * + * @return An error code + * @param[in] obj The object to insert + * @param[in] pPrevNode The node after which the object must be inserted + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SUCCESS The method is successful. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + __LinkedListNodeT< Type >* InsertNext(__LinkedListNodeT< Type >* pPrevNode, const Type& obj) + { + ClearLastResult(); + result r = E_SUCCESS; + __LinkedListNodeT< Type >* pNode = new __LinkedListNodeT< Type >(obj); + TryCatch(pNode != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + __modCount++; + __count++; + if (null == __pListHead) + { + __pListHead = pNode; + __pListTail = pNode; + } + else if (pPrevNode == __pListTail) + { + pNode->pPrev = __pListTail; + __pListTail->pNext = pNode; + __pListTail = pNode; + } + else + { + TryCatch(pPrevNode != null, r = E_INVALID_ARG, "[%s] The pPrevNode is null.", GetErrorMessage(E_INVALID_ARG)); + pNode->pPrev = pPrevNode; + pNode->pNext = pPrevNode->pNext; + pPrevNode->pNext->pPrev = pNode; + pPrevNode->pNext = pNode; + } + + return pNode; + +CATCH: + SetLastResult(r); + if (pNode != null) + { + delete pNode; + pNode = null; + } + + return pNode; + } + + /** + * Removes the specified node. + * + * @param[in] pNode The pointer of the node to remove + */ + void RemoveNode(__LinkedListNodeT< Type >* pNode) + { + AppAssertf((null != pNode), "pNode is null.\n"); + AppAssertf((__count > 0), "__count is zero.\n"); + + __modCount++; + __count--; + if (__count == 0) + { + __pListHead = null; + __pListTail = null; + } + else if (pNode == __pListHead) + { + __pListHead = pNode->pNext; + __pListHead->pPrev = null; + } + else if (pNode == __pListTail) + { + __pListTail = pNode->pPrev; + __pListTail->pNext = null; + } + else + { + pNode->pNext->pPrev = pNode->pPrev; + pNode->pPrev->pNext = pNode->pNext; + } + delete pNode; + } + + /** + * Sorts the specified sub-list within the calling instance. + * + * @param[in] startIndex The starting index of the sub-list to sort + * @param[in] endIndex The ending index of the sub-list to sort + * @param[in] pComparer The comparer function to sort the list + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or @n + * the comparer has failed to compare the elements. + */ + result QuickSort(int startIndex, int endIndex, const IComparerT< Type >& comparer) + { + result r = E_SUCCESS; + + if (startIndex < endIndex) + { + int middleIndex; + int i = startIndex - 1; + int j = endIndex + 1; + Type startObj = Type(); + __LinkedListNodeT< Type >* pNodeI = null; + __LinkedListNodeT< Type >* pNodeJ = null; + __LinkedListNodeT< Type >* pNode = GetNode(startIndex); + + if (pNode != null) + { + startObj = pNode->pObj; + } + + while (true) + { + int compareResult = 1; + while ((compareResult > 0) && (j > static_cast< int >(startIndex))) + { + j--; + pNodeJ = (null == pNodeJ) ? GetNode(j) : pNodeJ->pPrev; + if (pNodeJ != null) + { + r = comparer.Compare(pNodeJ->pObj, startObj, compareResult); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + } + + compareResult = -1; + while ((compareResult < 0) && (i < static_cast< int >(endIndex))) + { + i++; + pNodeI = (null == pNodeI) ? GetNode(i) : pNodeI->pNext; + if (pNodeI != null) + { + r = comparer.Compare(pNodeI->pObj, startObj, compareResult); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + } + + if (i < j) + { + if ((pNodeJ != null) && (pNodeI != null)) + { + Type temp = pNodeJ->pObj; + pNodeJ->pObj = pNodeI->pObj; + pNodeI->pObj = temp; + } + } + else + { + middleIndex = j; + break; + } + } + + r = QuickSort(startIndex, middleIndex, comparer); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = QuickSort(middleIndex + 1, endIndex, comparer); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; + } + + __LinkedListNodeT< Type >* __pListHead; + __LinkedListNodeT< Type >* __pListTail; + int __count; + int __modCount; + friend class __LinkedListEnumeratorT< Type >; + +}; // LinkedListT + +// +// @class __LinkedListNodeT +// @brief This is a node for LinkedListT. +// @since 2.0 +// +template< class Type > +class __LinkedListNodeT + : public Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + * + * @param[in] obj An object to include in this node + */ + __LinkedListNodeT(const Type& obj) + : pPrev(null) + , pNext(null) + , pObj(obj) + { + } + + /** + * Internal variable. + * + * @since 2.0 + */ + __LinkedListNodeT< Type >* pPrev; + + /** + * Internal variable. + * + * @since 2.0 + */ + __LinkedListNodeT< Type >* pNext; + + /** + * Internal variable. + * + * @since 2.0 + */ + Type pObj; + +}; // __LinkedListNodeT + +// +// @class __LinkedListEnumeratorT +// @brief This class is an implementation of IEnumeratorT for %LinkedListT. +// @since 2.0 +// +template< class Type > +class __LinkedListEnumeratorT + : public IBidirectionalEnumeratorT< Type > + , public Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + * + * @param[in] list A list to enumerate + * @param[in] modCount The modification count to detect the change in the list + */ + __LinkedListEnumeratorT(const LinkedListT< Type >& list, int modCount) + : __list(list) + , __pNode(null) + , __modCount(modCount) + { + + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__LinkedListEnumeratorT(void) + { + + } + + /** + * Gets the current object in the list. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The current object + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - This enumerator is currently positioned before the first element or + * past the last element. @n + - The list is modified after this enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + result GetCurrent(Type& obj) const + { + TryReturn(__modCount == __list.__modCount, E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn(__pNode != null, E_INVALID_OPERATION, + "[%s] Current position is before the first element or past the last element.", GetErrorMessage(E_INVALID_OPERATION)); + + obj = __pNode->pObj; + return E_SUCCESS; + } + + + /** + * Moves this enumerator to the next element of the list. @n + * When this enumerator is first created or after call to Reset(), + * the first call to MoveNext() positions this enumerator to the first element in the list. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the list is modified after this enumerator is created. + * @exception E_OUT_OF_RANGE The enumerator has passed the end of the list. + * @see Reset() + */ + result MoveNext(void) + { + TryReturn(__modCount == __list.__modCount, E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + if (null == __pNode) + { + __pNode = __list.__pListHead; + if (null == __pNode) + { + return E_OUT_OF_RANGE; + } + } + else + { + if (null != __pNode->pNext) + { + __pNode = __pNode->pNext; + } + else + { + return E_OUT_OF_RANGE; + } + } + + return E_SUCCESS; + } + + /** + * Positions this enumerator before the first elements in the list. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the list is modified after this enumerator is created. + */ + result Reset(void) + { + TryReturn(__modCount == __list.__modCount, E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __pNode = null; + return E_SUCCESS; + } + + result MovePrevious(void) + { + TryReturn(__modCount == __list.__modCount, E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + if (__pNode == null) + { + __pNode = __list.__pListTail; + if (__pNode == null) + { + return E_OUT_OF_RANGE; + } + } + else + { + if (__pNode->pPrev != null) + { + __pNode = __pNode->pPrev; + } + else + { + return E_OUT_OF_RANGE; + } + } + + return E_SUCCESS; + } + + result ResetLast(void) + { + return Reset(); + } + +private: + const LinkedListT< Type >& __list; + __LinkedListNodeT< Type >* __pNode; + int __modCount; + +}; // __LinkedListEnumeratorT + +}}} // Tizen::Base::Collection + +#endif // _FCOL_LINKED_LIST_T_H_ diff --git a/inc/FBaseColMapEntry.h b/inc/FBaseColMapEntry.h new file mode 100644 index 0000000..a1ecaee --- /dev/null +++ b/inc/FBaseColMapEntry.h @@ -0,0 +1,160 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColMapEntry.h + * @brief This is the header file for the %MapEntry class. + * + * This header file contains the declarations of the %MapEntry class. + */ +#ifndef _FCOL_MAP_ENTRY_H_ +#define _FCOL_MAP_ENTRY_H_ + +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class MapEntry + * @brief This class represents a key-value pair. + * + * @since 2.0 + * + * The %MapEntry class represents a key-value pair. + * + * For more information on the class features, see MapEntry. + */ +class _OSP_EXPORT_ MapEntry + : public Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @param[in] key The key + * @param[in] value The value + */ + MapEntry(const Object& key, const Object& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~MapEntry(void); + + /** + * Gets the key corresponding to this entry. + * + * @since 2.0 + * + * @return The key corresponding to this entry + * @see GetValue() + */ + virtual const Object* GetKey(void) const; + + /** + * Gets the value corresponding to this entry. + * + * @since 2.0 + * + * @return The value corresponding to this entry + * @see GetKey() + */ + virtual const Object* GetValue(void) const; + + /** + * Gets the key corresponding to this entry. + * + * @since 2.0 + * + * @return The key corresponding to this entry + * @see GetValue() + */ + virtual Object* GetKey(void); + + /** + * Gets the value corresponding to this entry. + * + * @since 2.0 + * + * @return The value corresponding to this entry + * @see GetKey() + */ + virtual Object* GetValue(void); + + /** + * Compares the value of the given Object to the + * value of the calling object. + * + * @since 2.0 + * + * @return @c true if the values are equal, @n + * else @c false + * @param[in] obj The object to compare with the calling object + * @remarks Returns @c false if the given object is not a %MapEntry object. + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + +protected: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + MapEntry(void); + Object* _pKey; + Object* _pValue; + +private: + /** + * This is the copy constructor for this class. + * + * @param[in] entry The instance of the MapEntry class to copy from + */ + MapEntry(const MapEntry& entry); + + /** + * Assigns the value of the specified instance to the current instance of %MapEntry. + * + * @param[in] entry An instance of %MapEntry + */ + MapEntry& operator =(const MapEntry& entry); + + friend class _MapEntryImpl; + class _MapEntryImpl* __pMapEntryImpl; + +}; // MapEntry + +}}} // Tizen::Collection + +#endif // _FCOL_MAP_ENTRY_H_ diff --git a/inc/FBaseColMapEntryT.h b/inc/FBaseColMapEntryT.h new file mode 100644 index 0000000..559714a --- /dev/null +++ b/inc/FBaseColMapEntryT.h @@ -0,0 +1,154 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColMapEntryT.h + * @brief This is the header file for the %MapEntryT class. + * + * This header file contains the declarations of the %MapEntryT class. + */ +#ifndef _FBASE_COL_MAP_ENTRY_T_H_ +#define _FBASE_COL_MAP_ENTRY_T_H_ + +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class MapEntryT + * @brief This class represents a template-based key-value pair. + * + * @since 2.0 + * + * The %MapEntryT class represents a template-based key-value pair. + * + * For more information on the class features, see MapEntry. + * + */ +template< class KeyType, class ValueType > +class MapEntryT + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + MapEntryT(void) + : __key(0) + , __val(0) + { + } + + /** + * Initializes this instance of %MapEntryT with the specified key-value pair. + * + * @since 2.0 + * + * @param[in] key The key for this mapping + * @param[in] value The value for this mapping + */ + MapEntryT(const KeyType& key, const ValueType& value) + : __key(key) + , __val(value) + { + + } + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~MapEntryT(void) + { + + } + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] entry An instance of %MapEntryT + */ + MapEntryT< KeyType, ValueType >& operator =(const MapEntryT< KeyType, ValueType >& entry) + { + if (&entry != this) + { + __key = entry.__key; + __val = entry.__val; + } + + return *this; + } + + /** + * Gets the key corresponding to this entry. + * + * @since 2.0 + * + * @return The key corresponding to this entry + * @see GetValue() + */ + virtual const KeyType& GetKey(void) const + { + return __key; + } + + /** + * Gets the value corresponding to this entry. + * + * @since 2.0 + * + * @return The value corresponding to this entry + * @see GetKey() + */ + virtual const ValueType& GetValue(void) const + { + return __val; + } + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const + { + int hash = 0; + hash += reinterpret_cast< int >(&__key); + hash += reinterpret_cast< int >(&__val); + return hash; + } + +private: + KeyType __key; + ValueType __val; + +}; // MapEntryT + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_MAP_ENTRY_T_H_ diff --git a/inc/FBaseColMultiHashMap.h b/inc/FBaseColMultiHashMap.h new file mode 100644 index 0000000..8a823a7 --- /dev/null +++ b/inc/FBaseColMultiHashMap.h @@ -0,0 +1,551 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColMultiHashMap.h + * @brief This is the header file for the %MultiHashMap class. + * + * This header file contains the declarations of the %MultiHashMap class. + */ +#ifndef _FBASE_COL_MULTI_HASH_MAP_H_ +#define _FBASE_COL_MULTI_HASH_MAP_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +class _MultiHashMapEntry; + +/** + * @class MultiHashMap + * @brief This class represents a collection of associated keys and values that are organized based on the hash code of the key. + * + * @since 2.0 + * + * The %MultiHashMap class represents a collection of associated keys and values that are organized based on the hash code of the key. + * There is no limit on the number of elements with the same key, but duplicated elements with the same key are not allowed. + * The key and value cannot be @c null. + * @n + * For more information on the class features, see HashMap and MultiHashMap. + * + * The following example demonstrates how to use the %MultiHashMap class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::MultiHashMapSample(void) + * { + * MultiHashMap map(SingleObjectDeleter); + * + * // Constructs a MultiHashMap instance with default values for capacity, load factor, hash code provider, and comparer + * map.Construct(); + * + * map.Add(new String(L"Zero"), new Integer(0)); // map.GetCount() : 1, map : (Zero -> 0) + * map.Add(new String(L"One"), new Integer(1)); // map.GetCount() : 2, map : (Zero -> 0), (one -> 1) + * map.Add(new String(L"Two"), new Integer(2)); // map.GetCount() : 3, map : (Zero -> 0), (one -> 1), (Two -> 2) + * map.Add(new String(L"Two"), new Integer(20)); // map.GetCount() : 4, map : (Zero -> 0), (One -> 1), (Two -> 2, 20) + * + * // Gets values with the specified key + * Integer* pValue = null; + * IEnumerator *pValueEnum = map.GetValuesN(String(L"Two")); + * while(pValueEnum->MoveNext() == E_SUCCESS) + * { + * pValue = static_cast (pValueEnum->GetCurrent()); + * } + * + * delete pValueEnum; + * + * // Removes values with the specified key // String(L"Two"), Integer(2), Integer(20) are removed + * map.Remove(String(L"Two")); + * + * // Uses an enumerator to access elements in the map + * IMapEnumerator* pMapEnum = map.GetMapEnumeratorN(); + * String* pKey = null; + * while (pMapEnum->MoveNext() == E_SUCCESS) + * { + * pKey = static_cast< String* > (pMapEnum->GetKey()); + * pValue = static_cast< Integer* > (pMapEnum->GetValue()); + * } + * + * delete pMapEnum; + * + * // Deallocates all objects + * // Because the destructor calls RemoveAll() internally, you don't need to call RemoveAll() to destroy all elements at the end. + * map.RemoveAll(); + * } + * @endcode + */ +class _OSP_EXPORT_ MultiHashMap + : public IMultiMap + , public Object +{ +public: + using IMultiMap::Add; + using IMultiMap::Remove; + using IMultiMap::RemoveAll; + using IMultiMap::SetValue; + using IMultiMap::Contains; + using IMultiMap::ContainsKey; + + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @param[in] deleter The function pointer to type of the element deleter + * @remarks To create an owing collection, set the element deleter value as @c SingleObjectDeleter. This gives the collection the ownership of elements and the collection will destroy elements. @n + * On the other hand, to create a non-owning collection, you don't need to set the element deleter value, as @c NoOpDeleter is the default element deleter. + * It means that you don't transfer the ownership of elements to the collection. + * @see NoOpDeleter() + * @see SingleObjectDeleter() + * @see ArrayDeleter() + */ + explicit MultiHashMap(DeleterFunctionType deleter = NoOpDeleter); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~MultiHashMap(void); + + /** + * Initializes a new instance of %MultiHashMap with the specified capacity and load factor. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity + * @param[in] loadFactor The maximum ratio of elements to buckets + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c capacity or the @c loadFactor is negative. + * @remarks The GetHashCode() method of the key object is used for hashing and the + * Equals() method of the key object is used for comparing the keys. + * @see MultiHashMap() + */ + result Construct(int capacity = 16, float loadFactor = 0.75); + + /** + * Initializes a new instance of %MultiHashMap by copying the elements of the given map. + * + * @since 2.0 + * + * @return An error code + * @param[in] map The map to copy + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor(0.75) is used. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c loadFactor is negative. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c map is modified during the operation of this method. + * @remarks This method performs a shallow copy. It copies just the pointer; not the element itself. + * @see MultiHashMap() + */ + result Construct(const IMultiMap& map, float loadFactor = 0.75); + + + /** + * Initializes a new instance of the %MultiHashMap class, with the specified initial capacity, load factor, hash code provider, and comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity @n + * If it is @c 0, the default capacity (16) is used. + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor (0.75) is used. + * @param[in] provider An instance of the IHashCodeProvider derived class that supplies the hash codes + * for all keys in this map + * @param[in] comparer An instance of the IComparer derived class to use when comparing keys + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c capacity or the @c loadFactor is negative. + * @remarks The instances of hash code provider and comparer will not be deallocated later from this map. + * @see MultiHashMap() + */ + result Construct(int capacity, float loadFactor, const IHashCodeProvider& provider, const IComparer& comparer); + + /** + * Initializes a new instance of the %MultiHashMap class by copying the elements of the specified map, + * with the specified load factor, hash code provider, and comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] map A map to copy + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor (0.75) is used. + * @param[in] provider An instance of the IHashCodeProvider derived class that supplies the hash codes + * for all keys in this map + * @param[in] comparer An instance of the IComparer derived class to use when comparing keys + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c loadFactor is negative. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c map is modified during the operation of this method. + * @remarks This method performs a shallow copy. It copies just the pointer; not the element itself. + * The instances of hash code provider and comparer will not be deallocated later from this map. + * @see MultiHashMap() + */ + result Construct(const IMultiMap& map, float loadFactor, const IHashCodeProvider& provider, const IComparer& comparer); + + /** + * Adds the specified key-value pair to this map. + * + * @since 2.0 + * + * @return An error code + * @param[in] pKey The pointer to key to add + * @param[in] pValue The pointer to corresponding value to add + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_ALREADY_EXIST The specified pair of @c pKey and @c pValue already exists. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks This method performs a shallow copy. It adds just the pointer; not the element itself. + * @see Remove() + */ + virtual result Add(Object* pKey, Object* pValue); + + /** + * Gets an enumerator of this map. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IEnumerator derived class) of this map, @n + * else @c null if some exception occurs + * @remarks If the key has multiple values, the enumeration proceeds as follows: {A: a}, {B: b}, {B: c}, {B, d}, {C: e}, ... + * The specific error code can be accessed using the GetLastResult() method. + * @see IEnumerator() + * @see IMapEnumerator() + */ + virtual IEnumerator* GetEnumeratorN(void) const; + + /** + * Gets an enumerator of this map. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IMapEnumerator derived class) of this map, @n + * else @c null if some exception occurs + * @remarks If the key has multiple values, the enumeration proceeds as follows: {A: a}, {B: b}, {B: c}, {B, d}, {C: e}, ... + * The specific error code can be accessed using the GetLastResult() method. + * @see IEnumerator() + * @see IMapEnumerator() + */ + virtual IMapEnumerator* GetMapEnumeratorN(void) const; + + /** + * Gets an enumerator of the values associated with the specified key. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IEnumerator derived class) of the values associated with the specified key, @n + * else @c null if some exception occurs + * @param[in] key A key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetValue() + */ + virtual IEnumerator* GetValuesN(const Object& key) const; + + /** + * Gets a list of all the keys in this map. + * + * @since 2.0 + * + * @return A list of all the keys in this map + * @remarks The order of the keys is the same as the corresponding values in the IList interface returned by the GetValuesN() method. + * The %IList stores just the pointers to the elements in the map, not the elements themselves. + * The specific error code can be accessed using the GetLastResult() method. + * @see GetValuesN() + */ + virtual IList* GetKeysN(void) const; + + /** + * Gets a list of all the values in this map. + * + * @since 2.0 + * + * @return A list of all the values in this map + * @remarks The IList stores just the pointers to the elements in the map, not the elements themselves. + * The specific error code can be accessed using the GetLastResult() method. + * @see GetKeysN() + */ + virtual IList* GetValuesN(void) const; + + /** + * Removes all the values with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see Add() + */ + virtual result Remove(const Object& key); + + /** + * Removes the specified value associated with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key whose mapping is to remove from the map + * @param[in] value The value to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key and @c value pair is not found in the map. + * @remarks The specified key is also removed if there are no more values associated with it. + * @see Add() + */ + virtual result Remove(const Object& key, const Object& value); + + /** + * Removes all the object pointers in the @c collection. @n + * + * @since 2.0 + * + * @remarks This method can be called before deleting @c collection. + */ + virtual void RemoveAll(void); + + /** + * Sets the value associated with the given key with a new value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key for which the associated value needs to replace + * @param[in] value The value to replace + * @param[in] pNewValue The pointer to new value to replace the existing value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key and @c value pair is not found in the map. + * @remarks To add a new key-value pair, use the Add() method. + * @see Add() + * @see GetValuesN() + */ + virtual result SetValue(const Object& key, const Object& value, Object* pNewValue); + + /** + * Gets the number of values currently stored in this map. + * + * @since 2.0 + * + * @return The number of values currently stored in this map + */ + virtual int GetCount(void) const; + + /** + * Gets the number of values whose key matches the key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key to locate + * @param[out] count The number of values whose key is the @c key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + */ + virtual result GetCount(const Object& key, int& count) const; + + /** + * Checks whether the map contains the specified key and value. + * + * @since 2.0 + * + * @return @c true if the map contains the specified key and value pair, @n + * else @c false + * @param[in] key The key to locate + * @param[in] value The value to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see ContainsKey() + * @see ContainsValue() + */ + virtual bool Contains(const Object& key, const Object& value) const; + + /** + * Checks whether the map contains the specified key. + * + * @since 2.0 + * + * @return @c true if the map contains the specified key, @n + * else @c false + * @param[in] key The key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see ContainsValue() + * @see Contains() + */ + virtual bool ContainsKey(const Object& key) const; + + /** + * Checks whether the map contains the specified value. + * + * @since 2.0 + * + * @return @c true if the map contains the specified value, @n + * else @c false + * @param[in] value The value to locate + * + * @see ContainsKey() + * @see Contains() + */ + virtual bool ContainsValue(const Object& value) const; + + /** + * Compares the specified instance to the current instance for equality. + * + * @since 2.0 + * + * @return @c true if the two instances are equal, @n + * @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true only if the specified object is also an instance of %MultiHashMap class, + * both maps have the same number of elements, and both maps contain the same elements. + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the element deleter of the collection. + * + * @since 2.0 + * + * @return An function pointer to the existing element deleter + */ + virtual DeleterFunctionType GetDeleter(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] map An instance of %MultiHashMap to initialize the current instance + */ + MultiHashMap(const MultiHashMap& map); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] map An instance of %MultiHashMap + */ + MultiHashMap& operator =(const MultiHashMap& map); + + /** + * Copies all the pairs from the specified map to this map. + * + * @return An error code + * @param[in] map The map to copy + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * The @c map is modified during the operation of this method. + */ + result AddAll(const IMultiMap& map); + + /** + * Gets a hash value for the specified object. + * + * @return An @c int hash value for the specified object + * @param[in] obj The object to get hash value + */ + int Hash(const Object& obj) const; + + /** + * Rehashes the contents of this map into a new array with a + * larger capacity.@n + * This method is called automatically when the number of keys in this map reaches its threshold. + * + * @return An error code + * @param[in] newCapacity The new capacity @n + * It must be a power of two and be greater than current capacity. + * @exception E_SUCCESS The method is successful. + */ + result Resize(int newCapacity); + + /** + * Clears all key-value pairs in this map. + */ + void Reset(void); + + /** + * Sets the element deleter of the collection. + * + * @since 2.0 + * + * @param[in] deleter An function pointer to the element deleter to set + */ + virtual void SetDeleter(DeleterFunctionType deleter); + + _MultiHashMapEntry** __pTable; + int __count; + int __capacity; + float __loadFactor; + int __threshold; + IHashCodeProvider* __pProvider; + IComparer* __pComparer; + bool __needToRemoveProviderComparer; + int __modCount; + DeleterFunctionType __deleter; + static const int DEFAULT_CAPACITY = 16; + static const float DEFAULT_LOAD_FACTOR; + + friend class _MultiHashMapEnumerator; + friend class _MultiHashMapImpl; + class _MultiHashMapImpl* __pMultiHashMapImpl; + +}; // MultiHashMap + +}}} // Tizen::Base::Collection + +#endif //_FBASE_COL_MULTI_HASH_MAP_H_ diff --git a/inc/FBaseColMultiHashMapT.h b/inc/FBaseColMultiHashMapT.h new file mode 100644 index 0000000..b0d26ab --- /dev/null +++ b/inc/FBaseColMultiHashMapT.h @@ -0,0 +1,1856 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColMultiHashMapT.h + * @brief This is the header file for the %MultiHashMapT class. + * + * This header file contains the declarations of the %MultiHashMapT class. + */ +#ifndef _FBASE_COL_MULTI_HASH_MAP_T_H_ +#define _FBASE_COL_MULTI_HASH_MAP_T_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +template< class KeyType, class ValueType > class __MultiHashMapEntryT; +template< class KeyType, class ValueType > class __MultiHashMapEnumeratorT; +template< class KeyType, class ValueType > class __EntryValueEnumeratorT; +template< class KeyType > class __MultiHashMapDefaultProviderT; + +template< class ValueType > class __ValueNodeT; + +/** + * @class MultiHashMapT + * @brief This class represents a template-based collection of associated keys and values that are organized based on the hash code of the key. + * + * @since 2.0 + * + * The %MultiHashMapT class represents a template-based collection of associated keys and values that are organized based on the hash code of the key. + * There is no limit on the number of elements with the same key, but duplicated elements with the same key are not allowed. + * The key and value cannot be null. Several methods in the %MultiHashMapT class need an assignment(=) operator of KeyType, and assignment(=) and equivalent(==) operators of ValueType. + * @n + * For more information on the class features, see HashMap and MultiHashMap. + * + * The following example demonstrates how to use the %MultiHashMapT class. + + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::MultiHashMapTSample(void) + * { + * MultiHashMapT map; + * + * // Constructs a MultiHashMap instance with default capacity, load factor, hash code provider, and comparer + * map.Construct(); + * + * int key; + * int value; + * + * map.Add(1, 1000); // map.GetCount() : 1, map : (1 -> 1000) + * map.Add(2, 2000); // map.GetCount() : 2, map : (1 -> 1000), (2 -> 2000) + * map.Add(3, 3000); // map.GetCount() : 3, map : (1 -> 1000), (2 -> 2000), (3 -> 3000) + * map.Add(3, 30); // map.GetCount() : 4, map : (1 -> 1000), (2 -> 2000), (3 -> 3000, 30) + * + * // Gets values with the specified key + * key = 1; + * IEnumeratorT* pValueEnum = map.GetValuesN(key); + * while (pValueEnum->MoveNext() == E_SUCCESS) + * { + * pValueEnum->GetCurrent(value); + * } + * + * delete pValueEnum; + * + * // Removes the values with the specified key + * key = 3; + * map.Remove(key); // 30, 3000 removed + * + * // Uses an enumerator to access elements in the map + * IMapEnumeratorT* pMapEnum = map.GetMapEnumeratorN(); + * while (pMapEnum->MoveNext() == E_SUCCESS) + * { + * pMapEnum->GetKey(key); + * pMapEnum->GetValue(value); + * } + * + * delete pMapEnum; + * } + * + * @endcode + */ +template< class KeyType, class ValueType > +class MultiHashMapT + : public IMultiMapT< KeyType, ValueType > + , public Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + MultiHashMapT(void) + : __pTable(null) + , __count(0) + , __capacity(0) + , __loadFactor(0) + , __threshold(0) + , __pProvider(null) + , __pComparer(null) + , __defaultConstruct(false) + , __modCount(0) + { + } + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~MultiHashMapT(void) + { + if (null != __pTable) + { + Reset(); + delete[] __pTable; + } + + if (__defaultConstruct) + { + delete __pProvider; + delete __pComparer; + } + + } + + /** + * Initializes this instance of %MultiHashMapT with the given capacity and load factor. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity + * @param[in] loadFactor The maximum ratio of elements to buckets + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c capacity or the @c loadFactor is negative. + * @remarks The key type must be a primitive data type. + * @see MultiHashMapT() + */ + result Construct(int capacity = 16, float loadFactor = 0.75) + { + TryReturn(capacity >= 0, E_INVALID_ARG, "[%s] The capacity(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), capacity); + TryReturn(loadFactor >= 0, E_INVALID_ARG, "[%s] The loadFactor(%f) MUST be greater than or equal to 0.0.", GetErrorMessage(E_INVALID_ARG), loadFactor); + + result r = E_SUCCESS; + + // set capacity + if (capacity == 0) + { + __capacity = DEFAULT_CAPACITY; + } + else + { + __capacity = 1; + while (__capacity < capacity) + { + __capacity <<= 1; + } + } + + // set load factor + if (Float::Compare(loadFactor, 0) == 0) + { + __loadFactor = DEFAULT_LOAD_FACTOR; + } + else + { + __loadFactor = loadFactor; + } + + // set threshold + __threshold = static_cast< int >(__capacity * __loadFactor); + + // set hash code provider + __pProvider = new __MultiHashMapDefaultProviderT< KeyType >(); + TryCatch(__pProvider != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + // set comparer + __pComparer = new Tizen::Base::ComparerT< KeyType >(); + TryCatch(__pComparer != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + __defaultConstruct = true; + + __pTable = new __MultiHashMapEntryT< KeyType, ValueType >*[__capacity]; + TryCatch(__pTable != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(__pTable, null, sizeof(__MultiHashMapEntryT< KeyType, ValueType >*) * __capacity); + + return r; + +CATCH: + __capacity = 0; + delete __pProvider; + delete __pComparer; + + return r; + } + + /** + * Initializes this instance of %MultiHashMapT by copying the elements of the specified map. + * + * @since 2.0 + * + * @return An error code + * @param[in] map A map to copy + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor(0.75) is used. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c loadFactor is negative. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c map is modified during the operation of this method. + * @see MultiHashMapT() + */ + result Construct(const IMultiMapT< KeyType, ValueType >& map, float loadFactor = 0.75) + { + TryReturn((loadFactor >= 0), E_INVALID_ARG, "[%s] The loadFactor(%f) MUST be greater than or equal to 0.0.", GetErrorMessage(E_INVALID_ARG), loadFactor); + + result r = E_SUCCESS; + + if (Float::Compare(loadFactor, 0) == 0) + { + loadFactor = DEFAULT_LOAD_FACTOR; + } + + int capacity = static_cast< int >(map.GetCount() / loadFactor) + 1; + r = Construct(capacity, loadFactor); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = AddAll(map); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + return r; + +CATCH: + Reset(); + delete[] __pTable; + __pTable = null; + + __capacity = 0; + + __pProvider = null; + delete __pProvider; + + __pComparer = null; + delete __pComparer; + + return r; + } + + /** + * Initializes this instance of %MultiHashMapT that is empty, + * with the specified initial capacity, load factor, hash code provider, and comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The initial capacity @n + * If it is @c 0, the default capacity(16) is used. + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor(0.75) is used. + * @param[in] provider An instance of the IHashCodeProvider derived class that supplies the hash codes + * for all keys in this map + * @param[in] comparer An instance of the IComparer derived class to use when comparing keys + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c capacity or the @c loadFactor is negative. + * @remarks The instances of hash code provider and comparer will not be deallocated later from this map. + * @see MultiHashMapT() + */ + result Construct(int capacity, float loadFactor, const IHashCodeProviderT< KeyType >& provider, + const IComparerT< KeyType >& comparer) + { + TryReturn(capacity >= 0, E_INVALID_ARG, "[%s] The capacity(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), capacity); + TryReturn(loadFactor >= 0, E_INVALID_ARG, "[%s] The loadFactor(%f) MUST be greater than or equal to 0.0.", GetErrorMessage(E_INVALID_ARG), loadFactor); + + result r = E_SUCCESS; + // set capacity + if (capacity == 0) + { + __capacity = DEFAULT_CAPACITY; + } + else + { + __capacity = 1; + while (__capacity < capacity) + { + __capacity <<= 1; + } + } + + // set load factor + if (Float::Compare(loadFactor, 0) == 0) + { + __loadFactor = DEFAULT_LOAD_FACTOR; + } + else + { + __loadFactor = loadFactor; + } + + // set threshold + __threshold = static_cast< int >(__capacity * __loadFactor); + + // set hash code provider + __pProvider = const_cast< IHashCodeProviderT< KeyType >* >(&provider); + + // set comparer + __pComparer = const_cast< IComparerT< KeyType >* >(&comparer); + + __pTable = new __MultiHashMapEntryT< KeyType, ValueType >*[__capacity]; + TryCatch(__pTable != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(__pTable, null, sizeof(__MultiHashMapEntryT< KeyType, ValueType >*) * __capacity); + + return r; + +CATCH: + __capacity = 0; + __pProvider = null; + __pComparer = null; + + return r; + } + + /** + * Initializes this instance of %MultiHashMapT by copying the elements of the specified map, + * with the specified load factor, hash code provider, and comparer. + * + * @since 2.0 + * + * @return An error code + * @param[in] map A map to copy + * @param[in] loadFactor The maximum ratio of elements to buckets @n + * If it is @c 0, the default load factor(0.75) is used. + * @param[in] provider An instance of the IHashCodeProvider derived class that supplies the hash codes + * for all keys in this map + * @param[in] comparer An instance of the IComparer derived class to use when comparing keys + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c loadFactor is negative. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c map is modified during the operation of this method. + * @remarks The instances of hash code provider and comparer will not be deallocated later from this map. + * @see MultiHashMapT() + */ + result Construct(const IMultiMapT< KeyType, ValueType >& map, float loadFactor, const IHashCodeProviderT< KeyType >& provider, + const IComparerT< KeyType >& comparer) + { + TryReturn(loadFactor >= 0, E_INVALID_ARG, "[%s] The loadFactor(%f) MUST be greater than or equal to 0.0.", GetErrorMessage(E_INVALID_ARG), loadFactor); + + result r = E_SUCCESS; + + if (Float::Compare(loadFactor, 0) == 0) + { + loadFactor = DEFAULT_LOAD_FACTOR; + } + + int capacity = static_cast< int >(map.GetCount() / loadFactor) + 1; + + r = Construct(capacity, loadFactor, provider, comparer); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = AddAll(map); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + return r; + +CATCH: + Reset(); + delete[] __pTable; + __pTable = null; + + __capacity = 0; + __pProvider = null; + __pComparer = null; + + return r; + } + + /** + * Adds the specified key-value pair to this map. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key of the value to add + * @param[in] value A value to add + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_ALREADY_EXIST The specified pair of @c key and @c value already exists. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @remarks SetItem() can be used to set value to a key that does not already exist. + * However, setting a value to a key that already exists overwrites the value. + * @see Remove() + * @see SetValue() + */ + virtual result Add(const KeyType& key, const ValueType& value) + { + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + __ValueNodeT< ValueType >* pNode = null; + __MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; + while (null != pEntry) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (cmpResult == 0) + { + pNode = pEntry->pList; + while (true) + { + if (pNode->value == value) + { + return E_OBJ_ALREADY_EXIST; + } + + if (pNode->pNext != null) + { + pNode = pNode->pNext; + } + else + { + pEntry->modCount++; + break; + } + } + break; + } + } + pEntry = pEntry->pNext; + } + + __ValueNodeT< ValueType >* pNewNode = new __ValueNodeT< ValueType >(value); + TryReturn(pNewNode != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + // key is not exist in this map. + if (pEntry == null) + { + __MultiHashMapEntryT< KeyType, ValueType >* pNewEntry = new __MultiHashMapEntryT< KeyType, ValueType >(key, pNewNode, __pTable[i], + hash); + TryReturn(pNewEntry != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + __pTable[i] = pNewEntry; + } + // key is already exist in this map, but value is not. + else + { + // pNode is the last value associated to the key + pNode->pNext = pNewNode; + } + + __modCount++; + + if (__count++ >= __threshold) + { + r = Resize(__capacity * 2); + TryReturn(r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return E_SUCCESS; + } + + /** + * Gets an enumerator of this map. + * + * @since 2.0 + * + * @return An enumerator (an instance of the %IMapEnumeratorT derived class) of this map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks If the key has multiple values, the Enumeration proceeds as follows: {A: a}, {B: b}, {B: c}, {B, d}, {C: e}, ... + * The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * @see Tizen::Base::Collection::IMapEnumerator + */ + virtual IEnumeratorT< MapEntryT< KeyType, ValueType > >* GetEnumeratorN(void) const + { + result r = E_SUCCESS; + + __MultiHashMapEnumeratorT< KeyType, ValueType >* pEnum = new __MultiHashMapEnumeratorT< KeyType, ValueType >(*this, __modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Gets an IMapEnumerator of this map. + * + * @since 2.0 + * + * @return An enumerator (an instance of the %IMapEnumeratorT derived class) of this map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks If the key has multiple values, the Enumeration proceeds like this: {A: a}, {B: b}, {B: c}, {B, d}, {C: e}, ... + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumerator + * @see Tizen::Base::Collection::IMapEnumerator + */ + virtual IMapEnumeratorT< KeyType, ValueType >* GetMapEnumeratorN(void) const + { + return dynamic_cast< IMapEnumeratorT< KeyType, ValueType >* >(GetEnumeratorN()); + } + + /** + * Gets an enumerator of the values associated with the specified key. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IEnumeratorT derived class) of the values associated with the specified key, @n + * else @c null if an exception occurs + * @param[in] key A key to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see SetValue() + */ + virtual IEnumeratorT< ValueType >* GetValuesN(const KeyType& key) const + { + result r = E_OBJ_NOT_FOUND; + + int hash = Hash(key); + int i = hash & (__capacity - 1); + IEnumeratorT< ValueType >* pEnum = null; + + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryCatch(r == E_SUCCESS, r = E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (0 == cmpResult) + { + pEnum = new __EntryValueEnumeratorT< KeyType, ValueType >(*pEntry, pEntry->modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + r = E_SUCCESS; + break; + } + + r = E_OBJ_NOT_FOUND; + } + } + + SetLastResult(r); + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Gets a list of all the keys in this map. + * + * @since 2.0 + * + * @return A list of all the keys in this map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The order of the keys is the same as the corresponding values in the IListT interface returned by the GetValuesN() method. + * The specific error code can be accessed using the GetLastResult() method. + * @see GetValuesN() + */ + virtual IListT< KeyType >* GetKeysN(void) const + { + ClearLastResult(); + + result r = E_SUCCESS; + int keyCount = 0; + + ArrayListT< KeyType >* pList = new ArrayListT< KeyType >(); + r = pList->Construct(__count); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < __capacity; i++) + { + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + r = pList->Add(pEntry->key); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + keyCount++; + } + } + + return pList; + +CATCH: + delete pList; + + SetLastResult(r); + return null; + } + + /** + * Gets a list of all the values in this map. + * + * @since 2.0 + * + * @return A list of all the values in this map, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetKeysN() + */ + virtual IListT< ValueType >* GetValuesN(void) const + { + ClearLastResult(); + + result r = E_SUCCESS; + + ArrayListT< ValueType >* pList = new ArrayListT< ValueType >(); + r = pList->Construct(__count); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < __capacity; i++) + { + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + for (__ValueNodeT< ValueType >* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + r = pList->Add(pNode->value); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + } + } + + return pList; + +CATCH: + delete pList; + + SetLastResult(r); + return null; + } + + /** + * Removes all the values for the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + * @see Add() + */ + virtual result Remove(const KeyType& key) + { + result r = E_OBJ_NOT_FOUND; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + __MultiHashMapEntryT< KeyType, ValueType >* pPrev = __pTable[i]; + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + r = E_OBJ_NOT_FOUND; + + if (cmpResult == 0) + { + __modCount++; + if (pPrev == pEntry) + { + __pTable[i] = pEntry->pNext; + } + else + { + pPrev->pNext = pEntry->pNext; + } + + __ValueNodeT< ValueType >* pNode = pEntry->pList; + while (null != pNode) + { + __ValueNodeT< ValueType >* pTemp = pNode; + pNode = pNode->pNext; + delete pTemp; + __count--; + } + delete pEntry; + r = E_SUCCESS; + break; + } + } + pPrev = pEntry; + } + + return r; + } + + /** + * Removes the specified value associated with the specified key. @n + * The key is also removed if there is no value associated with it. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key whose mapping is to remove from the map + * @param[in] value The value to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key and @c value pair is not found in the map. + * @see Add() + */ + virtual result Remove(const KeyType& key, const ValueType& value) + { + result r = E_OBJ_NOT_FOUND; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + __MultiHashMapEntryT< KeyType, ValueType >* pPrev = __pTable[i]; + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + r = E_OBJ_NOT_FOUND; + if (cmpResult == 0) + { + __ValueNodeT< ValueType >* pPrevNode = pEntry->pList; + for (__ValueNodeT< ValueType >* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + if (value == pNode->value) + { + __modCount++; + __count--; + if (pPrevNode == pNode) + { + pEntry->pList = pNode->pNext; + } + else + { + pPrevNode->pNext = pNode->pNext; + } + + delete pNode; + + pEntry->modCount++; + + if (null == pEntry->pList) + { + if (pPrev == pEntry) + { + __pTable[i] = pEntry->pNext; + } + else + { + pPrev->pNext = pEntry->pNext; + } + delete pEntry; + } + r = E_SUCCESS; + break; + } + pPrevNode = pNode; + } + if (!IsFailed(r)) + { + break; + } + } + } + pPrev = pEntry; + } + + return r; + } + + /** + * Removes all key-value pairs in this map. + * + * @since 2.0 + */ + virtual void RemoveAll(void) + { + if (__count > 0) + { + __modCount++; + Reset(); + __count = 0; + } + } + + /** + * Replaces the value associated with the key with the specified @c newValue. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key + * @param[in] value A value to replace + * @param[in] newValue A new value to replace the existing value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key and @c value pair is not found in the map. + * @remarks To add a new key-value pair, use the Add() method. + * @see Add() + * @see GetValuesN() + */ + virtual result SetValue(const KeyType& key, const ValueType& value, const ValueType& newValue) + { + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + __ValueNodeT< ValueType >* pNode = null; + bool pairExist = false; + __MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; + while (null != pEntry) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (cmpResult == 0) + { + pNode = pEntry->pList; + while (true) + { + if (pNode->value == value) + { + __modCount++; + pNode->value = newValue; + pairExist = true; + break; + } + if (pNode->pNext != null) + { + pNode = pNode->pNext; + } + else + { + pEntry->modCount++; + break; + } + } + break; + } + } + pEntry = pEntry->pNext; + } + + if (!pairExist) + { + r = E_OBJ_NOT_FOUND; + } + + return r; + } + + /** + * Gets the number of values currently stored in this map. + * + * @since 2.0 + * + * @return The number of values currently stored in this map + */ + virtual int GetCount(void) const + { + return __count; + } + + /** + * Gets the number of values whose keys match the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key A key to locate + * @param[out] count The number of values whose key is @c key + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found in the map. + */ + virtual result GetCount(const KeyType& key, int& count) const + { + result r = E_OBJ_NOT_FOUND; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (0 == cmpResult) + { + int __count = 0; + for (__ValueNodeT< ValueType >* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + __count++; + } + count = __count; + r = E_SUCCESS; + break; + } + + r = E_OBJ_NOT_FOUND; + } + } + + return r; + } + + /** + * Checks whether the map contains the specified key and value. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[in] value The value to locate + * @param[out] out Set to @c true if the map contains the specified key and value pair, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The current state of the instance prohibits the execution of the specified operation, or + * the comparer has failed to compare the keys. + * @see ContainsKey() + * @see ContainsValue() + */ + virtual result Contains(const KeyType& key, const ValueType& value, bool& out) const + { + out = false; + + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + if (IsFailed(r)) + { + AppLogException("[%s] Propagating.", GetErrorMessage(r)); + out = false; + return E_INVALID_ARG; + } + + if (cmpResult == 0) + { + for (__ValueNodeT< ValueType >* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + if (value == pNode->value) + { + r = E_SUCCESS; + out = true; + break; + } + } + break; + } + } + } + + return E_SUCCESS; + } + + /** + * Checks whether the map contains the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key to locate + * @param[out] out Set to @c true if the map contains the specified key, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the comparer has failed to compare the keys. + * @see ContainsValue() + * @see Contains() + */ + virtual result ContainsKey(const KeyType& key, bool& out) const + { + out = false; + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult; + r = __pComparer->Compare(key, pEntry->key, cmpResult); + if (IsFailed(r)) + { + AppLogException("[%s] Propagating.", GetErrorMessage(r)); + out = false; + return E_INVALID_ARG; + } + if (cmpResult == 0) + { + out = true; + break; + } + } + } + + return E_SUCCESS; + } + + /** + * Checks whether the map contains the specified value. + * + * @since 2.0 + * + * @return @c true if the map contains the specified value, @n + * else @c false + * @param[in] value The value to locate + * + * @see ContainsKey() + * @see Contains() + */ + virtual bool ContainsValue(const ValueType& value) const + { + bool out = false; + for (int i = 0; i < __capacity; i++) + { + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + for (__ValueNodeT< ValueType >* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + if (value == pNode->value) + { + out = true; + break; + } + } + + if (out) + break; + } + + if (out) + break; + } + + return out; + } + + /** + * Compares the specified instance to the current instance for equality. + * + * @since 2.0 + * + * @return @c true if the two instances are equal, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true only if the specified object is also an instance of the %MultiHashMapT class, + * both maps have the same number of elements, and both maps contain the same elements. + */ + virtual bool Equals(const Object& obj) const + { + result r = E_SUCCESS; + bool out = true; + + const MultiHashMapT< KeyType, ValueType >* other = dynamic_cast< const MultiHashMapT< KeyType, ValueType >* >(&obj); + if (null == other) // obj is not MultiHashMapT + { + out = false; + } + else if (other == this) + { + out = true; + } + else if (__count != other->__count) + { + out = false; + } + else + { + for (int i = 0; i < __capacity; i++) + { + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + for (__ValueNodeT< ValueType >* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + r = other->Contains(pEntry->key, pNode->value, out); + } + if (!out) + { + break; + } + } + if (!out) + { + break; + } + } + } + + return out; + } + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const + { + int hash = 0; + + for (int i = 0; i < __capacity; i++) + { + for (__MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + for (__ValueNodeT< ValueType >* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + hash += reinterpret_cast< int >(&pNode->value); + } + hash += reinterpret_cast< int >(&pEntry->key); + } + } + return hash; + } +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] map An instance of %MultiHashMapT to initialize the current instance + */ + MultiHashMapT(const MultiHashMapT< KeyType, ValueType >& map); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] map An instance of %MultiHashMapT + */ + MultiHashMapT< KeyType, ValueType >& operator =(const MultiHashMapT< KeyType, ValueType >& map); + + /** + * Copies all the pairs from the specified map to this map. + * + * @return An error code + * @param[in] map The map to copy + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation. @n + * The @c map is modified during the operation of this method. + */ + result AddAll(const IMultiMapT< KeyType, ValueType >& map) + { + result r = E_SUCCESS; + + IMultiMapT< KeyType, ValueType >* pMap = const_cast< IMultiMapT< KeyType, ValueType >* >(&map); + IMapEnumeratorT< KeyType, ValueType >* pMapEnum = pMap->GetMapEnumeratorN(); + + TryCatch(pMapEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (true) + { + KeyType key; + ValueType value; + + r = pMapEnum->MoveNext(); + // enumerator is reached to the end of collection + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + break; + } + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pMapEnum->GetKey(key); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pMapEnum->GetValue(value); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = Add(key, value); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + + if (null != pMapEnum) + { + delete pMapEnum; + } + return r; + +CATCH: + if (null != pMapEnum) + { + delete pMapEnum; + } + return r; + } + + /** + * Gets a hash value for the specified object. + * + * @return The hash value for the specified object + * @param[in] obj The object to get hash value + */ + int Hash(const KeyType& obj) const + { + int h = __pProvider->GetHashCode(obj); + + h ^= (h >> 20) ^ (h >> 12); + + return h ^ (h >> 7) ^ (h >> 4); + } + + /** + * Resizes the contents of this map into a new array with a + * larger capacity. @n + * This method is called automatically when the + * number of keys in this map reaches its threshold. + * + * @return An error code + * @param[in] newCapacity The new capacity @n + * It must be a power of 2 and must be greater than current capacity. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Resize(int newCapacity) + { + result r = E_SUCCESS; + __MultiHashMapEntryT< KeyType, ValueType >** newTable = new __MultiHashMapEntryT< KeyType, ValueType >*[newCapacity]; + TryCatch(newTable != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + for (int i = 0; i < newCapacity; i++) + { + newTable[i] = null; + } + + for (int i = 0; i < __capacity; i++) + { + __MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; + while (null != pEntry) + { + __MultiHashMapEntryT< KeyType, ValueType >* pNext = pEntry->pNext; + int i = pEntry->hash & (newCapacity - 1); + pEntry->pNext = newTable[i]; + newTable[i] = pEntry; + pEntry = pNext; + } + } + + delete[] __pTable; + __pTable = newTable; + __capacity = newCapacity; + __threshold = static_cast< int >(__capacity * __loadFactor); + + return r; + +CATCH: + return r; + } + + /** + * Clears all key-value pairs in this map. + * + */ + void Reset(void) + { + for (int i = 0; i < __capacity; i++) + { + __MultiHashMapEntryT< KeyType, ValueType >* pEntry = __pTable[i]; + while (null != pEntry) + { + __MultiHashMapEntryT< KeyType, ValueType >* pNext = pEntry->pNext; + __ValueNodeT< ValueType >* pNode = pEntry->pList; + while (null != pNode) + { + __ValueNodeT< ValueType >* pTemp = pNode; + pNode = pNode->pNext; + delete pTemp; + } + delete pEntry; + pEntry = pNext; + } + __pTable[i] = null; + } + } + + __MultiHashMapEntryT< KeyType, ValueType >** __pTable; + int __count; + int __capacity; + float __loadFactor; + int __threshold; + IHashCodeProviderT< KeyType >* __pProvider; + IComparerT< KeyType >* __pComparer; + bool __defaultConstruct; + int __modCount; + + static const int DEFAULT_CAPACITY = 16; + static const float DEFAULT_LOAD_FACTOR; + + friend class __MultiHashMapEnumeratorT< KeyType, ValueType >; + +}; // MultiHashMapT + +// +// @class __ValueNodeT +// @brief This class is a node for MultiHashMapT. +// @since 2.0 +// +template< class ValueType > +class __ValueNodeT + : public Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + * + * @param[in] v An object to include in this node + */ + __ValueNodeT(const ValueType& v) + : pNext(null) + , value(v) + { + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__ValueNodeT(void) + { + } + + /** + * Internal variable. + * + * @since 2.0 + */ + __ValueNodeT< ValueType >* pNext; + + /** + * Internal variable. + * + * @since 2.0 + */ + ValueType value; + +}; // __ValueNodeT + +// +// @class __MultiHashMapEntryT +// @brief This class is an entry for MultiHashMapT class. +// @since 2.0 +// +template< class KeyType, class ValueType > +class __MultiHashMapEntryT + : public Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + * + * @param[in] keyType A key to include in this entry + * @param[in] list A list of values whose key is specified @n + * It cannot be @c null. + * @param[in] next A pointer to the next entry + * @param[in] h An hash value of the key + */ + __MultiHashMapEntryT(const KeyType& keyType, __ValueNodeT< ValueType >* list, __MultiHashMapEntryT< KeyType, ValueType >* next, int h) + : key(keyType) + , pList(list) + , pNext(next) + , hash(h) + , modCount(0) + { + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__MultiHashMapEntryT(void) + { + } + + /** + * Internal variable. + * + * @since 2.0 + */ + KeyType key; + + /** + * Internal variable. + * + * @since 2.0 + */ + __ValueNodeT< ValueType >* pList; + + /** + * Internal variable. + * + * @since 2.0 + */ + __MultiHashMapEntryT< KeyType, ValueType >* pNext; + + /** + * Internal variable. + * + * @since 2.0 + */ + int hash; + + /** + * Internal variable. + * + * @since 2.0 + */ + int modCount; + + friend class __EntryValueEnumeratorT< KeyType, ValueType >; + +}; // __MultiHashMapEntryT + +// +// @class __MultiHashMapEnumeratorT +// @brief This class is an implementation of IMapEnumeratorT for %MultiHashMapT. +// @since 2.0 +// +template< class KeyType, class ValueType > +class __MultiHashMapEnumeratorT + : public IMapEnumeratorT< KeyType, ValueType > + , public Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + * + * @param[in] map A map to enumerate + * @param[in] modCount The modification count to detect the change in the map + */ + __MultiHashMapEnumeratorT(const MultiHashMapT< KeyType, ValueType >& map, int modCount) + : __map(map) + , __modCount(modCount) + , __pEntry(null) + , __pNode(null) + , __index(-1) + { + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__MultiHashMapEnumeratorT(void) + { + } + + /** + * Gets the current object in the map. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The current object + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - This enumerator is currently positioned before the first element or + * past the last element. @n + * - The map is modified after this enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + result GetCurrent(MapEntryT< KeyType, ValueType >& obj) const + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn((__pEntry != null && __pNode != null), E_INVALID_OPERATION, + "[%s] Invalid position(pEntry or pNode is null).", GetErrorMessage(E_INVALID_OPERATION)); + + obj = MapEntryT< KeyType, ValueType >(__pEntry->key, __pNode->value); + return E_SUCCESS; + } + + /** + * Moves this enumerator to the next element of the map. @n + * After the enumerator is first created or reset using the Reset() method, + * the first call to this method positions the enumerator to the first element in the @c collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the map is modified after this enumerator is created. + * @exception E_OUT_OF_RANGE The enumerator has passed the end of the map. + * @see Reset() + */ + result MoveNext(void) + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + result r = E_SUCCESS; + if ((null != __pNode) && (__pNode->pNext != null)) + { + __pNode = __pNode->pNext; + } + else if ((null != __pEntry) && (__pEntry->pNext != null)) + { + __pEntry = __pEntry->pNext; + __pNode = __pEntry->pList; + } + else + { + while (true) + { + if (++__index >= static_cast< int >(__map.__capacity)) + { + // Do not log the E_OUT_OF_RANGE, because it is normal or trivial in most cases. + r = E_OUT_OF_RANGE; + break; + } + __pEntry = __map.__pTable[__index]; + if (null != __pEntry) + { + __pNode = __pEntry->pList; + break; + } + } + } + + return r; + } + + /** + * Positions this enumerator before the first element in the map. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the map is modified after this enumerator is created. + */ + result Reset(void) + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __index = -1; + __pEntry = null; + __pNode = null; + return E_SUCCESS; + } + + /** + * Gets the current key in the map. + * + * @since 2.0 + * + * @return An error code + * @param[out] key The current key + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - This enumerator is currently positioned before the first element or + * past the last element. @n + * - The map is modified after this enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + result GetKey(KeyType& key) const + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn((__pEntry != null && __pNode != null), E_INVALID_OPERATION, + "[%s] Invalid position(pEntry or pNode is null).", GetErrorMessage(E_INVALID_OPERATION)); + + key = __pEntry->key; + return E_SUCCESS; + } + + /** + * Gets the current value in the map. + * + * @since 2.0 + * + * @return An error code + * @param[out] value The current value + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - This enumerator is currently positioned before the first element or + * past the last element. @n + * - The map is modified after the enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + result GetValue(ValueType& value) const + { + TryReturn((__modCount == __map.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn((__pEntry != null && __pNode != null), E_INVALID_OPERATION, + "[%s] Invalid position(pEntry or pNode is null).", GetErrorMessage(E_INVALID_OPERATION)); + + value = __pNode->value; + return E_SUCCESS; + } + +private: + const MultiHashMapT< KeyType, ValueType >& __map; + int __modCount; + __MultiHashMapEntryT< KeyType, ValueType >* __pEntry; + __ValueNodeT< ValueType >* __pNode; + int __index; + +}; // __MultiHashMapEnumeratorT + +// +// @class __EntryValueEnumeratorT +// @brief This class is an implementation of IEnumeratorT to enumerate values whose key is the same. +// @since 2.0 +// +template< class KeyType, class ValueType > +class __EntryValueEnumeratorT + : public IEnumeratorT< ValueType > + , public Object +{ +public: + /** + * Initializes an instance of __EntryValueEnumeratorT with the specified parameters. + * + * @since 2.0 + * + * @param[in] entry An entry to enumerate + * @param[in] modCount The modification count to detect the change in the entry + */ + __EntryValueEnumeratorT(const __MultiHashMapEntryT< KeyType, ValueType >& entry, int modCount) + : __entry(entry) + , __modCount(modCount) + , __pNode(null) + { + } + + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__EntryValueEnumeratorT(void) + { + } + + /** + * Gets the current value in the entry. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The current value + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - This enumerator is currently positioned before the first element or + * past the last element. @n + * - The entry is modified after this enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + result GetCurrent(ValueType& obj) const + { + TryReturn((__modCount == __entry.modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn(__pNode != null, E_INVALID_OPERATION, "[%s] Invalid position(pNode is null).", GetErrorMessage(E_INVALID_OPERATION)); + + obj = __pNode->value; + return E_SUCCESS; + } + + /** + * Moves this enumerator to the next element of the entry. @n + * After the enumerator is first created or reset using the Reset() method, + * the first call to this method positions the enumerator to the first element in the collection. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the entry is modified after this enumerator is created. + * @exception E_OUT_OF_RANGE The enumerator has passed the end of the entry. + * @see Reset() + */ + result MoveNext(void) + { + TryReturn((__modCount == __entry.modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + result r = E_SUCCESS; + if (null == __pNode) + { + __pNode = __entry.pList; + AppAssert(null != __pNode); + } + else if ((null != __pNode) && (__pNode->pNext != null)) + { + __pNode = __pNode->pNext; + } + else + { + // Do not log the E_OUT_OF_RANGE, because it is normal or trivial in most cases. + r = E_OUT_OF_RANGE; + } + + return r; + } + + /** + * Positions this enumerator before the first element in the entry. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the entry is modified after this enumerator is created. + */ + result Reset(void) + { + TryReturn((__modCount == __entry.modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __pNode = null; + return E_SUCCESS; + } + +private: + const __MultiHashMapEntryT< KeyType, ValueType >& __entry; + int __modCount; + __ValueNodeT< ValueType >* __pNode; + +}; // __EntryValueEnumeratorT + +// +// @class __MultiHashMapDefaultProviderT +// @brief This class is an implementation of IHashCodeProviderT for HashMap. +// @since 2.0 +// +template< class KeyType > +class __MultiHashMapDefaultProviderT + : public IHashCodeProviderT< KeyType > + , public Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + __MultiHashMapDefaultProviderT(void) {} + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__MultiHashMapDefaultProviderT(void) {} + + // Operation + + /** + * Gets the hash code of the specified instance. + * + * @since 2.0 + * + * @return The hash code + * @see Tizen::Base::Object::GetHashCode() + */ + virtual int GetHashCode(const KeyType& obj) const + { + return (int) obj; + } + +}; // __MultiHashMapDefaultProviderT + +template< class KeyType, class ValueType > +const float MultiHashMapT< KeyType, ValueType >::DEFAULT_LOAD_FACTOR = 0.75; + +}}} // Tizen::Base::Collection + +#endif //_FBASE_COL_MULTI_HASH_MAP_T_H_ diff --git a/inc/FBaseColQueue.h b/inc/FBaseColQueue.h new file mode 100644 index 0000000..36b5d5d --- /dev/null +++ b/inc/FBaseColQueue.h @@ -0,0 +1,336 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColQueue.h + * @brief This is the header file for the %Queue class. + * + * This header file contains the declarations of the %Queue class. + * + */ +#ifndef _FBASE_COL_QUEUE_H_ +#define _FBASE_COL_QUEUE_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ +/** + * @class Queue + * @brief This class represents a first-in-first-out collection of objects, that is, a queue. + * + * @since 2.0 + * + * The %Queue class represents a first-in-first-out collection of objects, that is, a queue. + * + * For more information on the class features, see Stack and Queue. + * + * The following example demonstrates how to use the %Queue class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::QueueSample(void) + * { + * Queue queue; + * queue.Construct(3); // capacity = 3 + * + * queue.Enqueue(new String(L"First")); + * queue.Enqueue(new String(L"Second")); + * queue.Enqueue(new String(L"Third")); + * + * // Reads the element at the beginning + * const Object* pObj = queue.Peek(); // pObj: "First", queue.GetCount(): 3 + * + * // Reads and removes the element at the beginning + * String* pStr = static_cast (queue.Dequeue()); // pStr: "First", queue.GetCount(): 2 + * + * delete pStr; // Because the queue does not have the Ownership of this pStr after dequeueing + * + * // Deallocates all objects + * queue.RemoveAll(true); + * } + * @endcode + */ +class _OSP_EXPORT_ Queue + : public virtual ICollection + , public Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + Queue(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Queue(void); + + /** + * Initializes an instance of %Queue with the specified capacity. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The number of elements in the queue @n + * The default capacity is @c 10. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the specified @c capacity is negative. + * @remarks If the number of elements added to the queue reaches the current capacity, + * the capacity is automatically increased by memory reallocation. + * Therefore, if the size of the queue can be estimated, + * specifying the initial capacity eliminates the need to perform a number of + * resizing operations while adding elements to the queue. + * @see Queue() + */ + result Construct(int capacity = DEFAULT_CAPACITY); + + /** + * Initializes an instance of %Queue with the elements of the given collection. @n + * The capacity of the queue is the same as the number of elements copied. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to copy elements from + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks This method performs a shallow copy. It copies just the pointer; not the element itself. + * @see Queue() + */ + result Construct(const ICollection& collection); + + /** + * Removes the element at the beginning of this queue and returns it. + * + * @since 2.0 + * + * @return The element at the beginning of this queue, @n + * else @c null if this queue is empty + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * this queue is empty. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Enqueue() + */ + virtual Object* Dequeue(void); + + /** + * @if OSPDEPREC + * Inserts an object at the end of this queue. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it has a problem of const reference argument. + * Instead of using this method, use Enqueue(Object* pObj). + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to add to this queue + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see Dequeue() + * @endif + */ + result Enqueue(const Object& obj) + { + return Enqueue(const_cast< Object* >(&obj)); + } + + /** + * Inserts an object at the end of this queue. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj The pointer to object to add to this queue + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @remarks This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see Dequeue() + */ + virtual result Enqueue(Object* pObj); + + /** + * Gets an enumerator of this queue. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IEnumerator derived class) of this queue, @n + * else @c null if an exception occurs + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see IEnumerator + */ + virtual IEnumerator* GetEnumeratorN(void) const; + + /** + * Gets the element at the front of this queue without removing it. + * + * @since 2.0 + * + * @return The element at the beginning of this queue, @n + * else @c null if this queue is empty + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * this queue is empty. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual const Object* Peek(void) const; + + /** + * Removes all objects and their pointers in collection, when the @c deallocate parameter is set to @c true. + * + * @since 2.0 + * + * @param[in] deallocate Set to @c true to deallocate all objects, @n + * else @c false + * @remarks This method can be called before deleting the collection. + */ + virtual void RemoveAll(bool deallocate = false); + + /** + * Gets the number of objects currently stored in this queue. + * + * @since 2.0 + * + * @return The number of objects currently stored in this queue + */ + virtual int GetCount(void) const; + + /** + * Checks whether this queue contains the specified object. + * + * @since 2.0 + * + * @return @c true if this queue contains the specified object, @n + * else @c false + * @param[in] obj The object to locate + */ + virtual bool Contains(const Object& obj) const; + + /** + * @if OSPDEPREC + * Checks whether this queue contains all the elements in the specified collection. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it transfers a result of comparison in out-parameter form. + * The return type will be changed into boolean type and this method will return the result. + * Instead of using this method, use bool ContainsAll(const ICollection& collection). + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to locate + * @param[out] out Set to @c true if this queue contains all the elements in the specified collection, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @endif + */ + result ContainsAll(const ICollection& collection, bool& out) const + { + out = ContainsAll(collection); + result r = GetLastResult(); + return r; + } + + /** + * Checks whether this queue contains all the elements in the specified collection. + * + * @since 2.0 + * + * @return @c true if this queue contains all the elements in the specified collection, @n + * else @c false + * @param[in] collection The collection to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual bool ContainsAll(const ICollection& collection) const; + + /** + * Compares the specified instance to the current instance for equality. + * + * @since 2.0 + * + * @return @c true if the specified instance equals the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true if and only if the specified object is also an instance of %Queue class, + * both queues have the same size, and all corresponding pairs of elements in the two queues are equal. + * In other words, two queues are equal if they contain the same elements in the same order. + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + +private: + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @param[in] queue The specified instance of %Queue to initialize the current instance + // + Queue(const Queue& queue); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @param[in] queue An instance of %Queue + // + Queue& operator =(const Queue& queue); + + int __capacity; + int __head; + int __tail; + Object** __pObjArray; + int __modCount; + static const int DEFAULT_CAPACITY = 10; + + friend class _QueueEnumerator; + friend class _QueueImpl; + class _QueueImpl* __pQueueImpl; + +}; // Queue + +}}} // Tizen::Collection + +#endif // _FBASE_COL_QUEUE_H_ diff --git a/inc/FBaseColQueueT.h b/inc/FBaseColQueueT.h new file mode 100644 index 0000000..fae7659 --- /dev/null +++ b/inc/FBaseColQueueT.h @@ -0,0 +1,655 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColQueueT.h + * @brief This is the header file for the %QueueT class. + * + * This header file contains the declarations of the %QueueT class. + * + */ +#ifndef _FBASE_COL_QUEUE_T_H_ +#define _FBASE_COL_QUEUE_T_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +template< class Type > class __QueueEnumeratorT; + +/** + * @class QueueT + * @brief This represents a template-based queue (a first-in-first-out collection of objects). + * + * @since 2.0 + * + * The %QueueT class represents a template-based queue (a first-in-first-out collection of objects). + * + * For more information on the class features, see Stack and Queue. + * + * The following example demonstrates how to use the %QueueT class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::QueueTSample(void) + * { + * QueueT queue; + * queue.Construct(); + * + * String str1(L"First"); + * String str2(L"Second"); + * String str3(L"Third"); + * + * queue.Enqueue(str1); + * queue.Enqueue(str2); + * queue.Enqueue(str3); + * + * // Reads the element at the beginning + * String temp; + * queue.Peek(temp); // temp: "First", queue.GetCount(): 3 + * + * // Reads and removes the element at the beginning + * queue.Dequeue(temp); // temp: "First", queue.GetCount(): 2 + * } + * @endcode + */ +template< class Type > +class QueueT + : public virtual ICollectionT< Type > + , public Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + QueueT(void) + : __capacity(0) + , __head(0) + , __tail(0) + , __pObjArray(null) + , __modCount(0) + { + } + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~QueueT(void) + { + __modCount++; + RemoveAll(); + } + + /** + * Initializes this instance of %QueueT with the specified capacity. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The number of elements in the queue @n + * The default capacity is @c 10. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the specified @c capacity is negative. + */ + result Construct(int capacity = DEFAULT_CAPACITY) + { + TryReturn(capacity >= 0, E_INVALID_ARG, "[%s] The capacity(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), capacity); + + if (capacity > 0) + { + __pObjArray = new Type[capacity]; + TryReturn(__pObjArray != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + } + __capacity = capacity; + + return E_SUCCESS; + } + + /** + * Initializes this instance of %QueueT that contains the elements of the specified @c collection. @n + * The capacity of the queue is the same as the number of elements copied. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to copy the elements from + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @see QueueT() + */ + result Construct(const ICollectionT< Type >& collection) + { + result r = E_SUCCESS; + + IEnumeratorT< Type >* pEnum = null; + if (collection.GetCount() > 0) + { + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + pEnum = pCol->GetEnumeratorN(); + TryCatch(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (true) + { + Type temp; + r = pEnum->MoveNext(); + + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + break; + } + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(temp); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = Enqueue(temp); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + } + + if (null != pEnum) + { + delete pEnum; + } + return r; + +CATCH: + RemoveAll(); + + if (null != pEnum) + { + delete pEnum; + } + return r; + } + + /** + * Reads and removes the element at the beginning of this queue. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The element at the beginning of this queue + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * this queue is empty. + * @see Enqueue() + */ + virtual result Dequeue(Type& obj) + { + if (__head <= __tail) + return E_UNDERFLOW; + + __modCount++; + int index = (__tail) % __capacity; + obj = __pObjArray[index]; + + __tail++; + + return E_SUCCESS; + } + + /** + * Inserts an object at the end of this queue. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to add to this queue + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @see Dequeue() + */ + virtual result Enqueue(const Type& obj) + { + if (null == __pObjArray) + { + __pObjArray = new Type[DEFAULT_CAPACITY]; + TryReturn(__pObjArray != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + __capacity = DEFAULT_CAPACITY; + } + else if ((__head - __tail) >= __capacity) + { + Type* pArrayTemp = new Type[__capacity + DEFAULT_CAPACITY]; + TryReturn(pArrayTemp != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0, j = __tail; i < __capacity; i++, j++) + { + pArrayTemp[i] = __pObjArray[j % __capacity]; + } + + delete[] __pObjArray; + __pObjArray = pArrayTemp; + __tail = 0; + __head = __capacity; + __capacity += DEFAULT_CAPACITY; + } + + __modCount++; + __pObjArray[__head % __capacity] = obj; + __head++; + + return E_SUCCESS; + } + + /** + * Removes all the elements in this queue. + * + * @since 2.0 + */ + virtual void RemoveAll(void) + { + if (__pObjArray != null) + { + delete[] __pObjArray; + } + + __pObjArray = null; + + __modCount++; + __capacity = 0; + __head = 0; + __tail = 0; + } + + /** + * Gets an enumerator of this queue. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IEnumeratorT derived class) of this queue, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumeratorT + */ + virtual IEnumeratorT< Type >* GetEnumeratorN(void) const + { + ClearLastResult(); + + result r = E_SUCCESS; + + __QueueEnumeratorT< Type >* pEnum = new __QueueEnumeratorT< Type >(*this, __modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Reads the element at the beginning of this queue without removing it. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The element at the beginning of this queue + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * this queue is empty. + */ + virtual result Peek(Type& obj) const + { + if (__head <= __tail) + { + return E_UNDERFLOW; + } + + obj = __pObjArray[__tail % __capacity]; + + return E_SUCCESS; + } + + /** + * Gets the number of objects currently stored in this queue. + * + * @since 2.0 + * + * @return The number of objects currently stored in this queue + */ + virtual int GetCount(void) const + { + return __head - __tail; + } + + /** + * Checks whether this queue contains the specified object. + * + * @since 2.0 + * + * @return @c true if this queue contains the specified object, @n + * else @c false + * @param[in] obj The object to locate + */ + virtual bool Contains(const Type& obj) const + { + bool out = false; + for (int i = 0; i < GetCount(); i++) + { + if (__pObjArray[(__tail + i) % __capacity] == obj) + { + out = true; + break; + } + } + + return out; + } + + /** + * Checks whether this queue contains all of the elements in the specified collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to locate + * @param[out] out Set to @c true if this queue contains all of the elements in the specified collection, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result ContainsAll(const ICollectionT< Type >& collection, bool& out) const + { + result r = E_SUCCESS; + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + IEnumeratorT< Type >* pEnum = pCol->GetEnumeratorN(); + TryCatch(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (true) + { + Type temp; + r = pEnum->MoveNext(); + + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + out = true; + break; + } + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(temp); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + if (false == Contains(temp)) + { + out = false; + break; + } + } + + if (null != pEnum) + { + delete pEnum; + } + return r; + +CATCH: + if (null != pEnum) + { + delete pEnum; + } + return r; + } + + /** + * Compares the specified instance to the current instance for equality. + * + * @since 2.0 + * + * @return @c true if the specified instance equals the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true if and only if the specified object is also an instance of %QueueT class, + * both queues have the same size, and all corresponding pairs of elements in the two queues are equal. + * In other words, two queues are equal if they contain the same elements in the same order. + */ + virtual bool Equals(const Object& obj) const + { + bool out = true; + + const QueueT< Type >* other = dynamic_cast< const QueueT< Type >* >(&obj); + if (null == other) + { + out = false; + } + else if (other == this) + { + out = true; + } + else if (GetCount() != other->GetCount()) + { + out = false; + } + else + { + for (int i = 0; i < GetCount(); i++) + { + if (!(__pObjArray[(__tail + i) % __capacity] == other->__pObjArray[(other->__tail + i) % other->__capacity])) + { + out = false; + break; + } + } + } + + return out; + } + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const + { + int hash = 0; + int count = GetCount(); + for (int i = 0; i < count; i++) + { + if (&(__pObjArray[(__tail + i) % __capacity]) != null) + { + hash += reinterpret_cast< int >(&(__pObjArray[(__tail + i) % __capacity])); + } + } + return hash; + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] queue The specified instance of %QueueT to initialize the current instance + */ + QueueT(const QueueT< Type >& queue); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] queue An instance of %QueueT + */ + QueueT< Type >& operator =(const QueueT< Type >& queue); + + int __capacity; + int __head; + int __tail; + Type* __pObjArray; + int __modCount; + static const int DEFAULT_CAPACITY = 10; + + friend class __QueueEnumeratorT< Type >; + +}; // QueueT + +// +// @class __QueueEnumeratorT +// @brief This class is an implementation of IEnumeratorT for %QueueT. +// @since 2.0 +// +template< class Type > +class __QueueEnumeratorT + : public IEnumeratorT< Type > + , public Object +{ +public: + /** + * Initializes this instance of __QueueEnumeratorT with the specified parameters. + * + * @since 2.0 + * + * @param[in] queue A queue to enumerate + * @param[in] modeCount The modification count to detect the change in the queue + */ + __QueueEnumeratorT(const QueueT< Type >& queue, int modeCount) + : __queue(queue) + , __modCount(modeCount) + , __position(-1) + { + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__QueueEnumeratorT(void) + { + } + + /** + * Gets the current object in the queue. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The current object + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - This enumerator is currently positioned before the first element or + * past the last element. @n + * - The queue is modified after this enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + result GetCurrent(Type& obj) const + { + TryReturn((__modCount == __queue.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn((__position >= __queue.__tail) && (__position < __queue.__head), E_INVALID_OPERATION, + "[%s] Current position is before the first element or past the last element.", GetErrorMessage(E_INVALID_OPERATION)); + + obj = __queue.__pObjArray[__position % __queue.__capacity]; + + return E_SUCCESS; + } + + /** + * Moves this enumerator to the next element of the queue. @n + * When this enumerator is first created or after the call to Reset(), + * the first call to MoveNext() positions this enumerator to the first element in the queue. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the queue is modified after this enumerator is created. + * @exception E_OUT_OF_RANGE The enumerator has passed the end of the queue. + * @see Reset() + */ + result MoveNext(void) + { + TryReturn((__modCount == __queue.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + if ((__position + 1) >= __queue.__head) + { + return E_OUT_OF_RANGE; + } + else + { + if (__position == -1) + { + __position = __queue.__tail; + } + else + { + __position++; + } + } + + return E_SUCCESS; + } + + /** + * Positions this enumerator before the first element in the queue. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the queue is modified after this enumerator is created. + */ + result Reset(void) + { + TryReturn((__modCount == __queue.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __position = -1; + + return E_SUCCESS; + } + +private: + const QueueT< Type >& __queue; + int __modCount; + int __position; + +}; // __QueueEnumeratorT + +}}} // Tizen::Base::Collection + +#endif //_FBASE_COL_QUEUE_T_H_ diff --git a/inc/FBaseColStack.h b/inc/FBaseColStack.h new file mode 100644 index 0000000..8cd8ce9 --- /dev/null +++ b/inc/FBaseColStack.h @@ -0,0 +1,340 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColStack.h + * @brief This is the header file for the %Stack class. + * + * This header file contains the declarations of the %Stack class. + * + */ +#ifndef _FBASE_COL_STACK_H_ +#define _FBASE_COL_STACK_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class Stack + * @brief This class represents a simple last-in-first-out collection of objects, that is, a stack. + * + * @since 2.0 + * + * The %Stack class represents a simple last-in-first-out collection of objects, that is, a stack. + * + * For more information on the class features, see Stack and Queue. + * + * The following example demonstrates how to use the %Stack class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::StackSample(void) + * { + * Stack stack; + * stack.Construct(3); // capacity = 3 + * + * stack.Push(new String(L"First")); + * stack.Push(new String(L"Second")); + * stack.Push(new String(L"Third")); + * + * // Reads the element at the top + * const Object* pObj = stack.Peek(); // pObj: "Third", stack.GetCount(): 3 + * + * // Reads and removes the element at the top + * String* pStr = static_cast (stack.Pop()); // pStr: "Third", stack.GetCount(): 2 + * + * delete pStr; // Because the stack does not have the ownership of this pStr after popping + * + * // Deallocates all objects + * stack.RemoveAll(true); + * } + * @endcode + */ +class _OSP_EXPORT_ Stack + : public virtual ICollection + , public Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + Stack(void); + + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Stack(void); + + + /** + * Initializes this instance of %Stack with the specified capacity. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The number of elements @n + * The default capacity is @c 10. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the specified @c capacity is negative. + * @remarks If the number of elements added to the stack reaches the current capacity, + * the capacity is automatically increased by memory reallocation. @n + * Therefore, if the size of the stack can be estimated, + * specifying the initial capacity eliminates the need to perform a number of + * resizing operations while adding elements to the stack. + * @see Stack() + */ + result Construct(int capacity = DEFAULT_CAPACITY); + + /** + * Initializes this instance of %Stack by copying the elements of the specified collection. @n + * The capacity of the stack is the same as the number of elements copied. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to copy elements from + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks This method performs a shallow copy. It copies just the pointer; not the element itself. + * @see Stack() + */ + result Construct(const ICollection& collection); + + /** + * Gets an enumerator of this stack. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IEnumerator derived class) of this stack, @n + * else @c null if an exception occurs + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see IEnumerator + */ + virtual IEnumerator* GetEnumeratorN(void) const; + + /** + * Gets the element at the top of this stack without removing it. + * + * @since 2.0 + * + * @return The element at the top of this stack, @n + * else @c null if this stack is empty + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * this stack is empty. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual const Object* Peek(void) const; + + /** + * Pops the element from the top of this stack. + * + * @since 2.0 + * + * @return The element at the top of this stack, @n + * else @c null if this stack is empty + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * this stack is empty. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Push() + */ + virtual Object* Pop(void); + + /** + * @if OSPDEPREC + * Pushes an object to the top of this stack. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it has a problem of const reference argument. + * Instead of using this method, use Push(Object* pObj). + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to add to this stack + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see Pop() + * @endif + */ + result Push(const Object& obj) + { + return Push(const_cast< Object* >(&obj)); + } + + /** + * Pushes an object to the top of this stack. + * + * @since 2.0 + * + * @return An error code + * @param[in] pObj The pointer to object to add to this stack + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @remarks This method performs a shallow copy. It inserts just the pointer; not the element itself. + * @see Pop() + */ + virtual result Push(Object* pObj); + + /** + * Removes all objects and their pointers in collection, when the @c deallocate parameter is set to @c true. @n + * This method can be called before deleting the objects in a collection. + * + * @since 2.0 + * + * @param[in] deallocate Set to @c true to deallocate all objects, @n + * else @c false + */ + virtual void RemoveAll(bool deallocate = false); + + /** + * Gets the number of objects currently stored in this stack. + * + * @since 2.0 + * + * @return The number of objects currently stored in this stack + */ + virtual int GetCount(void) const; + + /** + * Checks whether this stack contains the specified object. + * + * @since 2.0 + * + * @return @c true if this stack contains the specified object, @n + * else @c false + * @param[in] obj The object to locate + */ + virtual bool Contains(const Object& obj) const; + + /** + * @if OSPDEPREC + * Checks whether this stack contains all of the elements in the specified collection. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because it transfers a result of comparison in out-parameter form. + * The return type will be changed into boolean type and this method will return the result. + * Instead of using this method, use bool Contains(const ICollection& collection). + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to locate + * @param[out] out Set to @c true if this stack contains all the elements in the specified collection, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @endif + */ + result ContainsAll(const ICollection& collection, bool& out) const + { + out = ContainsAll(collection); + result r = GetLastResult(); + return r; + } + + /** + * Checks whether this stack contains all of the elements in the specified collection. + * + * @since 2.0 + * + * @return @c true if this stack contains all the elements in the specified collection, @n + * else @c false + * @param[in] collection The collection to locate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the @c collection is modified during the operation of this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual bool ContainsAll(const ICollection& collection) const; + + /** + * Checks whether the specified instance equals the current instance. + * + * @since 2.0 + * + * @return @c true if the specified instance equals the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true only if the specified object is also an instance of %Stack class, + * both stacks have the same size, and all corresponding pairs of elements in the two stacks are equal. + * In other words, two stacks are equal if they contain the same elements in the same order. + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] stack The other instance of Stack + */ + Stack(const Stack& stack); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * + * @param[in] stack An instance of %Stack + */ + Stack& operator =(const Stack& stack); + + int __capacity; + int __index; + Object** __pObjArray; + int __modCount; + static const int DEFAULT_CAPACITY = 10; + + friend class _StackEnumerator; + class _StackImpl* __pStackImpl; + friend class _StackImpl; + +}; // Stack + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_STACK_H_ diff --git a/inc/FBaseColStackT.h b/inc/FBaseColStackT.h new file mode 100644 index 0000000..991085a --- /dev/null +++ b/inc/FBaseColStackT.h @@ -0,0 +1,655 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColStackT.h + * @brief This is the header file for the %StackT class. + * + * This header file contains the declarations of the %StackT class. + * + */ +#ifndef _FBASE_COL_STACK_T_H_ +#define _FBASE_COL_STACK_T_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +template< class Type > class __StackEnumeratorT; + +/** + * @class StackT + * @brief This class represents a template-based stack (a last-in-first-out collection of objects). + * + * @since 2.0 + * + * The %StackT class represents a template-based stack (a last-in-first-out collection of objects). + * + * For more information on the class features, see Stack and Queue. + * + * The following example demonstrates how to use the %StackT class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * + * void + * MyClass::StackTSample(void) + * { + * StackT stack; + * stack.Construct(); + * + * String str1(L"First"); + * String str2(L"Second"); + * String str3(L"Third"); + * + * stack.Push(str1); + * stack.Push(str2); + * stack.Push(str3); + * + * // Reads the element at the top + * String temp; + * stack.Peek(temp); // temp: "Third", stack.GetCount(): 3 + * + * // Reads and removes the element at the top + * stack.Pop(temp); // temp: "Third", stack.GetCount(): 2 + * } + * @endcode + */ +template< class Type > +class StackT + : public virtual ICollectionT< Type > + , public Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + StackT(void) + : __capacity(0) + , __index(-1) + , __pObjArray(null) + , __modCount(0) + { + } + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~StackT(void) + { + __modCount++; + RemoveAll(); + } + + /** + * Initializes this instance of %StackT with the specified capacity. + * + * @since 2.0 + * + * @return An error code + * @param[in] capacity The number of elements @n + * The default capacity is @c 10. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c capacity is negative. + */ + result Construct(int capacity = DEFAULT_CAPACITY) + { + TryReturn(capacity >= 0, E_INVALID_ARG, "[%s] The capacity(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), capacity); + + if (capacity > 0) + { + __pObjArray = new Type[capacity]; + TryReturn(__pObjArray != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + } + __capacity = capacity; + + return E_SUCCESS; + } + + /** + * Initializes this instance of %StackT that contains the elements of the specified collection. @n + * The capacity of the stack is the same as the number of elements copied. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to copy elements from + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + * @see StackT() + */ + result Construct(const ICollectionT< Type >& collection) + { + result r = E_SUCCESS; + + IEnumeratorT< Type >* pEnum = null; + if (collection.GetCount() > 0) + { + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + pEnum = pCol->GetEnumeratorN(); + TryCatch(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (true) + { + Type temp; + + r = pEnum->MoveNext(); + // enumerator is reached to the end of collection + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + break; + } + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(temp); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = Push(temp); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + } + } + + if (null != pEnum) + { + delete pEnum; + } + return r; + +CATCH: + RemoveAll(); + + if (null != pEnum) + { + delete pEnum; + } + return r; + } + + /** + * Gets an enumerator of this stack. + * + * @since 2.0 + * + * @return An enumerator (an instance of the IEnumeratorT derived class) of this stack, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Collection::IEnumeratorT + */ + virtual IEnumeratorT< Type >* GetEnumeratorN(void) const + { + ClearLastResult(); + + result r = E_SUCCESS; + + __StackEnumeratorT< Type >* pEnum = new __StackEnumeratorT< Type >(*this, __modCount); + TryCatch(pEnum != null, r = E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + return pEnum; + +CATCH: + SetLastResult(r); + return null; + } + + /** + * Reads the element at the beginning of this stack without removing it. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The element at the beginning of this stack + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * this stack is empty. + */ + virtual result Peek(Type& obj) const + { + if (__index < 0) + { + return E_UNDERFLOW; + } + + obj = __pObjArray[__index]; + + return E_SUCCESS; + } + + /** + * Pops the element from the beginning of this stack. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The element at the beginning of this stack + * @exception E_SUCCESS The method is successful. + * @exception E_UNDERFLOW The operation (arithmetic/casting/conversion) has caused an underflow, or + * this stack is empty. + * @see Push() + */ + virtual result Pop(Type& obj) + { + if (__index < 0) + { + return E_UNDERFLOW; + } + + __modCount++; + + obj = __pObjArray[__index]; + + __index--; + + return E_SUCCESS; + } + + /** + * Pushes an object at the top of this stack. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj The object to add to this stack + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @see Pop() + */ + virtual result Push(const Type& obj) + { + // Ensure capacity + if (null == __pObjArray) + { + __pObjArray = new Type[DEFAULT_CAPACITY]; + TryReturn(__pObjArray != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + __capacity = DEFAULT_CAPACITY; + } + else if ((__index + 1) >= __capacity) + { + Type* pArrayTemp = new Type[__capacity + DEFAULT_CAPACITY]; + TryReturn(pArrayTemp != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i <= __index; i++) + { + pArrayTemp[i] = __pObjArray[i]; + } + + delete[] __pObjArray; + + __pObjArray = pArrayTemp; + __capacity += DEFAULT_CAPACITY; + } + + __modCount++; + + // Add element + __pObjArray[++__index] = obj; + + return E_SUCCESS; + } + + /** + * Removes all elements in this stack. + * + * @since 2.0 + */ + virtual void RemoveAll(void) + { + if (__pObjArray != null) + { + delete[] __pObjArray; + } + + __pObjArray = null; + + __modCount++; + __capacity = 0; + __index = -1; + } + + /** + * Gets the number of objects currently stored in this stack. + * + * @since 2.0 + * + * @return The number of objects currently stored in this stack + */ + virtual int GetCount(void) const + { + return __index + 1; + } + + /** + * Checks whether this stack contains the specified object. + * + * @since 2.0 + * + * @return @c true if this stack contains the specified object, @n + * else @c false + * @param[in] obj The object to locate + */ + virtual bool Contains(const Type& obj) const + { + bool out = false; + + if (__index > -1) + { + for (int i = 0; i <= __index; i++) + { + if (__pObjArray[i] == obj) + { + out = true; + break; + } + } + } + + return out; + } + + /** + * Checks whether this stack contains all of the elements in the specified collection. + * + * @since 2.0 + * + * @return An error code + * @param[in] collection The collection to locate + * @param[out] out Set to @c true if this stack contains all of the elements in the specified collection, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the specified @c collection is modified during the operation of this method. + */ + virtual result ContainsAll(const ICollectionT< Type >& collection, bool& out) const + { + result r = E_SUCCESS; + + ICollectionT< Type >* pCol = const_cast< ICollectionT< Type >* >(&collection); + IEnumeratorT< Type >* pEnum = pCol->GetEnumeratorN(); + TryCatch(pEnum != null, r = GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (true) + { + Type temp; + + r = pEnum->MoveNext(); + // enumerator has reached the end of collection + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + out = true; + break; + } + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + r = pEnum->GetCurrent(temp); + TryCatch(r == E_SUCCESS, , "[%s] Propagating.", GetErrorMessage(r)); + + if (false == Contains(temp)) + { + out = false; + break; + } + } + + if (null != pEnum) + { + delete pEnum; + } + return r; + +CATCH: + if (null != pEnum) + { + delete pEnum; + } + return r; + } + + /** + * Checks whether the specified instance equals the current instance. + * + * @since 2.0 + * + * @return @c true if the specified instance equals the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks This method returns @c true only if the specified object is also an instance of the Stack class, + * both stacks have the same size, and all the corresponding pairs of elements in the two stacks are equal. + * In other words, two stacks are equal if they contain the same elements in the same order. + */ + virtual bool Equals(const Object& obj) const + { + bool out = true; + + const StackT< Type >* other = dynamic_cast< const StackT< Type >* >(&obj); + if (null == other) // obj is not a StackT instance + { + out = false; + } + else if (other == this) + { + out = true; + } + else if (__index != other->__index) + { + out = false; + } + else + { + for (int i = 0; i <= __index; i++) + { + if (!(__pObjArray[i] == other->__pObjArray[i])) + { + out = false; + break; + } + } + } + + return out; + } + + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks The two Tizen::Base::Object::Equals() instances must return the same hash value. For better performance, @n + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const + { + int hash = 0; + for (int i = 0; i <= __index; i++) + { + if (&__pObjArray[i] != null) + { + hash += reinterpret_cast< int >(&__pObjArray[i]); + } + } + + return hash; + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] stack The other instance of StackT + */ + StackT(const StackT< Type >& stack); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] stack An instance of %StackT + */ + StackT< Type >& operator =(const StackT< Type >& stack); + + int __capacity; + int __index; + Type* __pObjArray; + int __modCount; + static const int DEFAULT_CAPACITY = 10; + + friend class __StackEnumeratorT< Type >; + +}; // StackT + +// +// @class __StackEnumeratorT +// @brief This class is an implementation of IEnumeratorT for %StackT. +// @since 2.0 +// +template< class Type > +class __StackEnumeratorT + : public IEnumeratorT< Type > + , public Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + * + * @param[in] stack A stack to enumerate + * @param[in] modCount The modification count to detect the change in the stack + */ + __StackEnumeratorT(const StackT< Type >& stack, int modCount) + : __stack(stack) + , __modCount(modCount) + , __position(-1) + { + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~__StackEnumeratorT(void) + { + } + + /** + * Gets the current object in the stack. + * + * @since 2.0 + * + * @return An error code + * @param[out] obj The current object + * @exception E_INVALID_OPERATION Either of the following conditions has occurred: @n + * - The current state of the instance prohibits the execution of the specified operation. @n + * - This enumerator is currently positioned before the first element or + * past the last element. @n + * - The stack is modified after this enumerator is created. + * @exception E_SUCCESS The method is successful. + */ + result GetCurrent(Type& obj) const + { + TryReturn(__modCount == __stack.__modCount, E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + TryReturn(((__position >= 0) && (__position <= __stack.__index)), E_INVALID_OPERATION, + "[%s] Current position is before the first element or past the last element.", GetErrorMessage(E_INVALID_OPERATION)); + + obj = __stack.__pObjArray[__position]; + + return E_SUCCESS; + } + + /** + * Moves this enumerator to the next element of the stack. @n + * When this enumerator is first created or after a call to Reset(), + * the first call to MoveNext() positions this enumerator to the first element in the stack. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the stack is modified after this enumerator is created. + * @exception E_OUT_OF_RANGE The enumerator has passed the end of the stack. + * @see Reset() + */ + result MoveNext(void) + { + TryReturn((__modCount == __stack.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + result r = E_SUCCESS; + if (__position >= __stack.__index) + { + // Do not log the E_OUT_OF_RANGE, because it is normal or trivial in most cases. + r = E_OUT_OF_RANGE; + } + else + { + __position++; + } + + return r; + } + + /** + * Positions this enumerator before the first element in the stack. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current state of the instance prohibits the execution of the specified operation, or + * the stack is modified after this enumerator is created. + */ + result Reset(void) + { + TryReturn((__modCount == __stack.__modCount), E_INVALID_OPERATION, + "[%s] The source collection is modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __position = -1; + + return E_SUCCESS; + } + +private: + const StackT< Type >& __stack; + int __modCount; + int __position; + +}; // __StackEnumeratorT + +}}} // Tizen::Base::Collection + +#endif //_FBASE_COL_STACK_T_H_ diff --git a/inc/FBaseColTypes.h b/inc/FBaseColTypes.h new file mode 100644 index 0000000..cc0de7c --- /dev/null +++ b/inc/FBaseColTypes.h @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColTypes.h + * @brief This is the header file for the element deleter. + * + * This header file contains the declarations of the element deleter. + * Depending on the element deleter, collection decides whether removing the object or not. + */ +#ifndef _FBASE_COL_TYPES_H_ +#define _FBASE_COL_TYPES_H_ + +#include + +namespace Tizen { namespace Base { namespace Collection +{ + +typedef void (*DeleterFunctionType)(Object* pObj); + +/** + * This function doesn't remove the object. + * + * @since 2.0 + * + * @param[in] pObj The pointer to object to remove + */ +_OSP_EXPORT_ void NoOpDeleter(Object* pObj); + +/** + * This function removes the single object. + * + * @since 2.0 + * + * @param[in] pObj The pointer to object to remove + */ +_OSP_EXPORT_ void SingleObjectDeleter(Object* pObj); + +/** + * This function removes the array object. + * + * @since 2.0 + * + * @param[in] pObj The pointer to object to remove + */ +_OSP_EXPORT_ void ArrayDeleter(Object* pObj); + +}}} // Tizen::Base::Collection + +#endif // _FBASE_COL_TYPES_H_ diff --git a/inc/FBaseComparerT.h b/inc/FBaseComparerT.h new file mode 100644 index 0000000..596e25d --- /dev/null +++ b/inc/FBaseComparerT.h @@ -0,0 +1,139 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseComparerT.h + * @brief This is the header file for the %ComparerT class. + * + * This file contains declarations of the %ComparerT class. + */ +#ifndef _FBASE_COMPARER_T_H_ +#define _FBASE_COMPARER_T_H_ + +// Includes +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class ComparerT + * + * @brief This class checks for equivalence between 2 values of the same primitive type. + * @since 2.0 + * + * The %ComparerT class checks for equivalence between 2 values of the same primitive type. + * + * The following example demonstrates how to use the %ComparerT class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::ComparerTSample(void) + * { + * double d1 = 123; + * double d2 = 124; + * ComparerT comparer; + * + * // Compares 2 instances of Double + * int cmp; + * comparer.Compare(d1, d2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +template +class ComparerT + : public virtual Tizen::Base::Collection::IComparerT + , public Object +{ +public: + /** + * This constructor initializes a new instance of the %ComparerT class. + * + * @since 2.0 + */ + ComparerT(void) {} + + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~ComparerT(void) { } + + /** + * Compares two given instances of the same type. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 The first object to compare + * @param[in] obj2 The second object to compare + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified objects are not of the expected type. + * @remarks @c cmp can take one of the following values: + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Type& obj1, const Type& obj2, int& cmp) const + { + if (obj1 > obj2) + { + cmp = 1; + } + else if (obj1 < obj2) + { + cmp = -1; + } + else + { + cmp = 0; + } + + return E_SUCCESS; + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + ComparerT(const ComparerT& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + ComparerT& operator =(const ComparerT& rhs); + +}; // ComparerT + +}} // Tizen::Base + +#endif // _FBASE_COMPARER_T_H_ diff --git a/inc/FBaseDataType.h b/inc/FBaseDataType.h new file mode 100644 index 0000000..4cbe8b8 --- /dev/null +++ b/inc/FBaseDataType.h @@ -0,0 +1,95 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDataType.h + * @brief This is the header file for the data types. + * + * This header file defines the data types. + */ +#ifndef _FBASE_DATA_TYPE_H_ +#define _FBASE_DATA_TYPE_H_ + + +/** + * @c byte is an @c unsigned @c char datatype. + * @since 2.0 + */ +typedef unsigned char byte; + +/** + * @c result is a @c unsigned @c long type and indicates the result of the method execution. + * @since 2.0 + */ +typedef unsigned long result; + + +namespace Tizen { namespace Base +{ +class String; +}} + +typedef Tizen::Base::String UserId; +typedef Tizen::Base::String LoginId; + + +/** +* The invocation ID is returned when a request is sent. +* @since 2.0 +*/ +typedef long RequestId; +#define INVALID_REQUEST_ID -1 + + +// Macro to get the value in byte +#define GET_MASK(val, pos, msk) (((val) & ((msk) << (pos))) >> (pos)) +// Macro to put the value in byte +#define PUT_MASK(var, val, pos) ((var) | ((val) << (pos))) + + +#ifndef Handle +typedef int Handle; +#define INVALID_HANDLE -1 +#endif // Handle + +#ifndef null +#define null 0 +#endif // null + +#ifndef INFINITE +#define INFINITE 0xFFFFFFFF +#endif // INFINITE + + +#ifndef UUID +#ifndef UUID__DEFINED +typedef struct UUID_ +{ + unsigned long x; + unsigned short s1; + unsigned short s2; + unsigned char c[8]; +} UUID_; + +#define UUID__DEFINED +#define UUID_DEFINED +#endif + +#define UUID UUID_ +#endif // UUID + +#endif // _FBASE_DATA_TYPE_H_ diff --git a/inc/FBaseDateTime.h b/inc/FBaseDateTime.h new file mode 100644 index 0000000..9675d18 --- /dev/null +++ b/inc/FBaseDateTime.h @@ -0,0 +1,602 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDateTime.h + * @brief This is the header file for the %DateTime class. + * + * This header file contains the declarations of the %DateTime class. + */ +#ifndef _FBASE_DATE_TIME_H_ +#define _FBASE_DATE_TIME_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class DateTime + * @brief This class represents the date and time as per the Gregorian calendar. + * + * @since 2.0 + * + * The %DateTime class represents dates and times with values ranging from 12:00:00 midnight, + * January 1, 1 to 11:59:59 P.M., December 31, 9999 in the Gregorian calendar. It + * provides methods for conversion between the time formats. + * + * For more information on the class features, see DateTime and TimeSpan. + * + * The following example demonstrates how to use the %DateTime class. + + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method sets both current local time and UTC time. + * void + * MyClass::DateTimeSample(void) + * { + * DateTime dt; + * int year, month, day; + * + * dt.SetValue(2009, 10, 25); + * + * dt.AddYears(10); + * dt.AddMonths(3); + * dt.AddDays(5); + * + * // Gets values + * year = dt.GetYear(); // 2020 + * month = dt.GetMonth(); // 1 + * day = dt.GetDay(); // 30 + * } + * @endcode + */ +class _OSP_EXPORT_ DateTime + : public Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks The value of the instance is the same as the value of the instance returned by the GetMinValue() method. + */ + DateTime(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value The %DateTime instance to copy + */ + DateTime(const DateTime& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DateTime(void); + + /** + * Sets the current instance of %DateTime to the value of the specified instance of TimeSpan since the minimum date (GetMinValue()). + * + * @since 2.0 + * + * @param[in] value The instance of TimeSpan + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result SetValue(const TimeSpan& value); + + /** + * Sets the current instance of %DateTime to the value of the specified instance of %DateTime. + * + * @since 2.0 + * + * @param[in] value An instance of %DateTime + */ + void SetValue(const DateTime& value); + + /** + * Sets the current instance of %DateTime to the specified year, month, day, hour, minute, and second. + * + * @since 2.0 + * + * @return An error code + * @param[in] year The year to set + * @param[in] month The month to set + * @param[in] day The day to set + * @param[in] hour The hour to set + * @param[in] minute The minute set + * @param[in] second The second to set + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * Either the arguments are greater than the value returned by GetMaxValue() or + * are less than the value returned by GetMinValue(), or + * the arguments contain invalid values. + * For example, day is 31 when month is 2. + */ + result SetValue(int year, int month, int day, int hour = 0, int minute = 0, int second = 0); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return A reference to the current object + * @param[in] rhs An instance of %DateTime + */ + DateTime& operator =(const DateTime& rhs); + + /** + * Checks whether the current instance of %DateTime is equivalent to the specified instance of %DateTime. + * + * @since 2.0 + * + * @return @c true if the current instance is equivalent to the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DateTime + */ + bool operator ==(const DateTime& rhs) const; + + /** + * Checks whether the current instance of %DateTime is not equivalent to the specified instance of %DateTime. + * + * @since 2.0 + * + * @return @c true if the current instance is not equivalent to the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DateTime + */ + bool operator !=(const DateTime& rhs) const; + + /** + * Checks whether the value of the current instance of %DateTime is less than the value of the specified instance of %DateTime. + * + * @since 2.0 + * + * @return @c true if the value of the current instance is less than the value of the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DateTime + */ + bool operator <(const DateTime& rhs) const; + + /** + * Checks whether the value of the current instance of %DateTime is greater than the value of the specified instance of %DateTime. + * + * @since 2.0 + * + * @return @c true if the value of the current instance is greater than the value of the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DateTime + */ + bool operator >(const DateTime& rhs) const; + + /** + * Checks whether the value of the current instance of %DateTime is less than or equal to the value of the specified instance of %DateTime. + * + * @since 2.0 + * + * @return @c true if the value of the current instance is less than or equal to the value of the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DateTime + */ + bool operator <=(const DateTime& rhs) const; + + /** + * Checks whether the value of the current instance of %DateTime is greater than or equal to the value of the specified instance of %DateTime. + * + * @since 2.0 + * + * @return @c true if the value of the current instance is greater than or equal to the value of the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DateTime + */ + bool operator >=(const DateTime& rhs) const; + + /** + * Adds the specified time span to the instance of %DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] t The time span to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result Add(const TimeSpan& t); + + /** + * Adds the specified number of days to the instance of %DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] days The number of days to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result AddDays(int days); + + /** + * Adds the specified number of hours to the instance of %DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] hours The number of hours to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result AddHours(int hours); + + /** + * Adds the specified number of minutes to the instance of %DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] minutes The number of minutes to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result AddMinutes(int minutes); + + /** + * Adds the specified number of months to the instance of %DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] months The number of months to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result AddMonths(int months); + + /** + * Adds the specified number of seconds to the instance of %DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] seconds The number of seconds to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result AddSeconds(int seconds); + + /** + * Adds the specified number of years to the instance of %DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] years The number of years to add + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result AddYears(int years); + + /** + * Compares two specified instances of %DateTime. @n + * The two instances must be in the same time zone to make a meaningful comparison. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of @c dt1 is less than the value of @c dt2 + * == 0 if the value of @c dt1 is equal to the value of @c dt2 + * > 0 if the value of @c dt1 is greater than the value of @c dt2 + * @endcode + * @param[in] dt1 An instance of %DateTime + * @param[in] dt2 An instance of %DateTime + */ + static int Compare(const DateTime& dt1, const DateTime& dt2); + + /** + * Compares the value of the current instance of %DateTime with the value of the specified instance of %DateTime. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of the current instance is less than value of the specified instance + * == 0 if the value of the current instance is equal to value of the specified instance + * > 0 if the value of the current instance is greater than value of the specified instance + * @endcode + * @param[in] value An instance of %DateTime + */ + int CompareTo(const DateTime& value) const; + + /** + * Checks whether the specified instance of Object is equivalent to the current instance of %DateTime. + * + * @since 2.0 + * + * @return @c true if the specified instance of Object is equivalent to the current instance of %DateTime, @n + else @c false + * @param[in] obj The object to compare with the current instance of %DateTime + * @see Tizen::Base::Object::GetHashCode() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance of %DateTime. @n + * The hash value is calculated as (GetTime() ^ (GetTime() >> 16)). + * + * @since 2.0 + * + * @return The hash value of the current instance of %DateTime + * @see Tizen::Base::Object::Equals() + */ + virtual int GetHashCode(void) const; + + /** + * Gets the time span since the midnight of the date represented by the current instance of %DateTime. + * + * @since 2.0 + * + * @return An instance of TimeSpan + */ + TimeSpan GetTimeOfDay(void) const; + + /** + * Gets the number of days in the specified month of the specified year. + * + * @since 2.0 + * + * @return An error code + * @param[in] year The year + * @param[in] month The month + * @param[out] days The number of days + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * @c year must be a value between @c 1 and @c 9999 and @c month must be a value between @c 1 and @c 12. + */ + static result GetDaysInMonth(int year, int month, int& days); + + /** + * Subtracts the specified time span from the value of the current instance of %DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] t The time span to deduct + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The resulting value of %DateTime is greater than the value returned by GetMaxValue() or @n + * is less than the value returned by GetMinValue(). + */ + result Subtract(const TimeSpan& t); + + /** + * Represents the current instance of %DateTime as a string. + * + * @since 2.0 + * + * @return A string containing Unicode representation of the value of the current instance of %DateTime + * @remarks The format of the String representation is "mm/dd/yyyy hh:mm:ss". + * @remarks Use the Tizen::Locale namespace for a string of the locale-specific representation. + * + */ + String ToString(void) const; + + /** + * Parses the specified String representation of the date and time value. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A String representation of a date and time value + * @param[out] dt The result of the method + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is in an invalid format. + * @exception E_OUT_OF_RANGE The specified string contains an invalid value. @n + * 1) The resulting value of %DateTime is greater than the value returned by GetMaxValue() + * or is less than the value returned by GetMinValue(). @n + * 2) The specified string contains an invalid value. + * For example, day is 31 when the month is 2. + * @remarks The format of the string is "mm/dd/yyyy hh:mm:ss". + */ + static result Parse(const String& str, DateTime& dt); + + /** + * Gets the year of the current instance of %DateTime. + * + * @since 2.0 + * + * @return An integer value indicating the year of the current instance of %DateTime + */ + int GetYear(void) const; + + /** + * Gets the month of the current instance of %DateTime. + * + * @since 2.0 + * + * @return An integer value indicating the month of the current instance of %DateTime + */ + int GetMonth(void) const; + + /** + * Gets the day of the current instance of %DateTime. + * + * @since 2.0 + * + * @return An integer value indicating the day of the current instance of %DateTime + */ + int GetDay(void) const; + + /** + * Gets the hour of the current instance of %DateTime. + * + * @since 2.0 + * + * @return An integer value indicating the hour of the current instance of %DateTime + */ + int GetHour(void) const; + + /** + * Gets the minute of the current instance of %DateTime. + * + * @since 2.0 + * + * @return An integer value indicating the minute of the current instance of %DateTime + */ + int GetMinute(void) const; + + /** + * Gets the second of the current instance of %DateTime. + * + * @since 2.0 + * + * @return An integer value indicating the second of the current instance of %DateTime + */ + int GetSecond(void) const; + + /** + * Gets the number of milliseconds (in TimeSpan) since the minimum date (GetMinValue()). + * + * @since 2.0 + * + * @return An instance of TimeSpan + * @remarks The returned instance is the time since the value returned by GetMinValue(). + */ + TimeSpan GetTime(void) const; + + /** + * Gets the maximum allowable value of %DateTime (that is, "December 31 9999 23:59:59"). + * + * @since 2.0 + * + * @return An instance of %DateTime + */ + static const DateTime& GetMaxValue(void); + + /** + * Gets the minimum allowable value of %DateTime (that is, "January 1 1 00:00:00"). + * + * @since 2.0 + * + * @return An instance of %DateTime + */ + static const DateTime& GetMinValue(void); + + /** + * Checks whether the year represented by the current instance of %DateTime is a leap year. + * + * @since 2.0 + * + * @return @c true if the year represented by the current instance of %DateTime is a leap year, @n + * else @c false + */ + bool IsLeapYear(void) const; + + /** + * Checks whether the specified year is a leap year. + * + * @since 2.0 + * + * @return @c true if the specified year is a leap year, @n + * else @c false + * @param[in] year The year + */ + static bool IsLeapYear(int year); + + +private: + DateTime(int year, int month, int day, int hour, int minute, int second); + + int CountLeapYear(int year) const + { + return (int) ((year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400); + + } + + int CountDays(int year) const + { + return (int) ((year - 1) * 365 + CountLeapYear(year)); + } + + int CountYears(int day) const + { + double year = (day - CountLeapYear(day / 365)) / 365.0; + Double year1(year); + Double year2(0.0); + + if (year1.Equals(year2)) + { + return 1; + } + else + { + return(year != (int) year ? 1 + (int) year : (int) year); + } + } + + typedef struct + { + int year; /** + + +namespace Tizen { namespace Base +{ +/** + * @class Double + * @brief This class is the wrapper class for the @c signed @c double built-in type. + * + * @since 2.0 + * + * The %Double class is the wrapper class for the @c signed @c double built-in type. + * + * It represents a double-precision 64-bit number with values ranging from negative + * 1.79769313486232e308 to positive 1.79769313486232e308. This class is useful when passing a @c double + * value to a method expecting an instance of Object, such as Tizen::Base::Collection::Queue or + * Tizen::Base::Collection::Stack. Furthermore, this class provides methods for converting + * %Double (and @c double) to String, and String to %Double (and @c double). + * + * The following example demonstrates how to use the %Double class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method checks whether the given string object contains a string + * // representation of the pre-defined minimum double value. + * result + * MyClass::Verify(const String& string, bool& out) + * { + * static const Double MINIMUM(1.23L); + * + * result r = E_SUCCESS; + * + * double d; + * r = Double::Parse(string, d); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * out = (MINIMUM.CompareTo(d) == 0) ? true: false; + * + * return r; + * CATCH: + * return r; + * } + * @endcode + */ +class _OSP_EXPORT_ Double + : public Number +{ +public: + /** + * Initializes this instance of %Double with the specified value. + * + * @since 2.0 + * + * @param[in] value A @c double value + */ + Double(double value = 0.0L); + + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %Double + */ + Double(const Double& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Double(void); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %Double + */ + Double& operator =(const Double& rhs); + + /** + * Compares two @c double values. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of @c d1 is less than the value of @c d2 + * == 0 if the value of @c d1 is equal to the value of @c d2 + * > 0 if the value of @c d1 is greater than the value of @c d2 + * @endcode + * @param[in] d1 The first @c double value to compare + * @param[in] d2 The second @c double value to compare + */ + static int Compare(double d1, double d2); + + /** + * Compares the value of the current instance of %Double with the value of the specified @c signed @c double. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of the current instance is less than the specified @c signed @c double + * == 0 if the value of the current instance is equal to the specified @c signed @c double + * > 0 if the value of the current instance is greater than the specified @c signed @c double + * @endcode + * @param[in] value A @c signed @c double value + */ + int CompareTo(double value) const; + + /** + * Compares the value of the current instance of %Double with the value of the specified instance of %Double. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of the current instance is less than the value of the specified instance + * == 0 if the value of the current instance is equal to the value of the specified instance + * > 0 if the value of the current instance is greater than the value of the specified instance + * @endcode + * @param[in] value An instance of %Double + */ + int CompareTo(const Double& value) const; + + /** + * Checks whether the value of the specified instance of Object is equal to the value of the current instance of %Double. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of %Object is equal to the value of the current instance of %Double, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @see Tizen::Base::Object::Equals + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance of %Double. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance of %Double + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the value of the current instance. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the hash value of the specified @c double value. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the specified @c double value + * @param[in] val A @c double value to get the hash value + */ + static int GetHashCode(double val); + + /** + * Parses the specified string representing a numeric value and returns the value as @c signed @c double (as out parameter). + * + * @since 2.0 + * + * @return An error code + * @param[in] s A unicode representation of @c signed @c double value + * @param[out] ret The converted numeric value + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + */ + static result Parse(const String& s, double& ret); + + /** + * Gets the @c signed @c char equivalent of the current instance of %Double. + * + * @since 2.0 + * + * @return A @c signed @c char equivalent of the current instance + */ + virtual char ToChar(void) const; + + /** + * Gets the @c signed @c short equivalent of the current instance of %Double. + * + * @since 2.0 + * + * @return A @c signed @c short equivalent of the current instance + */ + virtual short ToShort(void) const; + + /** + * Gets the @c signed @c int equivalent of the current instance of %Double. + * + * @since 2.0 + * + * @return A @c signed @c int equivalent of the current instance + */ + virtual int ToInt(void) const; + + /** + * Gets the @c signed @c long equivalent of the current instance of %Double. + * + * @since 2.0 + * + * @return A @c signed @c long equivalent of the current instance + */ + virtual long ToLong(void) const; + + /** + * Gets the @c signed @c long @c long equivalent of the current instance of %Double. + * + * @since 2.0 + * + * @return A @c signed @c long @c long equivalent of the current instance + */ + virtual long long ToLongLong(void) const; + + /** + * Gets the @c signed @c float equivalent of the current instance of %Double. + * + * @since 2.0 + * + * @return A @c signed @c float equivalent of the current instance + */ + virtual float ToFloat(void) const; + + /** + * Gets the @c signed @c double equivalent of the current instance of %Double. + * + * @since 2.0 + * + * @return A @c signed @c double equivalent of the current instance + */ + virtual double ToDouble(void) const; + + /** + * Gets the string representing the value of the current instance of %Double. + * + * @since 2.0 + * + * @return A string containing a Unicode representation of the value of the current instance + * @remarks If the value of the current instance is Not-a-Number (NaN), the result is the string "NaN". Furthermore, infinity + * produces the result "Infinity". @n + * 6 digits are given for the precision of this method. Use String::Format() to set the specific precision. + */ + virtual String ToString(void) const; + + /** + * Gets the string representing the specified @c double value. + * + * @since 2.0 + * + * @return A string containing a Unicode representation of the specified @c double value + * @param[in] value A @c double value to convert + * @remarks If the input value is Not-a-Number (NaN), the result is the string "NaN". Furthermore, infinity + * produces the result "Infinity". @n + * 6 digits are given for the precision of this method. Use String::Format() to set the specific precision. + */ + static String ToString(double value); + + /** + * Gets the IEEE 754 floating-point "double format" bit layout representation of the specified @c double value. + * + * @since 2.0 + * + * @return The bits that represent the floating-point number in the IEEE 754 floating-point "double format" bit layout + * @param[in] value A @c double value to convert + */ + static long long ToBits(double value); + + /** + * Gets the @c double value equivalent of the specified floating-point value represented in the IEEE 754 floating-point "double format" bit layout. + * + * @since 2.0 + * + * @return The @c double floating-point value with the same bit pattern + * @param[in] value The floating-point value to convert + */ + static double ToDoubleFromBits(long long value); + + /** + * Checks whether the current value of %Double is equal to negative or positive infinity. + * + * @since 2.0 + * + * @return @c true if the current value equals negative or positive infinity, @n + * else @c false + */ + bool IsInfinity(void) const; + + /** + * Checks whether the specified @c double value is equal to negative or positive infinity. + * + * @since 2.0 + * + * @return @c true if the specified value equals negative or positive infinity, @n + * else @c false + * @param[in] value A @c double value to check + */ + + static bool IsInfinity(double value); + + /** + * Checks whether the current value is Not-a-Number. + * + * @since 2.0 + * + * @return @c true if the current value is Not-a-Number, @n + * else @c false + */ + bool IsNaN(void) const; + + /** + * Checks whether the specified value is Not-a-Number. + * + * @since 2.0 + * + * @return @c true if the specified value is Not-a-Number, @n + * else @c false + * @param[in] value A @c double value to check + */ + static bool IsNaN(double value); + + /** + * Gets a constant holding the largest positive finite value of type @c double. @n + * This is equal to the value defined in Limit.h of the C library. + * + * @since 2.0 + * + * @return A constant holding the largest positive finite value of type @c double + */ + static double GetMaxValue(void); + + /** + * Gets a constant holding the smallest positive non-zero value of type @c double. @n + * This is equal to the value defined in Limit.h of the C library. + * + * @since 2.0 + * + * @return A constant holding the smallest possible non-zero value of type @c double + */ + static double GetMinValue(void); + + /** + * A @c double value of this instance. + * + * @since 2.0 + */ + double value; + + +private: + /** + * Checks if the specified @c double value is finite. + * + * @since 2.0 + * + * @return @c true if the specified value is finite, @n + * else @c false + * @param[in] value A @c double value to check + */ + static bool IsFinite(double d); + + static const int __DBL_MAX_10_EXP = 308; + + friend class _DoubleImpl; + class _DoubleImpl * __pDoubleImpl; + +}; // Double + +}} // Tizen::Base + +#endif //_FBASE_DOUBLE_H_ diff --git a/inc/FBaseDoubleComparer.h b/inc/FBaseDoubleComparer.h new file mode 100644 index 0000000..84dc483 --- /dev/null +++ b/inc/FBaseDoubleComparer.h @@ -0,0 +1,129 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDoubleComparer.h + * @brief This is the header file for the %DoubleComparer class. + * + * @see Double and Tizen::Base::Collection::IComparer + * + * This header file contains the declarations of the %DoubleComparer class. + */ +#ifndef _FBASE_DOUBLE_COMPARER_H_ +#define _FBASE_DOUBLE_COMPARER_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class DoubleComparer + * @brief This class checks for equivalence between 2 instances of the Double type. + * + * @since 2.0 + * + * The %DoubleComparer class checks for equivalence between 2 instances of the Double type. + * + * For more information on the class features, see Collection Comparisons. + * + * The following example demonstrates how to use the %DoubleComparer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::DoubleComparerSample(void) + * { + * Double d1(123); + * Double d2(124); + * DoubleComparer comparer; + * + * // Compare 2 instances of Double + * int cmp; + * comparer.Compare(d1, d2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +class _OSP_EXPORT_ DoubleComparer + : public Object + , public virtual Tizen::Base::Collection::IComparer +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + DoubleComparer(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DoubleComparer(void); + + /** + * Compares two given instances of type Double. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 The first instance of type %Double + * @param[in] obj2 The second instance of type %Double + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + DoubleComparer(const DoubleComparer& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + DoubleComparer& operator =(const DoubleComparer& rhs); + + friend class _DoubleComparerImpl; + class _DoubleComparerImpl * __pDoubleComparerImpl; + +}; // DoubleComparer + +}} // Tizen::Base + +#endif // _FBASE_DOUBLE_COMPARER_H_ diff --git a/inc/FBaseDoubleMatrix.h b/inc/FBaseDoubleMatrix.h new file mode 100644 index 0000000..e252a92 --- /dev/null +++ b/inc/FBaseDoubleMatrix.h @@ -0,0 +1,467 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDoubleMatrix.h + * @brief This is the header file for the %DoubleMatrix class. + * + * This header file contains the declarations of the %DoubleMatrix class. + * + */ + +#ifndef _FBASE_DOUBLE_MATRIX_H_ +#define _FBASE_DOUBLE_MATRIX_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +/** + * @class DoubleMatrix + * @brief This class encapsulates a two-dimensional matrix. + * + * @since 2.0 + * + * The %DoubleMatrix class provides a @c double precision, two-dimensional matrix class. + * + */ +class _OSP_EXPORT_ DoubleMatrix + : public Tizen::Base::Object +{ +public: + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %DoubleMatrix + */ + DoubleMatrix(const DoubleMatrix& rhs); + + /** + * Constructs a row by column null matrix in which all elements are zero. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + */ + DoubleMatrix(int rowCount, int columnCount); + + /** + * Constructs a row by column matrix initialized to the values in the specified array. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + * @param[in] pArray A one-dimensional array @n The array must be at least row * column in length. + * @param[in] rowMajor Set to @c true to copy the array in row-major order, @n + * else @c copy in column-major order + */ + DoubleMatrix(int rowCount, int columnCount, const double* pArray, bool rowMajor = true); + + /** + * Constructs a row by column matrix initialized to the values in the specified array. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + * @param[in] pArray[] A two-dimensional array @n The array must be at least row * column in length. + */ + DoubleMatrix(int rowCount, int columnCount, const double* pArray[]); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + * + */ + virtual ~DoubleMatrix(void); + + /** + * Checks whether the current instance and the specified instance of %DoubleMatrix are equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DoubleMatrix + */ + bool operator ==(const DoubleMatrix& rhs) const; + + /** + * Checks whether the current instance and the specified instance of %DoubleMatrix are not equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are not equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DoubleMatrix + */ + bool operator !=(const DoubleMatrix& rhs) const; + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] rhs An instance of %DoubleMatrix + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If either row or column count of the current instance is not same with that of the specified instance, + * return the reference to this instance without assigning. + */ + DoubleMatrix& operator =(const DoubleMatrix& rhs); + + /** + * Checks whether the current instance of %DoubleMatrix equals the specified instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return @c true if the values of the current instance are equal to the value of the specified instance, @n + * else @c false + * @param[in] obj An instance of %DoubleMatrix + * @remarks This method overrides Tizen::Base::Object::Equals(). This method uses the values of the Matrix components to compare the two instances. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Adds the value of the specified instance to the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %DoubleMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + */ + result Add(const DoubleMatrix& matrix); + + /** + * Adds the value to each matrix members of current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @param[in] value A @c double value to add + */ + void AddToEachElement(double value); + + /** + * Gets the number of column in the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return The number of column in the current instance + */ + int GetColumnCount(void) const; + + /** + * Gets a new array that includes the values of the specified column in the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return A pointer to @c double array + * @param[in] columnIndex The target column number in the current instance + * @exception E_INVALID_ARG The @c columnIndex is larger than the column count of the current instance. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + double* GetColumnN(int columnIndex) const; + + /** + * Gets the determinant of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return The determinant value of the current instance + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the current instance is not a square matrix, return zero. + */ + double GetDeterminant(void) const; + + /** + * Gets the value at the specified row and column of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return The value at the specified row and column of the current instance + * @param[in] rowIndex The target row number in the current instance + * @param[in] columnIndex The target column number in the current instance + * @exception E_INVALID_ARG The @c columnIndex or @c rowIndex is larger than that of the current instance. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + double GetElement(int rowIndex, int columnIndex) const; + + /** + * Gets the inverse matrix of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return A pointer to the instance of %DoubleMatrix containing the resulting value of the operation + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + DoubleMatrix* GetInverseN(void) const; + + /** + * Gets the number of row in the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return The number of row in the current instance + */ + int GetRowCount(void) const; + + /** + * Gets a new array that includes the values of the specified row in the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return A pointer to @c double array + * @param[in] rowIndex The target row number in the current instance + * @exception E_INVALID_ARG The @c rowIndex is larger than the row count of the current instance. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + double* GetRowN(int rowIndex) const; + + /** + * Gets the trace of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[out] value A @c double value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result GetTrace(double& value) const; + + /** + * Gets the transpose matrix of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return A pointer to the instance of %DoubleMatrix containing the resulting value of the operation + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + DoubleMatrix* GetTransposeN(void) const; + + /** + * Checks whether the current instance is an identity matrix. + * + * @since 2.0 + * + * @return @c true if the matrix is an identity matrix, @n + * else @c false + */ + bool IsIdentity(void) const; + + /** + * Checks whether the current matrix is invertible. + * + * @since 2.0 + * + * @return @c true if the matrix is invertible, @n + * else @c false + */ + bool IsInvertible(void) const; + + /** + * Multiplies the value of the specified instance with the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %DoubleMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The column count of the current instance is not same with the row count of the specified instance. + */ + result Multiply(const DoubleMatrix& matrix); + + /** + * Multiplies the value to each matrix members of current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @param[in] value A @c double value to multiply + */ + void Multiply(double value); + + /** + * Negates the matrix members of current instance of %DoubleMatrix. + * + * @since 2.0 + */ + void Negate(void); + + /** + * Sets the value of the current instance of %DoubleMatrix to its identity. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result SetAsIdentity(void); + + /** + * Sets the value of the current instance of %DoubleMatrix to its inverse. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result Invert(void); + + /** + * Sets the value of the current instance of %DoubleMatrix to its transpose. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result Transpose(void); + + /** + * Sets the values of the specified array to the specified column of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The target column number in the current instance + * @param[in] pArray An array which includes the values @n The array must be at least row in length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c pArray is @c null, or the @c columnIndex is larger than the column count of the current instance. + */ + result SetColumn(int columnIndex, const double* pArray); + + /** + * Sets the values of the specified array to the specified row of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] rowIndex The target row number in the current instance + * @param[in] pArray An array which includes the values @n The array must be at least column in length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c pArray is @c null, or the @c rowIndex is larger than the row count of the current instance. + */ + result SetRow(int rowIndex, const double* pArray); + + /** + * Sets the value to the specified row and column of the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] rowIndex The target row number in the current instance + * @param[in] columnIndex The target column number in the current instance + * @param[in] value A @c double value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The pArray is @c null, or the @c rowIndex is larger than the row count of the current instance, + * or the @c columnIndex is larger than the column count of the current instance. + */ + result SetElement(int rowIndex, int columnIndex, double value); + + /** + * Sets the values to the current instance of %DoubleMatrix in either the row-major or column-major order. + * + * @since 2.0 + * + * @return An error code + * @param[in] pArray A one-dimensional array @n The array must be at least row * column in length. + * @param[in] rowMajor Set to @c true to copy the array in row-major order, @n + * else @c copy in column-major order + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c pArray is @c null. + */ + result SetValue(const double* pArray, bool rowMajor = true); + + /** + * Sets the matrix members of current instance of %DoubleMatrix to zero. + * + * @since 2.0 + */ + void SetAsNull(void); + + /** + * Subtracts the value of the specified instance from the current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %DoubleMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + */ + result Subtract(const DoubleMatrix& matrix); + + /** + * Subtracts the value from each matrix members of current instance of %DoubleMatrix. + * + * @since 2.0 + * + * @param[in] value A @c double value to subtract + */ + void SubtractToEachElement(double value); + +private: + /* + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + DoubleMatrix(void); + + bool AllocateCapacity(int rowCount, int columnCount); + void GetMinor(double** pSrc, double** pDest, int rowIndex, int columnIndex, int order) const; + double CalculateDeterminant(double** pMatrix, int order) const; + + friend class _DoubleMatrixImpl; + class _DoubleMatrixImpl* __pImpl; + + double** __pMatrix; + int __row; + int __column; + +}; // DoubleMatrix + +}} // Tizen::Base + +#endif //_FBASE_DOUBLE_MATRIX_H_ diff --git a/inc/FBaseDoubleMatrix3.h b/inc/FBaseDoubleMatrix3.h new file mode 100644 index 0000000..e8c74d4 --- /dev/null +++ b/inc/FBaseDoubleMatrix3.h @@ -0,0 +1,412 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDoubleMatrix3.h + * @brief This is the header file for the %DoubleMatrix3 class. + * + * This header file contains the declarations of the %DoubleMatrix3 class. + * + */ + +#ifndef _FBASE_DOUBLE_MATRIX3_H_ +#define _FBASE_DOUBLE_MATRIX3_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +/** + * @class DoubleMatrix3 + * @brief This class encapsulates a 3 X 3 matrix. + * + * @since 2.0 + * + * The %DoubleMatrix3 class provides a @c double precision, two-dimensional matrix class. + * + */ +class _OSP_EXPORT_ DoubleMatrix3 + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. @n + * Constructs a 3 X 3 null matrix in which all elements are zero. + * + * @since 2.0 + */ + DoubleMatrix3(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %DoubleMatrix3 + */ + DoubleMatrix3(const DoubleMatrix3& rhs); + + /** + * Constructs a 3 by 3 matrix initialized to the value in the specified array. + * + * @since 2.0 + * + * @param[in] matrix The matrix with 9 @c double values + */ + DoubleMatrix3(const double matrix[3][3]); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DoubleMatrix3(void); + + /** + * Checks whether the current instance and the specified instance of %DoubleMatrix3 are equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DoubleMatrix3 + */ + bool operator ==(const DoubleMatrix3& rhs) const; + + /** + * Checks whether the current instance and the specified instance of %DoubleMatrix3 are not equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are not equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DoubleMatrix3 + */ + bool operator !=(const DoubleMatrix3& rhs) const; + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] rhs An instance of %DoubleMatrix3 + */ + DoubleMatrix3& operator =(const DoubleMatrix3& rhs); + + /** + * Assigns the value of the specified instance to the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] value A @c double value to assign + */ + DoubleMatrix3& operator =(double value); + + /** + * Multiplies the value of the specified instance with the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix3 + */ + DoubleMatrix3 operator *(const DoubleMatrix3& rhs) const; + + /** + * Multiplies the value to each matrix members of current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to multiply + */ + DoubleMatrix3 operator *(double value) const; + + /** + * Adds the value of the specified instance and the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix3 + */ + DoubleMatrix3 operator +(const DoubleMatrix3& rhs) const; + + /** + * Adds the value to each matrix members of current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to add + */ + DoubleMatrix3 operator +(double value) const; + + /** + * Subtracts the value of the specified instance and the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix3 + */ + DoubleMatrix3 operator -(const DoubleMatrix3& rhs) const; + + /** + * Subtracts the value from each matrix members of current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to subtract + */ + DoubleMatrix3 operator -(double value) const; + + /** + * Multiplies the value of the specified instance and the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix3 + */ + DoubleMatrix3& operator *=(const DoubleMatrix3& rhs); + + /** + * Multiplies the value to each matrix members of current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to multiply + */ + DoubleMatrix3& operator *=(double value); + + /** + * Adds the value of the specified instance to the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix3 + */ + DoubleMatrix3& operator +=(const DoubleMatrix3& rhs); + + /** + * Adds the value to each matrix members of current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to add + */ + DoubleMatrix3& operator +=(double value); + + /** + * Subtracts the value of the specified instance from the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix3 + */ + DoubleMatrix3& operator -=(const DoubleMatrix3& rhs); + + /** + * Subtracts the value from each matrix members of current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to subtract + */ + DoubleMatrix3& operator -=(double value); + + /** + * Gets the instance of %DoubleMatrix3 resulting from the sum of the value and the specified instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to add + * @param[in] rhs An instance of %DoubleMatrix3 + */ + _OSP_EXPORT_ friend DoubleMatrix3 operator +(const double& value, const DoubleMatrix3& rhs); + + /** + * Gets the instance of %DoubleMatrix3 resulting from the product of the value and the specified instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to multiply + * @param[in] rhs An instance of %DoubleMatrix3 + */ + _OSP_EXPORT_ friend DoubleMatrix3 operator *(const double& value, const DoubleMatrix3& rhs); + + /** + * Gets the instance of %DoubleMatrix3 resulting from the difference between the value and the specified instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @param[in] value A @c double value to subtract + * @param[in] rhs An instance of %DoubleMatrix3 + */ + _OSP_EXPORT_ friend DoubleMatrix3 operator -(const double& value, const DoubleMatrix3& rhs); + + /** + * Checks whether the current instance of %DoubleMatrix3 equals the specified instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return @c true if the values of the current instance is equal to the value of the specified instance, @n + * else @c false + * @param[in] obj An instance of %DoubleMatrix3 + * @remarks This method overrides Tizen::Base::Object::Equals(). This method uses the values of the Matrix components to compare the two instances. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the determinant of the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The determinant value of the current instance + */ + double GetDeterminant(void) const; + + /** + * Gets the inverse matrix of the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + * @remarks This function must be called after checking whether the matrix is invertible or not. + */ + DoubleMatrix3 GetInverse(void) const; + + /** + * Gets the trace of the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return The trace of the current instance + */ + double GetTrace(void) const; + + /** + * Gets the transpose matrix of the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix3 containing the resulting value of the operation + */ + DoubleMatrix3 GetTranspose(void) const; + + /** + * Checks whether the current instance is an identity matrix. + * + * @since 2.0 + * + * @return @c true if the matrix is an identity matrix, @n + * else @c false + */ + bool IsIdentity(void) const; + + /** + * Checks whether the current matrix is invertible. + * + * @since 2.0 + * + * @return @c true if the matrix is invertible, @n + * else @c false + */ + bool IsInvertible(void) const; + + /** + * Negates the matrix members of current instance of %DoubleMatrix3. + * + * @since 2.0 + */ + void Negate(void); + + /** + * Sets the identity matrix to the current instance of %DoubleMatrix3. + * + * @since 2.0 + */ + void SetAsIdentity(void); + + /** + * Sets the inverse matrix to the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not invertible. + */ + result Invert(void); + + /** + * Sets the transposed matrix to the current instance of %DoubleMatrix3. + * + * @since 2.0 + */ + void Transpose(void); + + /** + * Sets the matrix members of current instance of %DoubleMatrix3 to zero. + * + * @since 2.0 + */ + void SetAsNull(void); + + /** + * The matrix of the current instance of %DoubleMatrix3. + * + * @since 2.0 + * + * @remarks The column-major order matrix. + */ + double matrix[3][3]; + +private: + friend class _DoubleMatrix3Impl; + class _DoubleMatrix3Impl* __pImpl; + +}; // DoubleMatrix3 + +}}// Tizen::Base + +#endif //_FBASE_DOUBLE_MATRIX3_H_ diff --git a/inc/FBaseDoubleMatrix4.h b/inc/FBaseDoubleMatrix4.h new file mode 100644 index 0000000..cdeb76e --- /dev/null +++ b/inc/FBaseDoubleMatrix4.h @@ -0,0 +1,412 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDoubleMatrix4.h + * @brief This is the header file for the %DoubleMatrix4 class. + * + * This header file contains the declarations of the %DoubleMatrix4 class. + * + */ + +#ifndef _FBASE_DOUBLE_MATRIX4_H_ +#define _FBASE_DOUBLE_MATRIX4_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +/** + * @class DoubleMatrix4 + * @brief This class encapsulates a 4 X 4 matrix. + * + * @since 2.0 + * + * The %DoubleMatrix4 class provides a @c double precision, two-dimensional matrix class. + * + */ +class _OSP_EXPORT_ DoubleMatrix4 + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. @n + * Constructs a 4 X 4 null matrix in which all elements are zero. + * + * @since 2.0 + */ + DoubleMatrix4(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %DoubleMatrix4 + */ + DoubleMatrix4(const DoubleMatrix4& rhs); + + /** + * Constructs a 4 by 4 matrix initialized to the value in the specified array. + * + * @since 2.0 + * + * @param[in] matrix The matrix with 16 @c double values + */ + DoubleMatrix4(const double matrix[4][4]); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DoubleMatrix4(void); + + /** + * Checks whether the current instance and the specified instance of %DoubleMatrix4 are equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DoubleMatrix4 + */ + bool operator ==(const DoubleMatrix4& rhs) const; + + /** + * Checks whether the current instance and the specified instance of %DoubleMatrix4 are not equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are not equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %DoubleMatrix4 + */ + bool operator !=(const DoubleMatrix4& rhs) const; + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] rhs An instance of %DoubleMatrix4 + */ + DoubleMatrix4& operator =(const DoubleMatrix4& rhs); + + /** + * Assigns the value of the specified instance to the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] value A @c double value to assign + */ + DoubleMatrix4& operator =(double value); + + /** + * Multiplies the value of the specified instance with the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix4 + */ + DoubleMatrix4 operator *(const DoubleMatrix4& rhs) const; + + /** + * Multiplies the value to each matrix members of current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to multiply + */ + DoubleMatrix4 operator *(double value) const; + + /** + * Adds the value of the specified instance and the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix4 + */ + DoubleMatrix4 operator +(const DoubleMatrix4& rhs) const; + + /** + * Adds the value to each matrix members of current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to add + */ + DoubleMatrix4 operator +(double value) const; + + /** + * Subtracts the value of the specified instance and the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix4 + */ + DoubleMatrix4 operator -(const DoubleMatrix4& rhs) const; + + /** + * Subtracts the value from each matrix members of current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to subtract + */ + DoubleMatrix4 operator -(double value) const; + + /** + * Multiplies the value of the specified instance and the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix4 + */ + DoubleMatrix4& operator *=(const DoubleMatrix4& rhs); + + /** + * Multiplies the value to each matrix members of current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to multiply + */ + DoubleMatrix4& operator *=(double value); + + /** + * Adds the value of the specified instance to the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix4 + */ + DoubleMatrix4& operator +=(const DoubleMatrix4& rhs); + + /** + * Adds the value to each matrix members of current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to add + */ + DoubleMatrix4& operator +=(double value); + + /** + * Subtracts the value of the specified instance from the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %DoubleMatrix4 + */ + DoubleMatrix4& operator -=(const DoubleMatrix4& rhs); + + /** + * Subtracts the value from each matrix members of current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The reference to %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to subtract + */ + DoubleMatrix4& operator -=(double value); + + /** + * Gets the instance of %DoubleMatrix4 resulting from the sum of the value and the specified instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to add + * @param[in] rhs An instance of %DoubleMatrix4 + */ + _OSP_EXPORT_ friend DoubleMatrix4 operator +(const double& value, const DoubleMatrix4& rhs); + + /** + * Gets the instance of %DoubleMatrix4 resulting from the product of the value and the specified instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to multiply + * @param[in] rhs An instance of %DoubleMatrix4 + */ + _OSP_EXPORT_ friend DoubleMatrix4 operator *(const double& value, const DoubleMatrix4& rhs); + + /** + * Gets the instance of %DoubleMatrix4 resulting from the difference between the value and the specified instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @param[in] value A @c double value to subtract + * @param[in] rhs An instance of %DoubleMatrix4 + */ + _OSP_EXPORT_ friend DoubleMatrix4 operator -(const double& value, const DoubleMatrix4& rhs); + + /** + * Checks whether the current instance of %DoubleMatrix4 equals the specified instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return @c true if the values of the current instance is equal to the value of the specified instance, @n + * else @c false + * @param[in] obj An instance of %DoubleMatrix4 + * @remarks This method overrides Tizen::Base::Object::Equals(). This method uses the values of the Matrix components to compare the two instances. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the determinant of the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The determinant value of the current instance + */ + double GetDeterminant(void) const; + + /** + * Gets the inverse matrix of the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + * @remarks This function must be called after checking whether the matrix is invertible or not. + */ + DoubleMatrix4 GetInverse(void) const; + + /** + * Gets the trace of the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return The trace of the current instance + */ + double GetTrace(void) const; + + /** + * Gets the transpose matrix of the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return A new instance of %DoubleMatrix4 containing the resulting value of the operation + */ + DoubleMatrix4 GetTranspose(void) const; + + /** + * Checks whether the current instance is an identity matrix. + * + * @since 2.0 + * + * @return @c true if the matrix is an identity matrix, @n + * else @c false + */ + bool IsIdentity(void) const; + + /** + * Checks whether the current matrix is invertible. + * + * @since 2.0 + * + * @return @c true if the matrix is invertible, @n + * else @c false + */ + bool IsInvertible(void) const; + + /** + * Negates the matrix members of current instance of %DoubleMatrix4. + * + * @since 2.0 + */ + void Negate(void); + + /** + * Sets the identity matrix to the current instance of %DoubleMatrix4. + * + * @since 2.0 + */ + void SetAsIdentity(void); + + /** + * Sets the inverse matrix to the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not invertible. + */ + result Invert(void); + + /** + * Sets the transposed matrix to the current instance of %DoubleMatrix4. + * + * @since 2.0 + */ + void Transpose(void); + + /** + * Sets the matrix members of current instance of %DoubleMatrix4 to zero. + * + * @since 2.0 + */ + void SetAsNull(void); + + /** + * The matrix of the current instance of %DoubleMatrix4. + * + * @since 2.0 + * + * @remarks The column-major order matrix. + */ + double matrix[4][4]; + +private: + friend class _DoubleMatrix4Impl; + class _DoubleMatrix4Impl* __pImpl; + +}; // DoubleMatrix4 + +}} // Tizen::Base + +#endif //_FBASE_DOUBLE_MATRIX4_H_ diff --git a/inc/FBaseErrorDefine.h b/inc/FBaseErrorDefine.h new file mode 100644 index 0000000..659687e --- /dev/null +++ b/inc/FBaseErrorDefine.h @@ -0,0 +1,53 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseErrorDefine.h + * @brief This header file defines common error codes. + * + * This header file contains the definitions of error codes. + */ + +#ifndef _FBASE_ERROR_DEFINE_H_ +#define _FBASE_ERROR_DEFINE_H_ + +#include + + +#define E_SEVERITY_POS 31 +#define E_TYPE_POS 29 + +#define SET_E_SEVERITY(X) (static_cast(PUT_MASK(0, (X), E_SEVERITY_POS))) +#define SET_E_TYPE(X) (static_cast(PUT_MASK(0, (X), E_TYPE_POS))) +#define SET_E_CAUSE(X) (static_cast(X)) + + +// Error severities +#define E_SUCCESS (SET_E_SEVERITY(0)) +#define E_FAILURE (SET_E_SEVERITY(1)) + + +// Error types +#define ERR_SRC_FRAMEWORK (E_FAILURE + SET_E_TYPE(1)) +#define ERR_SRC_USER (E_FAILURE + SET_E_TYPE(2)) + + +// Macros for error codes +#define IsFailed(X) (static_cast(X) != E_SUCCESS) + + +#endif //_FBASE_ERROR_DEFINE_H_ diff --git a/inc/FBaseErrors.h b/inc/FBaseErrors.h new file mode 100644 index 0000000..86ac53e --- /dev/null +++ b/inc/FBaseErrors.h @@ -0,0 +1,582 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseErrors.h + * @brief This header file defines error codes. + * + * This header file contains the definitions of error codes. + */ +#ifndef _FBASE_ERRORS_H_ +#define _FBASE_ERRORS_H_ + +#include + + +//----------------------------------------------------------------------------A +/** (specialized) Thrown when network address is changed externally. */ +#define E_ADDRESS_CHANGED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1100)) + +/** Thrown when the target is bounded to another source. */ +#define E_ALREADY_BOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1101)) + +/** Thrown when the target is connected to another source. */ +#define E_ALREADY_CONNECTED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1102)) + +/** Thrown when the target is already opened. */ +#define E_ALREADY_OPENED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1103)) + +/** Thrown when the authentication request fails. */ +#define E_AUTHENTICATION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1104)) + +/** Thrown when the required application is not installed. */ +#define E_APP_NOT_INSTALLED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1105)) + +/** Thrown when the specified instance is already set to other values, instances or resources. */ +#define E_ALREADY_SET (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1106)) + +/** Thrown when a specified account already exists. */ +#define E_ACCOUNT_ALREADY_EXIST (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1107)) + +/** Thrown when a required account does not exist. */ +#define E_ACCOUNT_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1108)) + + +//----------------------------------------------------------------------------B + +//----------------------------------------------------------------------------C +/** (specialized) ... */ +#define E_CHUNKED_TRANSACTION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1300)) + +/** Thrown when the connection is busy, so cannot process the new request. */ +#define E_CONNECTION_BUSY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1301)) + +/** Thrown when the connection to the specific destination fails. */ +#define E_CONNECTION_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1302)) + +/** Thrown when the connection is reset while the other thread is still + * working on it. */ +#define E_CONNECTION_RESET (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1303)) + +/** Thrown when the token is expired. */ +#define E_CREDENTIAL_EXPIRED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1304)) + +/** The server certificate verification has failed. */ +#define E_CERTIFICATE_VERIFICATION_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1305)) + +//----------------------------------------------------------------------------D +/** Thrown when the requested data does not exist. */ +#define E_DATA_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1400)) + +/** Thrown when underlying database system raises exception. */ +#define E_DATABASE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1401)) + +/** Thrown when decoding operation fails. */ +#define E_DECODING_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1402)) + +/** Thrown when the device is processing the previous task, so cannot process + * the new one. */ +#define E_DEVICE_BUSY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1403)) + +/** Thrown when the device fails with unknown reason. */ +#define E_DEVICE_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1404)) + +/** Thrown when the device does not support the specific request. */ +#define E_DEVICE_INCOMPATIBLE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1405)) + +/** Thrown when the device is not installed, or not answering at all. */ +#define E_DEVICE_UNAVAILABLE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1406)) + +/** General DHCP exception. */ +#define E_DHCP (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1407)) + +/** Thrown when the dimension has changed. */ +#define E_DIMENSION_CHANGED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1408)) + +/** General DNS exception. */ +#define E_DNS (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1409)) + +/** Thrown when DNS cannot resolve the requested address. */ +#define E_DNS_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1410)) + +/** Thrown when the data is not enough to generate the processing result. */ +#define E_DATA_NOT_ENOUGH (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1411)) + +//----------------------------------------------------------------------------E +/** Thrown when effects being played on the current haptic device are disabled. */ +#define E_EFFECTS_DISABLED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1500)) + +/** Thrown when a body is empty. */ +#define E_EMPTY_BODY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1501)) + +/** Thrown when encoding operation fails. */ +#define E_ENCODING_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1502)) + +/** Thrown when an end of the file or an end of the stream is reached unexpectedly + * during an input operation. */ +#define E_END_OF_FILE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1503)) + + +//----------------------------------------------------------------------------F +// Thrown when the requested operation fails by undefined reason. +//#define E_FAILURE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1600)) + +/** (specialized) Thrown when application tries to call with a number which is + * not allowed in FDN mode, while the FDN mode is enabled. */ +#define E_FDN_MODE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1600)) + +/** Thrown when an attempt to create the file denoted by a specified pathname + * fails. */ +#define E_FILE_ALREADY_EXIST (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1601)) + +/** Thrown when an attempt to open the file denoted by a specified pathname + * fails. */ +#define E_FILE_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1602)) + + +//----------------------------------------------------------------------------G +/** Thrown when a required group does not exist. */ +#define E_GROUP_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1700)) + + +//----------------------------------------------------------------------------H +/** Thrown the destination host is not found. */ +#define E_HOST_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1800)) + +/** Thrown when the destination host is unreachable. */ +#define E_HOST_UNREACHABLE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1801)) + +/** Thrown the Http transaction is canceled by user. */ +#define E_HTTP_USER (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1802)) + + +//----------------------------------------------------------------------------I +/** Thrown when the user does not have proper permissions. */ +#define E_ILLEGAL_ACCESS (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1900)) + +/** Thrown when the application requests an operation which is in progress. */ +#define E_IN_PROGRESS (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1901)) + +/** Thrown when the return type is supposed to be a file path, but the path is not accessible by the application. */ +#define E_INACCESSIBLE_PATH (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1902)) + +/** Thrown when initialization fails. */ +#define E_INIT_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1903)) + +/** Thrown when an instantiation fails by certain reason. */ +#define E_INSTANTIATION_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1904)) + +/** Thrown when the haptic device priority is lower than that of the current + * effects being played, belonging to another device instance. */ +#define E_INSUFFICIENT_PRIORITY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1905)) + +/** Thrown when a requested operation cannot perform any further due to an + * interruption from other thread. */ +#define E_INTERRUPTED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1906)) + +/** Thrown when an account configuration is invalid. */ +#define E_INVALID_ACCOUNT (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1907)) + +/** Thrown when a given address is invalid or not suitable for a requested + * operation. */ +#define E_INVALID_ADDRESS (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1908)) + +/** Thrown when a combination of passed information is not proper for performing + * the requested operation. */ +#define E_INVALID_ARG (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1909)) + +/** Thrown when a combination of passed information is not proper for performing + * the requested operation. */ +#define E_INVALID_CONDITION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1910)) + +/** Thrown when an operation requests for invalid connection. */ +#define E_INVALID_CONNECTION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1911)) + +/** Thrown when content is invalid. */ +#define E_INVALID_CONTENT (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1912)) + +/** Thrown when context is invalid. */ +#define E_INVALID_CONTEXT (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1913)) + +/** Thrown when the requested (given or referenced) data is invalid. */ +#define E_INVALID_DATA (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1914)) + +/** (specialized) Thrown when the requested (given or referenced) domain is + * invalid. */ +#define E_INVALID_DOMAIN (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1915)) + +/** Thrown when an indicated string contains code pointing outside of bounds by the + * specified character encoding scheme. */ +#define E_INVALID_ENCODING_RANGE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1916)) + +/** Thrown when the specified input has invalid format. */ +#define E_INVALID_FORMAT (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1917)) + +/** (specialized) Thrown when */ +#define E_INVALID_HEADER (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1918)) + +/** Thrown when the specified input has invalid format. */ +#define E_INVALID_KEY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1919)) + +/** Thrown when current state of the instance prohibits the execution of the + * specified operation. */ +#define E_INVALID_OPERATION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1920)) + +/** (specialized) Thrown when the proxy address is invalid. */ +#define E_INVALID_PROXY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1921)) + +/** (specialized) Thrown when the SIM is not in proper state for processing the + * requested operation. */ +#define E_INVALID_SIM_STATE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1922)) + +/** (specialized) Thrown when the DNS request goes to an invalid DNS server. */ +#define E_INVALID_SERVER (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1923)) + +/** Thrown when the relevant session is invalid. */ +#define E_INVALID_SESSION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1924)) + +/** Thrown when the socket which is responsible for the application's request + * is invalid. */ +#define E_INVALID_SOCKET (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1925)) + +/** Thrown when an instance is not in valid state. */ +#define E_INVALID_STATE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1926)) + +/** Thrown when the relevant transaction is invalid. */ +#define E_INVALID_TRANSACTION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1927)) + +/** Thrown when an exception occurs during I/O operations. This is a general + * exception produced by failed or interrupted I/O operations. */ +#define E_IO (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1928)) + +/** Thrown when the client has not joined the domain controller. */ +#define E_NOT_JOINED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1929)) + +/** The server certificate verification has failed on client. */ +#define E_INVALID_CERTIFICATE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1930)) + +/** Thrown when a given url is invalid or not suitable for a requested +* operation. */ +#define E_INVALID_URL (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1931)) + +/** Thrown when the specified user id has invalid format. */ +#define E_INVALID_USER_ID (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1932)) + +/** Thrown when the specified password has invalid format. */ +#define E_INVALID_PASSWORD (ERR_SRC_FRAMEWORK + SET_E_CAUSE(1933)) + + +//----------------------------------------------------------------------------J + +//----------------------------------------------------------------------------K +/** Thrown when a specified key already exists. */ +#define E_KEY_ALREADY_EXIST (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2100)) + +/** Thrown when a required key does not exist. */ +#define E_KEY_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2101)) + +//----------------------------------------------------------------------------L +/** Thrown when an error related to handling landmark occurs. */ +#define E_LANDMARK (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2200)) + +/** Thrown when a specified library does not exists. */ +#define E_LIBRARY_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2201)) + +/** Thrown when a specified library is not loaded. */ +#define E_LIBRARY_NOT_LOADED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2202)) + +/** (specialized) Thrown when a link error occurs. */ +#define E_LINK (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2203)) + +/** Thrown when a Location API specific error has occurred. */ +#define E_LOCATION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2204)) + +/** Thrown when an error related to handling service provider requests has + * occurred. */ +#define E_LOCATION_SERVICE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2205)) + +/** Thrown when locking (or unlocking) fails inside the logic. So cannot + * guarantee synchronous operation. */ +#define E_LOCK_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2206)) + +/** Thrown when the language is not set yet. */ +#define E_LANGUAGE_NOT_SET (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2207)) + +/** Thrown when a location is not available */ +#define E_LOCATION_UNAVAILABLE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2208)) + +//----------------------------------------------------------------------------M +/** Thrown when the defined limit exceeds. */ +#define E_MAX_EXCEEDED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2300)) + +/** Thrown when one or more of the required input is not provided. */ +#define E_MISSING_INPUT (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2301)) + +/** (specialized) ... */ +#define E_MOBILE_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2302)) + +/** (specialized) ... */ +#define E_MODEL_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2303)) + +/** Thrown when a specified member already exists. */ +#define E_MEMBER_ALREADY_EXIST (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2304)) + + +//----------------------------------------------------------------------------N +/** General network exception. */ +#define E_NETWORK_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2400)) + +/** Thrown when the network is not enabled. */ +#define E_NETWORK_UNAVAILABLE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2401)) + +/** Thrown the client certificate is required to connect to the server. */ +#define E_NO_CERTIFICATE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2402)) + +/** Thrown when the operation is permitted only for members, but the current + * user is not. */ +#define E_NOT_A_MEMBER (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2403)) + +/** (specialized) Thrown when Bluetooth pairing is not established. */ +#define E_NOT_PAIRED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2404)) + +/** Thrown when the target is not responding. */ +#define E_NOT_RESPONDING (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2405)) + +/** Thrown when the specified string does not represent valid number. */ +#define E_NUM_FORMAT (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2406)) + +//----------------------------------------------------------------------------O +/** Thrown when the specified instance already exists. */ +#define E_OBJ_ALREADY_EXIST (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2500)) + +/** Thrown when the required instance does not exist. */ +#define E_OBJ_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2501)) + +/** Thrown when the specified instance is already locked. */ +#define E_OBJECT_LOCKED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2502)) + +/** Thrown when any request occurs while the target is still + * initializing. */ +#define E_ON_INITIALIZING (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2503)) + +/** Thrown when the operation is canceled explicitly. */ +#define E_OPERATION_CANCELED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2504)) + +/** Thrown when the operation fails due to certain reason. */ +#define E_OPERATION_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2505)) + +/** Thrown when the memory is not sufficient to perform the requested + * operation. */ +#define E_OUT_OF_MEMORY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2506)) + +/** Thrown when the internal state of the current instance reaches the + * valid range. */ +#define E_OUT_OF_RANGE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2507)) + +/** Thrown when the operation has caused an overflow. */ +#define E_OVERFLOW (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2508)) + +/** Thrown when OpenGL operation failed. */ +#define E_OPENGL_ERROR (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2509)) + + +//----------------------------------------------------------------------------P +/** (specialized) Thrown when the requested Bluetooth pairing fails. */ +#define E_PAIRING_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2600)) + +/** Thrown when the parsing fails due to any reason. */ +#define E_PARSING_FAILED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2601)) + +/** Thrown when an application invokes an API without a proper privilege. */ +#define E_PRIVILEGE_DENIED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2602)) + +/** Thrown when the package is not installed. */ +#define E_PKG_NOT_INSTALLED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2603)) + +//----------------------------------------------------------------------------Q + +//----------------------------------------------------------------------------R +/** Thrown when a write operation is requested for an instance in read only + * mode. */ +#define E_READ_ONLY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2800)) + +/** Thrown when the operation is rejected by remote site. */ +#define E_REJECTED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2801)) + +/** (not used) */ +#define E_REMOTE_DEVICE_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2802)) + +/** (not used) */ +#define E_REMOVE_SERVICE_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2803)) + +/** Thrown when the required resource is currently unavailable. */ +#define E_RESOURCE_UNAVAILABLE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2804)) + +/** Thrown when the right to get served has expired. */ +#define E_RIGHT_EXPIRED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2805)) + +/** Thrown when there is no right. */ +#define E_RIGHT_NO_LICENSE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2806)) + +/** Thrown when the right is for future use. */ +#define E_RIGHT_FUTURE_USE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2807)) + + +//----------------------------------------------------------------------------S +/** Thrown when the specified section already exists. */ +#define E_SECTION_ALREADY_EXIST (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2900)) + +/** Thrown when the required section does not exist. */ +#define E_SECTION_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2901)) + +/** Thrown when a server tells the device that operation failed due to some + * reason. Detailed message will be followed by - error code and an error message. */ +#define E_SERVER (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2902)) + +/** Thrown when the dedicated service module is too busy to handle another + * request. */ +#define E_SERVICE_BUSY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2903)) + +/** Thrown when the specific service is restricted by policy. */ +#define E_SERVICE_LIMITED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2904)) + +/** Thrown when a service is locked. */ +#define E_SERVICE_LOCKED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2905)) + +/** Thrown when the dedicated service is not available. */ +#define E_SERVICE_UNAVAILABLE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2906)) + +/** Thrown when the base session is deactivated while it's still being used. */ +#define E_SESSION_DEACTIVATED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2907)) + +/** (not used) */ +#define E_SESSION_UNAVAILABLE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2908)) + +/** (not used) */ +#define E_SIZE_MISMATCH (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2909)) + +/** The socket connection closed by user. */ +#define E_SOCKET_USER (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2910)) + +/** Thrown when the storage is full. */ +#define E_STORAGE_FULL (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2911)) + +/** Thrown when the specified symbol is not found. */ +#define E_SYMBOL_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2912)) + +/** Thrown when the input statement does not confirm to the specific syntax. */ +#define E_SYNTAX (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2913)) + +/** Thrown when a failure occurs from the underlying system. */ +#define E_SYSTEM (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2914)) + +/** Thrown when a service is deactivated. */ +#define E_SERVICE_DEACTIVATED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(2915)) + + +//----------------------------------------------------------------------------T +/** (specialized) Thrown then the specified table does not exist. */ +#define E_TABLE_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3000)) + +/** Thrown when the operation can not be completed within the specified time + * period. */ +#define E_TIMEOUT (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3001)) + +/** Thrown when the specified type does not match. */ +#define E_TYPE_MISMATCH (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3002)) + + +//----------------------------------------------------------------------------U +/** Thrown when the operation causes an underflow. */ +#define E_UNDERFLOW (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3100)) + +/** Thrown when a unknown error occurs. */ +#define E_UNKNOWN (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3101)) + +/** Thrown when the specified algorithm is not supported. */ +#define E_UNSUPPORTED_ALGORITHM (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3102)) + +/** Thrown when the required CODEC is not found. */ +#define E_UNSUPPORTED_CODEC (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3103)) + +/** (specialized) Thrown when the requested address family is not supported. */ +#define E_UNSUPPORTED_FAMILY (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3104)) + +/** Thrown when the current implementation does not support the format of the + * input. */ +#define E_UNSUPPORTED_FORMAT (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3105)) + +/** Thrown when the specified protocol is not supported. */ +#define E_UNSUPPORTED_PROTOCOL (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3106)) + +/** Thrown when the current implementation does not support the requested + * operation. */ +#define E_UNSUPPORTED_OPERATION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3107)) + +/** Thrown when the specified option is not supported. */ +#define E_UNSUPPORTED_OPTION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3108)) + +/** Thrown when the specified service is not supported. */ +#define E_UNSUPPORTED_SERVICE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3109)) + +/** Thrown when the specified type is not supported. */ +#define E_UNSUPPORTED_TYPE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3110)) + +/** Thrown when the URL is changed. */ +#define E_URL_CHANGED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3111)) + +/** (specialized) used by HTTP transaction. */ +#define E_USER_AGENT_NOT_ALLOWED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3112)) + +/** Thrown when a user is already registered to the device. */ +#define E_USER_ALREADY_REGISTERED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3113)) + +/** Thrown when the required user does not exist. */ +#define E_USER_NOT_FOUND (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3114)) + +/** Thrown when no user is registered to the device yet. */ +#define E_USER_NOT_REGISTERED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3115)) + +/** Thrown when the specified language is not supported. */ +#define E_UNSUPPORTED_LANGUAGE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3116)) + +/** Thrown when the specified version of the input content is not supported. */ +#define E_UNSUPPORTED_VERSION (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3117)) + +/** Thrown when the specified locale is not supported. */ +#define E_UNSUPPORTED_LOCALE (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3118)) + +/** Thrown when the user blocks an application from using the user information. */ +#define E_USER_NOT_CONSENTED (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3119)) + +//----------------------------------------------------------------------------V + +//----------------------------------------------------------------------------W +/** (specialized) Thrown when non-blocking socket operation could not be + * completed immediately. */ +#define E_WOULD_BLOCK (ERR_SRC_FRAMEWORK + SET_E_CAUSE(3300)) + +//----------------------------------------------------------------------------X + +//----------------------------------------------------------------------------Y + +//----------------------------------------------------------------------------Z + + +//----------------------------------------------------------------------------- + +#endif // _FBASE_ERRORS_H_ diff --git a/inc/FBaseFloat.h b/inc/FBaseFloat.h new file mode 100644 index 0000000..1415f3b --- /dev/null +++ b/inc/FBaseFloat.h @@ -0,0 +1,402 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloat.h + * @brief This is the header file for the %Float class. + * + * @see Tizen::Base::Number + * + * This header file contains the declarations of the %Float class. + */ +#ifndef _FBASE_FLOAT_H_ +#define _FBASE_FLOAT_H_ + +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Float + * @brief This class is the wrapper class for the @c signed @c float built-in type. + * + * @since 2.0 + * + * The %Float class represents a single-precision 32-bit floating number. The %Float class wraps a @c float type value. This enables + * passing a @c float value to a method that only accepts an instance of Object class. This class provides methods to compare instances + * of this type, convert the value of an instance to its string representation, and convert the string representation + * of a number to an instance of this type. + * + * The following example demonstrates how to use the %Float class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method checks whether the given string object contains the string + * // representation of the pre-defined minimum float value. + * result + * MyClass::Verify(String& string, bool& out) + * { + * // Creates and initializes an instance of Double + * static const Float MINIMUM(1.23L); + * + * result r = E_SUCCESS; + * + * float f; + * + * // Parses the string representation of the numeric value + * // Returns f (value as signed float) + * r = Float::Parse(string, f); + * + * // Error Handling + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * out = (MINIMUM.CompareTo(f) == 0) ? true: false; + * return r; + * CATCH: + * return r; + * } + * @endcode + */ +class _OSP_EXPORT_ Float + : public Number +{ +public: + /** + * Initializes this instance of %Float with the specified value. + * + * @since 2.0 + * + * @param[in] value A @c float value + */ + Float(float value = 0.0); + + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %Float + */ + Float(const Float& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Float(void); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %Float + */ + Float& operator =(const Float& rhs); + + /** + * Compares two @c float values. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of @c f1 is less than the value of @c f2 + * == 0 if the value of @c f1 is equal to the value of @c f2 + * > 0 if the value of @c f1 is greater than the value of @c f2 + * @endcode + * @param[in] f1 The first @c float value to compare + * @param[in] f2 The second @c float value to compare + */ + static int Compare(float f1, float f2); + + /** + * Compares the value of the current instance with the value of the specified instance of the %Float class. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * @li < 0 if the value of the current instance is less than the value of the specified instance + * @li == 0 if the value of the current instance is equal to the value of the specified instance + * @li > 0 if the value of the current instance is greater than the value of the specified instance + * @endcode + * @param[in] value An instance of the %Float class to compare + */ + int CompareTo(const Float& value) const; + + /** + * Checks whether the value of the specified instance of Object is equal to the value of the current instance of %Float. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of Object is equal to the value of the current instance of %Float, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @see Tizen::Base::Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + + /** + * Gets the hash value of the current instance of %Float. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance of %Float + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the value of the current instance. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the hash value of the specified @c float value. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the specified @c float value + * @param[in] val A @c float value to get the hash value + */ + static int GetHashCode(float val); + + /** + * Parses the specified string representing a numeric value and returns the value as @c signed @c float (as out parameter). + * + * @since 2.0 + * + * @return An error code + * @param[in] s A unicode string representing a @c signed @c float value + * @param[out] ret The numeric representation of the string + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @see Tizen::Base::Double::Parse() + */ + static result Parse(const String& s, float& ret); + + /** + * Gets the @c signed @c char equivalent of the current instance of the %Float class. + * + * @since 2.0 + * + * @return A @c signed @c char equivalent of the current instance + */ + virtual char ToChar(void) const; + + /** + * Gets the @c signed @c short equivalent of the current instance of the %Float class. + * + * @since 2.0 + * + * @return A @c signed @c short equivalent of the current instance + */ + virtual short ToShort(void) const; + + /** + * Gets the @c signed @c int equivalent of the current instance of the %Float class. + * + * @since 2.0 + * + * @return A @c signed @c int equivalent of the current instance + */ + virtual int ToInt(void) const; + + /** + * Gets the @c signed @c long equivalent of the current instance of the %Float class. + * + * @since 2.0 + * + * @return A @c signed @c long equivalent of the current instance + */ + virtual long ToLong(void) const; + + /** + * Gets the @c signed @c long @c long equivalent of the current instance of the %Float class. + * + * @since 2.0 + * + * @return A @c signed @c long @c long equivalent of the current instance + */ + virtual long long ToLongLong(void) const; + + /** + * Gets the @c signed @c float equivalent of the current instance of the %Float class. + * + * @since 2.0 + * + * @return A @c signed @c float equivalent of the current instance + */ + virtual float ToFloat(void) const; + + /** + * Gets the @c signed @c double equivalent of the current instance of the %Float class. + * + * @since 2.0 + * + * @return A @c signed @c double equivalent of the current instance + */ + virtual double ToDouble(void) const; + + /** + * Gets the string representing the value of the current instance of %Float. + * + * @since 2.0 + * + * @return A string containing a Unicode representation of the value of the current instance + * @remarks If the value is Not-a-Number (NaN), the result is the string "NaN". Furthermore, infinity + * produces the result "Infinity". @n + * 6 digits are given for the precision of this method. Use String::Format() to set the specific precision. + */ + virtual String ToString(void) const; + + /** + * Gets the string representing the specified @c float value. + * + * @since 2.0 + * + * @return A string containing a Unicode representation of the specified @c float value + * @param[in] value A @c float value to convert + * @remarks If the value is Not-a-Number (NaN), the result is the string "NaN". Furthermore, infinity + * produces the result "Infinity". @n + * 6 digits are given for the precision of this method. Use String::Format() to set the specific precision. + */ + static String ToString(float value); + + /** + * Gets the IEEE 754 floating-point "single format" bit layout representation of the specified @c float value. + * + * @since 2.0 + * + * @return The bits that represent the floating-point number in the IEEE 754 floating-point "single format" bit layout + * @param[in] value A @c float value to convert + * @see Tizen::Base::Double::Parse() + */ + static int ToBits(float value); + + /** + * Gets the @c float value corresponding to the specified floating-point value in the IEEE 754 floating-point "single format" bit layout. + * + * @since 2.0 + * + * @return The @c float floating-point value with the same bit pattern + * @param[in] value A floating-point value in the IEEE 754 floating-point "single format" bit layout + * @see Tizen::Base::Double::Parse() + */ + static float ToFloatFromBits(int value); + + /** + * Checks whether the current value of %Float is equal to negative or positive infinity. + * + * @since 2.0 + * + * @return @c true if the current value equals negative or positive infinity, @n + * else @c false + */ + bool IsInfinity(void) const; + + /** + * Checks whether the specified @c float value is equal to negative or positive infinity. + * + * @since 2.0 + * + * @return @c true if the specified value equals negative or positive infinity, @n + * else @c false + * @param[in] value A @c float value to check + */ + static bool IsInfinity(float value); + + /** + * Checks whether the current value is Not-a-Number. + * + * @since 2.0 + * + * @return @c true if the current value is Not-a-Number, @n + * else @c false + */ + bool IsNaN(void) const; + + /** + * Checks whether the specified value is Not-a-Number. + * + * @since 2.0 + * + * @return @c true if the specified value is Not-a-Number, @n + * else @c false + * @param[in] value A @c float value to check + */ + static bool IsNaN(float value); + + /** + * Gets a constant holding the largest positive finite value of type @c float. @n + * This is equal to the value defined in Limit.h of the C library. + * + * @since 2.0 + * + * @return A constant holding the largest positive finite value of type @c float + */ + static float GetMaxValue(void); + + /** + * Gets a constant holding the smallest positive non-zero value of type @c float. @n + * This is equal to the value defined in Limit.h of the C library. + * + * @since 2.0 + * + * @return A constant holding the smallest possible non-zero value of type @c float + */ + static float GetMinValue(void); + + /** + * A @c float value of this instance. + * + * @since 2.0 + */ + float value; + + +private: + /** + * Checks if the specified @c float value is finite. + * + * @since 2.0 + * + * @return @c true if the specified value is finite, @n + * else @c false + * @param[in] value A @c float value to check + */ + static bool IsFinite(float value); + + static const int __DBL_MAX_10_EXP = 308; + + friend class _FloatImpl; + class _FloatImpl * __pFloatImpl; + +}; // Float + +}} // Tizen::Base + +#endif //_FBASE_FLOAT_H_ diff --git a/inc/FBaseFloatComparer.h b/inc/FBaseFloatComparer.h new file mode 100644 index 0000000..04c67d4 --- /dev/null +++ b/inc/FBaseFloatComparer.h @@ -0,0 +1,129 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloatComparer.h + * @brief This is the header file for the %FloatComparer class. + * + * @see Float and Tizen::Base::Collection::IComparer + * + * This header file contains the declarations of the %FloatComparer class. + */ +#ifndef _FBASE_FLOAT_COMPARER_H_ +#define _FBASE_FLOAT_COMPARER_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class FloatComparer + * @brief This class checks for equivalence between 2 instances of the Float type. + * + * @since 2.0 + * + * The %FloatComparer class checks for equivalence between 2 instances of the Float type. + * + * For more information on the class features, see Collection Comparisons. + * + * The following example demonstrates how to use the %FloatComparer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::FloatComparerSample(void) + * { + * Float f1(123); + * Float f2(124); + * FloatComparer comparer; + * + * // Compares 2 instances of Float + * int cmp; + * comparer.Compare(f1, f2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +class _OSP_EXPORT_ FloatComparer + : public Object + , public Tizen::Base::Collection::IComparer +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + FloatComparer(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~FloatComparer(void); + + /** + * Compares two given instances of type Float. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 The first instance of type Float + * @param[in] obj2 The second instance of type Float + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + FloatComparer(const FloatComparer& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + FloatComparer& operator =(const FloatComparer& rhs); + + friend class _FloatComparerImpl; + class _FloatComparerImpl * __pFloatComparerImpl; + +}; // FloatComparer + +}} // Tizen::Base + +#endif // _FBASE_FLOAT_COMPARER_H_ diff --git a/inc/FBaseFloatMatrix.h b/inc/FBaseFloatMatrix.h new file mode 100644 index 0000000..9c0a11d --- /dev/null +++ b/inc/FBaseFloatMatrix.h @@ -0,0 +1,466 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloatMatrix.h + * @brief This is the header file for the %FloatMatrix class. + * + * This header file contains the declarations of the %FloatMatrix class. + * + */ + +#ifndef _FBASE_FLOAT_MATRIX_H_ +#define _FBASE_FLOAT_MATRIX_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +/** + * @class FloatMatrix + * @brief This class encapsulates a two-dimensional matrix. + * + * @since 2.0 + * + * The %FloatMatrix class provides a @c float precision, two-dimensional matrix class. + * + */ +class _OSP_EXPORT_ FloatMatrix + : public Tizen::Base::Object +{ +public: + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %FloatMatrix + */ + FloatMatrix(const FloatMatrix& rhs); + + /** + * Constructs a row by column null matrix in which all elements are zero. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + */ + FloatMatrix(int rowCount, int columnCount); + + /** + * Constructs a row by column matrix initialized to the values in the specified array. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + * @param[in] pArray A one-dimensional array @n The array must be at least row * column in length. + * @param[in] rowMajor Set to @c true to copy the array in row-major order, @n + * else @c copy in column-major order + */ + FloatMatrix(int rowCount, int columnCount, const float* pArray, bool rowMajor = true); + + /** + * Constructs a row by column matrix initialized to the values in the specified array. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + * @param[in] pArray[] A two-dimensional array @n The array must be at least row * column in length. + */ + FloatMatrix(int rowCount, int columnCount, const float* pArray[]); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~FloatMatrix(void); + + /** + * Checks whether the current instance and the specified instance of %FloatMatrix are equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %FloatMatrix + */ + bool operator ==(const FloatMatrix& rhs) const; + + /** + * Checks whether the current instance and the specified instance of %FloatMatrix are not equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are not equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %FloatMatrix + */ + bool operator !=(const FloatMatrix& rhs) const; + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] rhs An instance of %FloatMatrix + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If either row or column count of the current instance is not same with that of the specified instance, + * return the reference to this instance without assigning. + */ + FloatMatrix& operator =(const FloatMatrix& rhs); + + /** + * Checks whether the current instance of %FloatMatrix equals the specified instance of %FloatMatrix. + * + * @since 2.0 + * + * @return @c true if the values of the current instance are equal to the value of the specified instance, @n + * else @c false + * @param[in] obj An instance of %FloatMatrix + * @remarks This method overrides Tizen::Base::Object::Equals(). This method uses the values of the Matrix components to compare the two instances. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Adds the value of the specified instance to the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %FloatMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + */ + result Add(const FloatMatrix& matrix); + + /** + * Adds the value to each matrix members of current instance of %FloatMatrix. + * + * @since 2.0 + * + * @param[in] value A @c float value to add + */ + void AddToEachElement(float value); + + /** + * Gets the number of column in the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return The number of column in the current instance + */ + int GetColumnCount(void) const; + + /** + * Gets a new array that includes the values of the specified column in the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return A pointer to float array + * @param[in] columnIndex The target column number in the current instance + * @exception E_INVALID_ARG The @c columnIndex is larger than the column count of the current instance. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + float* GetColumnN(int columnIndex) const; + + /** + * Gets the determinant of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return The determinant value of the current instance + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the current instance is not a square matrix, return zero. + */ + float GetDeterminant(void) const; + + /** + * Gets the value at the specified row and column of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return The value at the specified row and column of the current instance + * @param[in] rowIndex The target row number in the current instance + * @param[in] columnIndex The target column number in the current instance + * @exception E_INVALID_ARG The @c columnIndex or @c rowIndex is larger than that of the current instance. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + float GetElement(int rowIndex, int columnIndex) const; + + /** + * Gets the inverse matrix of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return A pointer to the instance of %FloatMatrix containing the resulting value of the operation + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + FloatMatrix* GetInverseN(void) const; + + /** + * Gets the number of row in the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return The number of row in the current instance + */ + int GetRowCount(void) const; + + /** + * Gets a new array that includes the values of the specified row in the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return A pointer to @c float array + * @param[in] rowIndex The target row number in the current instance + * @exception E_INVALID_ARG The @c rowIndex is larger than the row count of the current instance. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + float* GetRowN(int rowIndex) const; + + /** + * Gets the trace of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[out] value A @c float value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result GetTrace(float& value) const; + + /** + * Gets the transpose matrix of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return A pointer to the instance of %FloatMatrix containing the resulting value of the operation + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + FloatMatrix* GetTransposeN(void) const; + + /** + * Checks whether the current instance is an identity matrix. + * + * @since 2.0 + * + * @return @c true if the matrix is an identity matrix, @n + * else @c false + */ + bool IsIdentity(void) const; + + /** + * Checks whether the current matrix is invertible. + * + * @since 2.0 + * + * @return @c true if the matrix is invertible, @n + * else @c false + */ + bool IsInvertible(void) const; + + /** + * Multiplies the value of the specified instance with the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %FloatMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The column count of the current instance is not same with the row count of the specified instance. + */ + result Multiply(const FloatMatrix& matrix); + + /** + * Multiplies the value to each matrix members of current instance of %FloatMatrix. + * + * @since 2.0 + * + * @param[in] value A @c float value to multiply + */ + void Multiply(float value); + + /** + * Negates the matrix members of current instance of %FloatMatrix. + * + * @since 2.0 + */ + void Negate(void); + + /** + * Sets the value of the current instance of %FloatMatrix to its identity. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result SetAsIdentity(void); + + /** + * Sets the value of the current instance of %FloatMatrix to its inverse. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result Invert(void); + + /** + * Sets the value of the current instance of %FloatMatrix to its transpose. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result Transpose(void); + + /** + * Sets the values of the specified array to the specified column of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The target column number in the current instance + * @param[in] pArray An array which includes the values @n The array must be at least row in length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c pArray is @c null, or the @c columnIndex is larger than the column count of the current instance. + */ + result SetColumn(int columnIndex, const float* pArray); + + /** + * Sets the values of the specified array to the specified row of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] rowIndex The target row number in the current instance + * @param[in] pArray An array which includes the values @n The array must be at least column in length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c pArray is @c null, or the @c rowIndex is larger than the row count of the current instance. + */ + result SetRow(int rowIndex, const float* pArray); + + /** + * Sets the value to the specified row and column of the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] rowIndex The target row number in the current instance + * @param[in] columnIndex The target column number in the current instance + * @param[in] value A @c float value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The pArray is @c null, or the @c rowIndex is larger than the row count of the current instance, + * or the @c columnIndex is larger than the column count of the current instance. + */ + result SetElement(int rowIndex, int columnIndex, float value); + + /** + * Sets the values to the current instance of %FloatMatrix in either the row-major or column-major order. + * + * @since 2.0 + * + * @return An error code + * @param[in] pArray A one-dimensional array @n The array must be at least row * column in length. + * @param[in] rowMajor Set to @c true to copy the array in row-major order, @n + * else @c false to copy in column-major order + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The pArray is @c null. + */ + result SetValue(const float* pArray, bool rowMajor = true); + + /** + * Sets the matrix members of current instance of %FloatMatrix to zero. + * + * @since 2.0 + */ + void SetAsNull(void); + + /** + * Subtracts the value of the specified instance from the current instance of %FloatMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %FloatMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + */ + result Subtract(const FloatMatrix& matrix); + + /** + * Subtracts the value from each matrix members of current instance of %FloatMatrix. + * + * @since 2.0 + * + * @param[in] value A @c float value to subtract + */ + void SubtractToEachElement(float value); + +private: + /* + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + FloatMatrix(void); + + bool AllocateCapacity(int rowCount, int columnCount); + void GetMinor(float** pSrc, float** pDest, int rowIndex, int columnIndex, int order) const; + float CalculateDeterminant(float** pMatrix, int order) const; + + friend class _FloatMatrixImpl; + class _FloatMatrixImpl* __pImpl; + + float** __pMatrix; + int __row; + int __column; + +}; // FloatMatrix + +}} // Tizen::Base + +#endif //_FBASE_FLOAT_MATRIX_H_ diff --git a/inc/FBaseFloatMatrix3.h b/inc/FBaseFloatMatrix3.h new file mode 100644 index 0000000..9d20e63 --- /dev/null +++ b/inc/FBaseFloatMatrix3.h @@ -0,0 +1,412 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloatMatrix3.h + * @brief This is the header file for the %FloatMatrix3 class. + * + * This header file contains the declarations of the %FloatMatrix3 class. + * + */ + +#ifndef _FBASE_FLOAT_MATRIX3_H_ +#define _FBASE_FLOAT_MATRIX3_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +/** + * @class FloatMatrix3 + * @brief This class encapsulates a 3 X 3 matrix. + * + * @since 2.0 + * + * The %FloatMatrix3 class provides a @c float precision, two-dimensional matrix class. + * + */ +class _OSP_EXPORT_ FloatMatrix3 + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. @n + * Constructs a 3 X 3 null matrix in which all elements are zero. + * + * @since 2.0 + */ + FloatMatrix3(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %FloatMatrix3 + */ + FloatMatrix3(const FloatMatrix3& rhs); + + /** + * Constructs a 3 by 3 matrix initialized to the value in the specified array. + * + * @since 2.0 + * + * @param[in] matrix The matrix with 9 @c float values + */ + FloatMatrix3(const float matrix[3][3]); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~FloatMatrix3(void); + + /** + * Checks whether the current instance and the specified instance of %FloatMatrix3 are equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %FloatMatrix3 + */ + bool operator ==(const FloatMatrix3& rhs) const; + + /** + * Checks whether the current instance and the specified instance of %FloatMatrix3 are not equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are not equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %FloatMatrix3 + */ + bool operator !=(const FloatMatrix3& rhs) const; + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] rhs An instance of %FloatMatrix3 + */ + FloatMatrix3& operator =(const FloatMatrix3& rhs); + + /** + * Assigns the value of the specified instance to the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] value A @c float value to assign + */ + FloatMatrix3& operator =(float value); + + /** + * Multiplies the value of the specified instance with the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix3 + */ + FloatMatrix3 operator *(const FloatMatrix3& rhs) const; + + /** + * Multiplies the value to each matrix members of current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to multiply + */ + FloatMatrix3 operator *(float value) const; + + /** + * Adds the value of the specified instance and the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix3 + */ + FloatMatrix3 operator +(const FloatMatrix3& rhs) const; + + /** + * Adds the value to each matrix members of current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to add + */ + FloatMatrix3 operator +(float value) const; + + /** + * Subtracts the value of the specified instance and the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix3 + */ + FloatMatrix3 operator -(const FloatMatrix3& rhs) const; + + /** + * Subtracts the value from each matrix members of current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to subtract + */ + FloatMatrix3 operator -(float value) const; + + /** + * Multiplies the value of the specified instance and the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix3 + */ + FloatMatrix3& operator *=(const FloatMatrix3& rhs); + + /** + * Multiplies the value to each matrix members of current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to multiply + */ + FloatMatrix3& operator *=(float value); + + /** + * Adds the value of the specified instance to the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix3 + */ + FloatMatrix3& operator +=(const FloatMatrix3& rhs); + + /** + * Adds the value to each matrix members of current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to add + */ + FloatMatrix3& operator +=(float value); + + /** + * Subtracts the value of the specified instance from the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix3 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix3 + */ + FloatMatrix3& operator -=(const FloatMatrix3& rhs); + + /** + * Subtracts the value from each matrix members of current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to subtract + */ + FloatMatrix3& operator -=(float value); + + /** + * Gets the instance of %FloatMatrix3 resulting from the sum of the value and the specified instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to add + * @param[in] rhs An instance of %FloatMatrix3 + */ + _OSP_EXPORT_ friend FloatMatrix3 operator +(const float& value, const FloatMatrix3& rhs); + + /** + * Gets the instance of %FloatMatrix3 resulting from the product of the value and the specified instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to multiply + * @param[in] rhs An instance of %FloatMatrix3 + */ + _OSP_EXPORT_ friend FloatMatrix3 operator *(const float& value, const FloatMatrix3& rhs); + + /** + * Gets the instance of %FloatMatrix3 resulting from the difference between the value and the specified instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @param[in] value A @c float value to subtract + * @param[in] rhs An instance of %FloatMatrix3 + */ + _OSP_EXPORT_ friend FloatMatrix3 operator -(const float& value, const FloatMatrix3& rhs); + + /** + * Checks whether the current instance of %FloatMatrix3 equals the specified instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return @c true if the values of the current instance is equal to the value of the specified instance, @n + * else @c false + * @param[in] obj An instance of %FloatMatrix3 + * @remarks This method overrides Tizen::Base::Object::Equals(). This method uses the values of the Matrix components to compare the two instances. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the determinant of the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The determinant value of the current instance + */ + float GetDeterminant(void) const; + + /** + * Gets the inverse matrix of the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + * @remarks This function must be called after checking whether the matrix is invertible or not. + */ + FloatMatrix3 GetInverse(void) const; + + /** + * Gets the trace of the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return The trace of the current instance + */ + float GetTrace(void) const; + + /** + * Gets the transpose matrix of the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix3 containing the resulting value of the operation + */ + FloatMatrix3 GetTranspose(void) const; + + /** + * Checks whether the current instance is an identity matrix. + * + * @since 2.0 + * + * @return @c true if the matrix is an identity matrix, @n + * else @c false + */ + bool IsIdentity(void) const; + + /** + * Checks whether the current matrix is invertible. + * + * @since 2.0 + * + * @return @c true if the matrix is invertible, @n + * else @c false + */ + bool IsInvertible(void) const; + + /** + * Negates the matrix members of current instance of %FloatMatrix3. + * + * @since 2.0 + */ + void Negate(void); + + /** + * Sets the identity matrix to the current instance of %FloatMatrix3. + * + * @since 2.0 + */ + void SetAsIdentity(void); + + /** + * Sets the inverse matrix to the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not invertible. + */ + result Invert(void); + + /** + * Sets the transposed matrix to the current instance of %FloatMatrix3. + * + * @since 2.0 + */ + void Transpose(void); + + /** + * Sets the matrix members of current instance of %FloatMatrix3 to zero. + * + * @since 2.0 + */ + void SetAsNull(void); + + /** + * The matrix of the current instance of %FloatMatrix3. + * + * @since 2.0 + * + * @remarks The column-major order matrix. + */ + float matrix[3][3]; + +private: + friend class _FloatMatrix3Impl; + class _FloatMatrix3Impl* __pImpl; + +}; // FloatMatrix3 + +}}// Tizen::Base + +#endif //_FBASE_FLOAT_MATRIX3_H_ diff --git a/inc/FBaseFloatMatrix4.h b/inc/FBaseFloatMatrix4.h new file mode 100644 index 0000000..d19a64f --- /dev/null +++ b/inc/FBaseFloatMatrix4.h @@ -0,0 +1,412 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloatMatrix4.h + * @brief This is the header file for the %FloatMatrix4 class. + * + * This header file contains the declarations of the %FloatMatrix4 class. + * + */ + +#ifndef _FBASE_FLOAT_MATRIX4_H_ +#define _FBASE_FLOAT_MATRIX4_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +/** + * @class FloatMatrix4 + * @brief This class encapsulates a 4 X 4 matrix. + * + * @since 2.0 + * + * The %FloatMatrix4 class provides a @c float precision, two-dimensional matrix class. + * + */ +class _OSP_EXPORT_ FloatMatrix4 + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. @n + * Constructs a 4 X 4 null matrix in which all elements are zero. + * + * @since 2.0 + */ + FloatMatrix4(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %FloatMatrix4 + */ + FloatMatrix4(const FloatMatrix4& rhs); + + /** + * Constructs a 4 by 4 matrix initialized to the value in the specified array. + * + * @since 2.0 + * + * @param[in] matrix The matrix with 16 @c float values + */ + FloatMatrix4(const float matrix[4][4]); + + /** + * TThis destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~FloatMatrix4(void); + + /** + * Checks whether the current instance and the specified instance of %FloatMatrix4 are equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %FloatMatrix4 + */ + bool operator ==(const FloatMatrix4& rhs) const; + + /** + * Checks whether the current instance and the specified instance of %FloatMatrix4 are not equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are not equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %FloatMatrix4 + */ + bool operator !=(const FloatMatrix4& rhs) const; + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] rhs An instance of %FloatMatrix4 + */ + FloatMatrix4& operator =(const FloatMatrix4& rhs); + + /** + * Assigns the value of the specified instance to the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] value A @c float value to assign + */ + FloatMatrix4& operator =(float value); + + /** + * Multiplies the value of the specified instance with the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix4 + */ + FloatMatrix4 operator *(const FloatMatrix4& rhs) const; + + /** + * Multiplies the value to each matrix members of current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to multiply + */ + FloatMatrix4 operator *(float value) const; + + /** + * Adds the value of the specified instance and the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix4 + */ + FloatMatrix4 operator +(const FloatMatrix4& rhs) const; + + /** + * Adds the value to each matrix members of current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to add + */ + FloatMatrix4 operator +(float value) const; + + /** + * Subtracts the value of the specified instance and the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix4 + */ + FloatMatrix4 operator -(const FloatMatrix4& rhs) const; + + /** + * Subtracts the value from each matrix members of current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to subtract + */ + FloatMatrix4 operator -(float value) const; + + /** + * Multiplies the value of the specified instance and the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix4 + */ + FloatMatrix4& operator *=(const FloatMatrix4& rhs); + + /** + * Multiplies the value to each matrix members of current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to multiply + */ + FloatMatrix4& operator *=(float value); + + /** + * Adds the value of the specified instance to the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix4 + */ + FloatMatrix4& operator +=(const FloatMatrix4& rhs); + + /** + * Adds the value to each matrix members of current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to add + */ + FloatMatrix4& operator +=(float value); + + /** + * Subtracts the value of the specified instance from the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix4 containing the resulting value of the operation + * @param[in] rhs An instance of %FloatMatrix4 + */ + FloatMatrix4& operator -=(const FloatMatrix4& rhs); + + /** + * Subtracts the value from each matrix members of current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The reference to %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to subtract + */ + FloatMatrix4& operator -=(float value); + + /** + * Gets the instance of %FloatMatrix4 resulting from the sum of the value and the specified instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to add + * @param[in] rhs An instance of %FloatMatrix4 + */ + _OSP_EXPORT_ friend FloatMatrix4 operator +(const float& value, const FloatMatrix4& rhs); + + /** + * Gets the instance of %FloatMatrix4 resulting from the product of the value and the specified instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to multiply + * @param[in] rhs An instance of %FloatMatrix4 + */ + _OSP_EXPORT_ friend FloatMatrix4 operator *(const float& value, const FloatMatrix4& rhs); + + /** + * Gets the instance of %FloatMatrix4 resulting from the difference between the value and the specified instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @param[in] value A @c float value to subtract + * @param[in] rhs An instance of %FloatMatrix4 + */ + _OSP_EXPORT_ friend FloatMatrix4 operator -(const float& value, const FloatMatrix4& rhs); + + /** + * Checks whether the current instance of %FloatMatrix4 equals the specified instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return @c true if the values of the current instance is equal to the value of the specified instance, @n + * else @c false + * @param[in] obj An instance of %FloatMatrix4 + * @remarks This method overrides Tizen::Base::Object::Equals(). This method uses the values of the Matrix components to compare the two instances. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the determinant of the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The determinant value of the current instance + */ + float GetDeterminant(void) const; + + /** + * Gets the inverse matrix of the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + * @remarks This function must be called after checking whether the matrix is invertible or not. + */ + FloatMatrix4 GetInverse(void) const; + + /** + * Gets the trace of the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return The trace of the current instance + */ + float GetTrace(void) const; + + /** + * Gets the transpose matrix of the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return A new instance of %FloatMatrix4 containing the resulting value of the operation + */ + FloatMatrix4 GetTranspose(void) const; + + /** + * Checks whether the current instance is an identity matrix. + * + * @since 2.0 + * + * @return @c true if the matrix is an identity matrix, @n + * else @c false + */ + bool IsIdentity(void) const; + + /** + * Checks whether the current matrix is invertible. + * + * @since 2.0 + * + * @return @c true if the matrix is invertible, @n + * else @c false + */ + bool IsInvertible(void) const; + + /** + * Negates the matrix members of current instance of %FloatMatrix4. + * + * @since 2.0 + */ + void Negate(void); + + /** + * Sets the identity matrix to the current instance of %FloatMatrix4. + * + * @since 2.0 + */ + void SetAsIdentity(void); + + /** + * Sets the inverse matrix to the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not invertible. + */ + result Invert(void); + + /** + * Sets the transposed matrix to the current instance of %FloatMatrix4. + * + * @since 2.0 + */ + void Transpose(void); + + /** + * Sets the matrix members of current instance of %FloatMatrix4 to zero. + * + * @since 2.0 + */ + void SetAsNull(void); + + /** + * The matrix of the current instance of %FloatMatrix4. + * + * @since 2.0 + * + * @remarks The column-major order matrix. + */ + float matrix[4][4]; + +private: + friend class _FloatMatrix4Impl; + class _FloatMatrix4Impl* __pImpl; + +}; // FloatMatrix4 + +}} // Tizen::Base + +#endif //_FBASE_FLOAT_MATRIX4_H_ diff --git a/inc/FBaseInt8.h b/inc/FBaseInt8.h new file mode 100644 index 0000000..eb6f65e --- /dev/null +++ b/inc/FBaseInt8.h @@ -0,0 +1,350 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseInt8.h + * @brief This is the header file for the %Int8 class. + * + * @see Tizen::Base::Number + * + * This header file contains the declarations of the %Int8 class. + */ +#ifndef _FBASE_INT8_H_ +#define _FBASE_INT8_H_ + +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Int8 + * @brief This class is the wrapper class for the @c signed @c char built-in type. + * + * @since 2.0 + * + * The %Int8 class represents an integer value ranging from -128 to 127. The class is useful when passing an 8-bit + * signed integral value to a method that accepts only an instance of Object. Furthermore, this class provides + * methods for converting %Int8 (and @c char) to String, and %String to %Int8 (and @c char). + * + * The following example demonstrates how to use the %Int8 class. + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method checks whether the given string object contains a string + * // representation of the pre-defined minimum 8-bit integral value. + * result + * MyClass::Verify(String& string, bool& out) + * { + * static const Int8 MINIMUM(123); + * + * result r = E_SUCCESS; + * + * char ch; + * r = Int8::Parse(string, ch); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * out = (MINIMUM.CompareTo(ch) == 0) ? true: false; + * + * return r; + * CATCH: + * return r; + * } + * @endcode + */ +class _OSP_EXPORT_ Int8 + : public Number +{ +public: + /** + * Initializes this instance of %Int8 with the specified value. + * + * @since 2.0 + * + * @param[in] value A @c char value + */ + Int8(char value = 0); + + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %Int8 + */ + Int8(const Int8& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Int8(void); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %Int8 + */ + Int8& operator =(const Int8& rhs); + + /** + * Compares two @c char values. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of ch1 is less than the value of ch2 + * == 0 if the value of ch1 is equal to the value of ch2 + * > 0 if the value of ch1 is greater than the value of ch2 + * @endcode + * @param[in] ch1 The first @c char value to compare + * @param[in] ch2 The second @c char value to compare + */ + static int Compare(char ch1, char ch2); + + /** + * Compares the value of the current instance with the value of the specified instance of the %Int8 class. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of the current instance is less than the value of the specified instance + * == 0 if the value of the current instance is equal to the value of the specified instance + * > 0 if the value of the current instance is greater than the value of the specified instance + * @endcode + * @param[in] value An instance of the %Int8 class to compare + */ + int CompareTo(const Int8& value) const; + + /** + * Checks whether the value of the specified instance of %Int8 is equal to the value of the current instance. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance is equal to the value of the current instance, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @see Tizen::Base::Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance of %Int8. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance of %Int8 + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the value of the current instance. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the hash value of the specified @c char value. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the specified @c char value + * @param[in] val A @c char value to get the hash value + */ + static int GetHashCode(char val); + + /** + * Decodes a string into a @c signed @c char. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @remarks This method accepts decimal, hexadecimal, and octal numbers given by the + * following grammar: + * @code + * - DecodableString: + * Sign[opt] DecimalNumeral + * Sign[opt] 0x HexDigits + * Sign[opt] 0X HexDigits + * Sign[opt] # HexDigits + * Sign[opt] 0 OctalDigits + * - Sign: + * '-' + * @endcode + */ + static result Decode(const String& s, char& ret); + + /** + * Parses the @c signed @c char equivalent of the specified string representing a numeric value. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a byte that can be parsed. + * @remarks This method assumes that the string representing the numeric value + * uses a radix 10. + */ + static result Parse(const String& s, char& ret); + + /** + * Parses the specified string representing a numeric value and + * returns the value as @c signed @c char (as out parameter). + * + * @since 2.0 + * + * @return The @c signed @c char equivalent of the specified string representing the numeric value using the specified index + * @param[in] s A string representing a numeric value + * @param[in] radix The radix of the string representing a numeric value @n + * It must either be 2, 8, 10, or 16. + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @exception E_OUT_OF_RANGE The specified @c radix is invalid. + */ + static result Parse(const String& s, int radix, char& ret); + + /** + * Gets the @c signed @c char equivalent of the current instance of %Int8. + * + * @since 2.0 + * + * @return The @c signed @c char equivalent of the current instance + */ + virtual char ToChar(void) const; + + /** + * Gets the @c signed @c short equivalent of the current instance of %Int8. + * + * @since 2.0 + * + * @return The @c signed @c short equivalent of the current instance + */ + virtual short ToShort(void) const; + + /** + * Gets the @c signed @c int equivalent of the current instance of %Int8. + * + * @since 2.0 + * + * @return The @c signed @c int equivalent of the current instance + */ + virtual int ToInt(void) const; + + /** + * Gets the @c signed @c long equivalent of the current instance of %Int8. + * + * @since 2.0 + * + * @return The @c signed @c long equivalent of the current instance + */ + virtual long ToLong(void) const; + + /** + * Gets the @c signed @c long @c long equivalent of the current instance of %Int8. + * + * @since 2.0 + * + * @return The @c signed @c long @c long equivalent of the current instance + */ + virtual long long ToLongLong(void) const; + + /** + * Gets the @c signed @c float equivalent of the current instance of %Int8. + * + * @since 2.0 + * + * @return The @c signed @c float equivalent of the current instance + */ + virtual float ToFloat(void) const; + + /** + * Gets the @c signed @c double equivalent of the current instance of %Int8. + * + * @since 2.0 + * + * @return The @c signed @c double equivalent of the current instance + */ + virtual double ToDouble(void) const; + + /** + * Gets the string representing the value of the current instance of %Int8. + * + * @since 2.0 + * + * @return A string representing the value of the current instance + */ + virtual String ToString(void) const; + + /** + * Gets the string representing the specified @c signed @c char value using radix @c 10. + * + * @since 2.0 + * + * @return A string containing a Unicode representation of the specified @c char value using radix 10 + * @param[in] value A @c char value + */ + static String ToString(char value); + + /** + * A constant holding the maximum value of type @c char. @n + * A @c short character can hold a value of upto 2^7-1. + * + * @since 2.0 + */ + static const char VALUE_MAX = (signed char) 0x7F; + + /** + * A constant holding the minimum value of type @c char. @n + * A @c short character can hold a value of upto -2^7. + * + * @since 2.0 + */ + static const char VALUE_MIN = (signed char) 0x80; + + /** + * A @c signed @c char value of this instance. + * + * @since 2.0 + */ + signed char value; + + +private: + friend class _Int8Impl; + class _Int8Impl * __pInt8Impl; + +}; // Int8 + +}} // Tizen::Base + +#endif //_FBASE_INT8_H_ diff --git a/inc/FBaseInt8Comparer.h b/inc/FBaseInt8Comparer.h new file mode 100644 index 0000000..eb54bc6 --- /dev/null +++ b/inc/FBaseInt8Comparer.h @@ -0,0 +1,130 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseInt8Comparer.h + * @brief This is the header file for the %Int8Comparer class. + * + * @see Int8 and Tizen::Base::Collection::IComparer + * + * This header file contains the declarations of the %Int8Comparer class. + */ +#ifndef _FBASE_INT8_COMPARER_H_ +#define _FBASE_INT8_COMPARER_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Int8Comparer + * @brief This class checks for equivalence between 2 instances of the Int8 type. + * + * @since 2.0 + * + * The %Int8Comparer class checks for equivalence between 2 instances of the Int8 type. + * + * For more information on the class features, see Collection Comparisons. + * + * The following example demonstrates how to use the %Int8Comparer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::Int8ComparerSample(void) + * { + * Int8 i1(123); + * Int8 i2(124); + * Int8Comparer comparer; + * + * int cmp; + * comparer.Compare(i1, i2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +class _OSP_EXPORT_ Int8Comparer + : public Object + , public virtual Tizen::Base::Collection::IComparer +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Int8Comparer(void); + + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Int8Comparer(void); + + /** + * Compares two given instances of type Int8. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 The first instance of type Int8 + * @param[in] obj2 The second instance of type Int8 + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + Int8Comparer(const Int8Comparer& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + Int8Comparer& operator =(const Int8Comparer& rhs); + + friend class _Int8ComparerImpl; + class _Int8ComparerImpl * __pInt8ComparerImpl; + +}; // Int8Comparer + +}} // Tizen::Base + +#endif // _FBASE_INT8_COMPARER_H_ diff --git a/inc/FBaseIntMatrix.h b/inc/FBaseIntMatrix.h new file mode 100644 index 0000000..32592ba --- /dev/null +++ b/inc/FBaseIntMatrix.h @@ -0,0 +1,459 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/* + * @file FBaseIntMatrix.h + * @brief This is the header file for the %IntMatrix class. + * + * This header file contains the declarations of the %IntMatrix class. + * + */ + +#ifndef _FBASE_INT_MATRIX_H_ +#define _FBASE_INT_MATRIX_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +/* + * @class IntMatrix + * @brief This class encapsulates a two-dimensional matrix. + * + * @since 2.0 + * + * The %IntMatrix class provides a int precision, two-dimensional matrix class. + * + */ +class _OSP_EXPORT_ IntMatrix + : public Tizen::Base::Object +{ +public: + /* + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %IntMatrix + */ + IntMatrix(const IntMatrix& rhs); + + /* + * Constructs a row by column null matrix in which all elements are zero. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + */ + IntMatrix(int rowCount, int columnCount); + + /* + * Constructs a row by column matrix initialized to the values in the specified array. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + * @param[in] pArray A one-dimensional array @n The array must be at least row * column in length. + * @param[in] rowMajor Set to @c true to copy the array in row-major order, @n + * else @c copy in column-major order + */ + IntMatrix(int rowCount, int columnCount, const int* pArray, bool rowMajor = true); + + /* + * Constructs a row by column matrix initialized to the values in the specified array. + * + * @since 2.0 + * + * @param[in] rowCount The number of rows in the current instance + * @param[in] columnCount The number of columns in the current instance + * @param[in] pArray[] A two-dimensional array @n The array must be at least row * column in length. + */ + IntMatrix(int rowCount, int columnCount, const int* pArray[]); + + /* + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~IntMatrix(void); + + /* + * Checks whether the current instance and the specified instance of %IntMatrix are equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %IntMatrix + */ + bool operator ==(const IntMatrix& rhs) const; + + /* + * Checks whether the current instance and the specified instance of %IntMatrix are not equal. + * + * @since 2.0 + * + * @return @c true if all matrix members of the current instance are not equal to the corresponding matrix members in the specified instance, @n + * else @c false + * @param[in] rhs An instance of %IntMatrix + */ + bool operator !=(const IntMatrix& rhs) const; + + /* + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return The reference to this instance + * @param[in] rhs An instance of %IntMatrix + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + * @remarks If either row or column count of the current instance is not same with that of the specified instance, + * return the reference to this instance without assigning. + */ + IntMatrix& operator =(const IntMatrix& rhs); + + /* + * Checks whether the current instance of %IntMatrix equals the specified instance of %IntMatrix. + * + * @since 2.0 + * + * @return @c true if the values of the current instance are equal to the value of the specified instance, @n + * else @c false + * @param[in] obj An instance of %IntMatrix + * @remarks This method overrides Tizen::Base::Object::Equals(). This method uses the values of the Matrix components to compare the two instances. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /* + * Gets the hash value of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + /* + * Adds the value of the specified instance to the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %IntMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + */ + result Add(const IntMatrix& matrix); + + /* + * Adds the value to each matrix members of current instance of %IntMatrix. + * + * @since 2.0 + * + * @param[in] value A @c int value to add + */ + void AddToEachElement(int value); + + /* + * Gets the number of column in the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return The number of column in the current instance + */ + int GetColumnCount(void) const; + + /* + * Gets a new array that includes the values of the specified column in the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return A pointer to @c int array + * @param[in] columnIndex The target column number in the current instance + * @exception E_INVALID_ARG The @c columnIndex is larger than the column count of the current instance. + */ + int* GetColumnN(int columnIndex) const; + + /* + * Gets the determinant of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return The determinant value of the current instance + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + * @remarks If the current instance is not a square matrix, return zero. + */ + int GetDeterminant(void) const; + + /* + * Gets the value at the specified row and column of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return The value at the specified row and column of the current instance + * @param[in] rowIndex The target row number in the current instance + * @param[in] columnIndex The target column number in the current instance + * @exception E_INVALID_ARG The @c columnIndex or @c rowIndex is larger than that of the current instance. + */ + int GetElement(int rowIndex, int columnIndex) const; + + /* + * Gets the inverse matrix of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return A pointer to the instance of %IntMatrix containing the resulting value of the operation + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + IntMatrix* GetInverseN(void) const; + + /* + * Gets the number of row in the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return The number of row in the current instance + */ + int GetRowCount(void) const; + + /* + * Gets a new array that includes the values of the specified row in the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return A pointer to @c int array + * @param[in] rowIndex The target row number in the current instance + * @exception E_INVALID_ARG The @c rowIndex is larger than the row count of the current instance. + */ + int* GetRowN(int rowIndex) const; + + /* + * Gets the trace of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[out] value A @c int value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result GetTrace(int& value) const; + + /* + * Gets the transpose matrix of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return A pointer to the instance of %IntMatrix containing the resulting value of the operation + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + IntMatrix* GetTransposeN(void) const; + + /* + * Checks whether the current instance is an identity matrix. + * + * @since 2.0 + * + * @return @c true if the matrix is an identity matrix, @n + * else @c false + */ + bool IsIdentity(void) const; + + /* + * Checks whether the current matrix is invertible. + * + * @since 2.0 + * + * @return @c true if the matrix is invertible, @n + * else @c false + */ + bool IsInvertible(void) const; + + /* + * Multiplies the value of the specified instance with the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %IntMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The column count of the current instance is not same with the row count of the specified instance. + */ + result Multiply(const IntMatrix& matrix); + + /* + * Multiplies the value to each matrix members of current instance of %IntMatrix. + * + * @since 2.0 + * + * @param[in] value A @c int value to multiply + */ + void Multiply(int value); + + /* + * Negates the matrix members of current instance of %IntMatrix. + * + * @since 2.0 + */ + void Negate(void); + + /* + * Sets the value of the current instance of %IntMatrix to its identity. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result SetAsIdentity(void); + + /* + * Sets the value of the current instance of %IntMatrix to its inverse. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result Invert(void); + + /* + * Sets the value of the current instance of %IntMatrix to its transpose. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The current instance is not a square matrix. + */ + result Transpose(void); + + /* + * Sets the values of the specified array to the specified column of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The target column number in the current instance + * @param[in] pArray An array which includes the values @n The array must be at least row in length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c pArray is @c null, or the @c columnIndex is larger than the column count of the current instance. + */ + result SetColumn(int columnIndex, const int* pArray); + + /* + * Sets the values of the specified array to the specified row of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] rowIndex The target row number in the current instance + * @param[in] pArray An array which includes the values @n The array must be at least column in length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c pArray is @c null, or the @c rowIndex is larger than the row count of the current instance. + */ + result SetRow(int rowIndex, const int* pArray); + + /* + * Sets the value to the specified row and column of the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] rowIndex The target row number in the current instance + * @param[in] columnIndex The target column number in the current instance + * @param[in] value A @c int value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The pArray is @c null, or the @c rowIndex is larger than the row count of the current instance, + * or the @c columnIndex is larger than the column count of the current instance. + */ + result SetElement(int rowIndex, int columnIndex, int value); + + /* + * Sets the values to the current instance of %IntMatrix in either the row-major or column-major order. + * + * @since 2.0 + * + * @return An error code + * @param[in] pArray A one-dimensional array @n The array must be at least row * column in length. + * @param[in] rowMajor Set to @c true to copy the array in row-major order, @n + * else @c false to copy in column-major order + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The pArray is @c null. + */ + result SetValue(const int* pArray, bool rowMajor = true); + + /* + * Sets the matrix members of current instance of %IntMatrix to zero. + * + * @since 2.0 + */ + void SetAsNull(void); + + /* + * Subtracts the value of the specified instance from the current instance of %IntMatrix. + * + * @since 2.0 + * + * @return An error code + * @param[in] matrix An instance of %IntMatrix + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either row or column count of the current instance is not same with that of the specified instance. + */ + result Subtract(const IntMatrix& matrix); + + /* + * Subtracts the value from each matrix members of current instance of %IntMatrix. + * + * @since 2.0 + * + * @param[in] value A @c int value to subtract + */ + void SubtractToEachElement(int value); + +private: + /* + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + IntMatrix(void); + + bool AllocateCapacity(int rowCount, int columnCount); + void GetMinor(int** pSrc, int** pDest, int rowIndex, int columnIndex, int order) const; + int CalculateDeterminant(int** pMatrix, int order) const; + + friend class _IntMatrixImpl; + class _IntMatrixImpl* __pImpl; + + int** __pMatrix; + int __row; + int __column; + +}; // IntMatrix + +}} // Tizen::Base + +#endif //_FBASE_INT_MATRIX_H_ diff --git a/inc/FBaseInteger.h b/inc/FBaseInteger.h new file mode 100644 index 0000000..249ec8e --- /dev/null +++ b/inc/FBaseInteger.h @@ -0,0 +1,352 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseInteger.h + * @brief This is the header file for the %Integer class. + * + * @see Number() class() + * + * This header file contains the declarations of the %Integer class. + */ +#ifndef _FBASE_INTEGER_H_ +#define _FBASE_INTEGER_H_ + +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Integer + * @brief This class is the wrapper class for the @c signed @c int built-in type. + * + * @since 2.0 + * + * The %Integer class represents an integer value ranging from -2147483648 to 2147483647, + * that is, -(2^31) to +((2^31)-1). This class is useful when passing a 32-bit @c signed + * integral value to a method that accepts only an instance of Object. Furthermore, + * this class provides methods for converting %Integer (and @c int) to String, and %String + * to %Integer (and @c int). + * + * The following example demonstrates how to use the %Integer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method checks whether the given string object contains a string + * // representation of the pre-defined minimum 32-bit integral value. + * result + * MyClass::Verify(String& string, bool& out) + * { + * static const Integer MINIMUM(1230); + * + * result r = E_SUCCESS; + * + * int i; + * r = Integer::Parse(string, i); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * out = (MINIMUM.CompareTo(i) == 0) ? true: false; + * + * return r; + * CATCH: + * return r; + * } + * @endcode + */ +class _OSP_EXPORT_ Integer + : public Number +{ +public: + /** + * Initializes this instance of %Integer with the specified value. + * + * @since 2.0 + * + * @param[in] value An integer value + */ + Integer(int value = 0); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %Integer + */ + Integer(const Integer& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Integer(void); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %Integer + */ + Integer& operator =(const Integer& rhs); + + /** + * Compares two @c int values. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of @c i1 is less than the value of @c i2 + * == 0 if the value of @c i1 is equal to the value of @c i2 + * > 0 if the value of @c i1 is greater than the value of @c i2 + * @endcode + * @param[in] i1 The first @c int value to compare + * @param[in] i2 The second @c int value to compare + */ + static int Compare(int i1, int i2); + + /** + * Compares the value of the current instance with the value of the specified instance of the %Integer class. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * + * @code + * < 0 if the value of the current instance is less than the value of the specified instance + * == 0 if the value of the current instance is equal to the value of the specified instance + * > 0 if the value of the current instance is greater than the value of the specified instance + * @endcode + * @param[in] value An instance of the %Integer class to compare + */ + int CompareTo(const Integer& value) const; + + /** + * Checks whether the value of the specified instance of Object is equal to the value of the current instance of %Integer. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of Object is equal to the value of the current instance of %Integer, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @see Tizen::Base::Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Decodes a string into a @c signed @c int. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing the numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @remarks This method accepts decimal, hexadecimal, and octal numbers given by the + * following grammar: + * @code + * - DecodableString: + * Sign[opt] DecimalNumeral + * Sign[opt] 0x HexDigits + * Sign[opt] 0X HexDigits + * Sign[opt] # HexDigits + * Sign[opt] 0 OctalDigits + * - Sign: + * '-' + * @endcode + */ + static result Decode(const String& s, int& ret); + + /** + * Gets the hash value of the current instance of %Integer. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance of %Integer + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the value of the current instance. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the hash value of the specified @c int value. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the specified @c int value + * @param[in] val A @c int value to get the hash value + */ + static int GetHashCode(int val); + + /** + * Parses the @c signed @c int equivalent of the specified string representing a numeric value. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @remarks This method assumes that the string representing the numeric value + * uses a radix 10. + */ + static result Parse(const String& s, int& ret); + + /** + * Parses the @c signed @c int equivalent of the specified string representing a numeric value using the specified radix. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[in] radix The radix of the string representing the numeric value @n + * It must either be 2, 8, 10, or 16. + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @exception E_OUT_OF_RANGE The specified @c radix is invalid. + */ + static result Parse(const String& s, int radix, int& ret); + + /** + * Gets the @c signed @c char equivalent of the current instance of the %Integer class. + * + * @since 2.0 + * + * @return A @c signed @c char equivalent of the current instance + */ + virtual char ToChar(void) const; + + /** + * Gets the @c signed @c short equivalent of the current instance of the %Integer class. + * + * @since 2.0 + * + * @return A @c signed @c short equivalent of the current instance + */ + virtual short ToShort(void) const; + + /** + * Gets the @c signed @c int equivalent of the current instance of the %Integer class. + * + * @since 2.0 + * + * @return A @c signed @c int equivalent of the current instance + */ + virtual int ToInt(void) const; + + /** + * Gets the @c signed @c long equivalent of the current instance of the %Integer class. + * + * @since 2.0 + * + * @return A @c signed @c long equivalent of the current instance + */ + virtual long ToLong(void) const; + + /** + * Gets the @c signed @c long @c long equivalent of the current instance of the %Integer class. + * + * @since 2.0 + * + * @return A @c signed @c long @c long equivalent of the current instance + */ + virtual long long ToLongLong(void) const; + + /** + * Gets the @c signed @c float equivalent of the current instance of the %Integer class. + * + * @since 2.0 + * + * @return A @c signed @c float equivalent of the current instance + */ + virtual float ToFloat(void) const; + + /** + * Gets the @c signed @c double equivalent of the current instance of the %Integer class. + * + * @since 2.0 + * + * @return A @c signed @c double equivalent of the current instance + */ + virtual double ToDouble(void) const; + + /** + * Gets the string representing the value of the current instance of the %Integer class. + * + * @since 2.0 + * + * @return A string representing the value of the current instance + */ + virtual String ToString(void) const; + + /** + * Gets the string representing the specified @c signed @c int value. + * + * @since 2.0 + * + * @return A string containing a Unicode representation of the specified @c signed @c int value + * @param[in] value A @c signed @c int value to convert + */ + static String ToString(int value); + + /** + * A constant holding the maximum value of type @c int. @n + * A @c short integer can hold a value of upto 2^31-1. + * + * @since 2.0 + */ + static const int VALUE_MAX = (int) 0x7FFFFFFF; + + /** + * A constant holding the minimum value of type @c int. @n + * A @c short integer can hold a value of upto -2^31. + * + * @since 2.0 + */ + static const int VALUE_MIN = (int) 0x80000000; + + /** + * An integer value of this instance. + * + * @since 2.0 + */ + int value; + + +private: + friend class _IntegerImpl; + class _IntegerImpl * __pIntegerImpl; + +}; // Integer + +}} //Tizen::Base + +#endif //_FBASE_INTEGER_H_ diff --git a/inc/FBaseIntegerComparer.h b/inc/FBaseIntegerComparer.h new file mode 100644 index 0000000..ceb2e49 --- /dev/null +++ b/inc/FBaseIntegerComparer.h @@ -0,0 +1,129 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseIntegerComparer.h + * @brief This is the header file for the %IntegerComparer class. + * + * @see Integer and Tizen::Base::Collection::IComparer + * + * This header file contains the declarations of the %IntegerComparer class. + */ +#ifndef _FBASE_INTEGER_COMPARER_H_ +#define _FBASE_INTEGER_COMPARER_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class IntegerComparer + * @brief This class checks for equivalence between 2 instances of the Integer type. + * + * @since 2.0 + * + * The %IntegerComparer class checks for equivalence between 2 instances of the Integer type. + * + * For more information on the class features, see Collection Comparisons. + * + * The following example demonstrates how to use the %IntegerComparer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::IntegerComparerSample(void) + * { + * Integer i1(123); + * Integer i2(124); + * IntegerComparer comparer; + * + * int cmp; + * comparer.Compare(i1, i2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +class _OSP_EXPORT_ IntegerComparer + : public Object + , public virtual Tizen::Base::Collection::IComparer +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + IntegerComparer(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~IntegerComparer(void); + + /** + * Compares two given instances of type Integer. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 The first instance of type %Integer + * @param[in] obj2 The second instance of type %Integer + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + IntegerComparer(const IntegerComparer& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + IntegerComparer& operator =(const IntegerComparer& rhs); + + friend class _IntegerComparerImpl; + class _IntegerComparerImpl * __pIntegerComparerImpl; + +}; // IntegerComparer + +}} // Tizen::Base + +#endif // _FBASE_INTEGER_COMPARER_H_ diff --git a/inc/FBaseLog.h b/inc/FBaseLog.h new file mode 100644 index 0000000..33b7585 --- /dev/null +++ b/inc/FBaseLog.h @@ -0,0 +1,687 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLog.h + * @brief This is the header file for the diagnostic types. + * + * This header file defines the diagnostic types. + * + */ +#ifndef _FBASE_LOG_H_ +#define _FBASE_LOG_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup GroupMacros Debugging Macros + * + * This page describes Tizen debugging macros. + * + * @since 2.0 + */ + +#if defined(_APP_LOG) || defined(_OSP_DEBUG_) || defined(_DEBUG) + +// AppLog Macro + +#define AppLog(...) AppLogInternal(__PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) +#define AppLogDebug(...) AppLogDebugInternal(__PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) +#define AppLogException(...) AppLogExceptionInternal(__PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) + +#define AppLogTag(tag, ...) AppLogTagInternal(tag, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) +#define AppLogDebugTag(tag, ...) AppLogDebugTagInternal(tag, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) +#define AppLogExceptionTag(tag, ...) AppLogExceptionTagInternal(tag, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) + +#define AppLogIf(expression, ...) \ + if (expression) { \ + AppLogInternal(__PRETTY_FUNCTION__, __LINE__, __VA_ARGS__); \ + } \ + else {;} + +#define AppLogDebugIf(expression, ...) \ + if (expression) { \ + AppLogDebugInternal(__PRETTY_FUNCTION__, __LINE__, __VA_ARGS__); \ + } \ + else {;} + +#define AppLogExceptionIf(expression, ...) \ + if (expression) { \ + AppLogExceptionInternal(__PRETTY_FUNCTION__, __LINE__, __VA_ARGS__); \ + } \ + else {;} + +#define AppAssert(condition) \ + if (!(condition)) { \ + AppassertInternal(__PRETTY_FUNCTION__, __LINE__); \ + } \ + else {;} + +#define AppAssertf(condition, ...) \ + if (!(condition)) { \ + AppassertfInternal(# condition, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__); \ + } \ + else {;} +#else // defined(_APP_LOG) + +/** + * @addtogroup GroupMacros + * + * @{ + */ +/** + * This macro allows display of arbitrary messages for future examination. + * + * @since 2.0 + * + * @param[in] ... The message to display + * + * The following example demonstrates how to use the AppLog macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * AppLog("Initialization successful."); + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLog(...) + +/** + * This macro must be added in your program if you want the debug messages to be displayed in the output. + * + * @since 2.0 + * + * @param[in] ... The message to display + * + * @image html debugging_applog_output.png + * + * The following example demonstrates how to use the AppLogDebug macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * AppLogDebug("Invoked with value: %d", value); + * + * //... + * + * AppLogDebug("Exit."); + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLogDebug(...) + +/** + * This macro must be added in your program if you want the exception messages to be displayed in the output. + * + * @since 2.0 + * + * @param[in] ... The message to display + * + * The following example demonstrates how to use the AppLogException macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * AppLogDebug("Invoked with value: %d", value); + * //... + * if (something_wrong) // The Try family macros can be used instead. + * { + * AppLogException("An unexpected error occurred."); + * + * return false; + * } + * + * AppLog("Initialization successful."); + * AppLogDebug("Exit."); + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLogException(...) + +/** + * This macro is used to check logical errors in a program. + * If the assertion fails, the current process is killed. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @hideinitializer + */ +#define AppAssert(condition) + +/** + * This macro is used to check logical errors in a program. + * If the assertion fails, a message is printed on the console and the current process is killed. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] ... The message to print, if the assertion fails + * + * @image html debugging_appassert.png + * + * The following example demonstrates how to use the Assert macro. + * + * @code + * result + * MyClass::DoSomething(void) + * { + * result r = E_SUCCESS; + * r = mutex.Acquire(); + * // Do something + * r = mutex.Release(); + * + * // If false, console prints "Mutex Release Failed." + * // and the process is killed. + * AppAssertf(r == E_SUCCESS, "Mutex Release Failed."); + * + * return r; + * } + * @endcode + * @hideinitializer + */ +#define AppAssertf(condition, ...) + +/** + * This macro is added in a program to display a message when an expression is @c true. + * + * @since 2.0 + * + * @param[in] expression The expression to evaluate + * @param[in] ... The message to display + * + * The following example demonstrates how to use the AppLogIf macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * AppLogIf(value !=0, "Invoked with value: %d", value); + * //... + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLogIf(expression, ...) + +/** + * This macro is added in a program to display a debug message when an expression is @c true. + * + * @since 2.0 + * + * @param[in] expression The expression to evaluate + * @param[in] ... The message to display + * + * The following example demonstrates how to use the AppLogDebugIf macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * AppLogDebugIf(value !=0, "Invoked with value: %d", value); + * //... + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLogDebugIf(expression, ...) + +/** + * This macro is added in a program to display an exception message when an expression is @c true. + * + * @since 2.0 + * + * @param[in] expression The expression to evaluate + * @param[in] ... The message to display + * + * The following example demonstrates how to use the AppLogExceptionIf macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * int status; + * + * AppLogExceptionIf(status != 0, "status : %d.", status); + * //... + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLogExceptionIf(expression, ...) + +/** + * This macro is added in a program to display an info message with a tag. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] ... The message to display + * + * The following example demonstrates how to use the AppLogTag macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * int status; + * + * AppLogTag("MyTag", "Initialization successful."); + * //... + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLogTag(tag, ...) + +/** + * This macro is added in a program to display a debug message with a tag. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] ... The message to display + * + * The following example demonstrates how to use the AppLogDebugTag macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * AppLogDebugTag("MyTag", "Invoked with value: %d", value); + * + * //... + * + * AppLogDebugTag("MyTag", "Exit."); + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLogDebugTag(tag, ...) + +/** + * This macro is added in a program to display an exception message with a tag. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] ... The message to display + * + * The following example demonstrates how to use the AppLogExceptionTag macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * AppLogDebug("Invoked with value: %d", value); + * //... + * if (something_wrong) // The Try family macros can be used instead. + * { + * AppLogExceptionTag("MyTag", "An unexpected error occurred."); + * + * return false; + * } + * + * AppLog("Initialization successful."); + * AppLogDebug("Exit."); + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define AppLogExceptionTag(tag, ...) +/** @} */ +#endif // defined(_APP_LOG) + +// Try Macros +/** + * @addtogroup GroupMacros + * + * @{ + */ +/** + * If the condition is @c false, it prints a message, evaluates a cleanup expression, + * and goes to CATCH. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] expr Expressions that are evaluated before going to CATCH label + * @param[in] ... The message to display + * + * The following example demonstrates how to use the Try macro. + * + * @code + * const A* + * MyClass::DoSomething(const wchar_t* pValue) + * { + * result r = E_SUCCESS; + * + * // Do something... + * + * // If pValue is null, print "pValue == null" to the + * // console and return E_INVALID_ARG. + * TryCatch(pValue != null, r = E_INVALID_ARG, "pValue == null"); + * + * SetLastResult(E_SUCCESS); + * + * return _pValue; + * + * CATCH: + * SetLastResult(r); + * + * return null; + * } + * @endcode + * @hideinitializer + */ +#define TryCatch(condition, expr, ...) \ + if (!(condition)) { \ + AppLogException(__VA_ARGS__); \ + expr; \ + goto CATCH; \ + } \ + else {;} + +/** + * If the condition is @c false, it prints a message, sets the last result, evaluates a cleanup expression + * and goes to CATCH. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] expr Expressions that are evaluated before going to CATCH label + * @param[in] r The last result to set + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryCatchResult(condition, expr, r, ...) \ + if (!(condition)) { \ + SetLastResult(r); \ + AppLogException(__VA_ARGS__); \ + expr; \ + goto CATCH; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed and a value is returned. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] returnValue The value to return when the condition is @c false + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryReturn(condition, returnValue, ...) \ + if (!(condition)) { \ + AppLogException(__VA_ARGS__); \ + return returnValue; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed, sets the last result and a value is returned. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] returnValue The value to return when the condition is @c false + * @param[in] r The last result to set + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryReturnResult(condition, returnValue, r, ...) \ + if (!(condition)) { \ + SetLastResult(r); \ + AppLogException(__VA_ARGS__); \ + return returnValue; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed, sets the last result and no value is returned. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] r The last result to set + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryReturnVoidResult(condition, r, ...) \ + if (!(condition)) { \ + SetLastResult(r); \ + AppLogException(__VA_ARGS__); \ + return; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed and no value is returned. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryReturnVoid(condition, ...) \ + if (!(condition)) { \ + AppLogException(__VA_ARGS__); \ + return; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryLog(condition, ...) \ + if (!(condition)) { \ + AppLog(__VA_ARGS__); \ + } \ + else {;} + + +// TryTag Macros + +/** + * If the condition is @c false, it prints a message with a tag, evaluates a cleanup expression + * and goes to CATCH. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] condition The condition that is expected to be true + * @param[in] expr Expressions that are evaluated before going to CATCH label + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryCatchTag(tag, condition, expr, ...) \ + if (!(condition)) { \ + AppLogExceptionTag(tag, __VA_ARGS__); \ + expr; \ + goto CATCH; \ + } \ + else {;} + +/** + * If the condition is @c false, it prints a message with a tag, sets the last result, evaluates a cleanup expression, + * and goes to CATCH. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] condition The condition that is expected to be true + * @param[in] expr Expressions that are evaluated before going to CATCH label + * @param[in] r The last result to set + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryCatchResultTag(tag, condition, expr, r, ...) \ + if (!(condition)) { \ + SetLastResult(r); \ + AppLogExceptionTag(tag, __VA_ARGS__); \ + expr; \ + goto CATCH; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed with a tag and a value is returned. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] condition The condition that is expected to be true + * @param[in] returnValue The value to return when the condition is @c false + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryReturnTag(tag, condition, returnValue, ...) \ + if (!(condition)) { \ + AppLogExceptionTag(tag, __VA_ARGS__); \ + return returnValue; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed with a tag, sets the last result and a value is returned. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] condition The condition that is expected to be true + * @param[in] returnValue The value to return when the condition is @c false + * @param[in] r The last result to set + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryReturnResultTag(tag, condition, returnValue, r, ...) \ + if (!(condition)) { \ + SetLastResult(r); \ + AppLogExceptionTag(tag, __VA_ARGS__); \ + return returnValue; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed with a tag, sets the last result and no value is returned. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] condition The condition that is expected to be true + * @param[in] r The last result to set + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryReturnVoidResultTag(tag, condition, r, ...) \ + if (!(condition)) { \ + SetLastResult(r); \ + AppLogExceptionTag(tag, __VA_ARGS__); \ + return; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed with a tag and no value is returned. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] condition The condition that is expected to be true + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryReturnVoidTag(tag, condition, ...) \ + if (!(condition)) { \ + AppLogExceptionTag(tag, __VA_ARGS__); \ + return; \ + } \ + else {;} + +/** + * If the condition is @c false, the message is printed with a tag. + * + * @since 2.0 + * + * @param[in] tag Used to identify the source of a log message + * @param[in] condition The condition that is expected to be true + * @param[in] ... The message to display + * @hideinitializer + */ +#define TryLogTag(tag, condition, ...) \ + if (!(condition)) { \ + AppLogTag(tag, __VA_ARGS__); \ + } \ + else {;} + +/** @} */ + +_OSP_EXPORT_ void AppLogInternal(const char* pFunction, int lineNumber, const char* pFormat, ...); +_OSP_EXPORT_ void AppLogDebugInternal(const char* pFunction, int lineNumber, const char* pFormat, ...); +_OSP_EXPORT_ void AppLogExceptionInternal(const char* pFunction, int lineNumber, const char* pFormat, ...); +_OSP_EXPORT_ void AppassertInternal(const char* pFunction, int lineNumber); +_OSP_EXPORT_ void AppassertfInternal(const char* expr, const char* pFunction, int lineNumber, const char* pFormat, ...); + +_OSP_EXPORT_ void AppLogTagInternal(const char* pTag, const char* pFunction, int lineNumber, const char* pFormat, ...); +_OSP_EXPORT_ void AppLogDebugTagInternal(const char* pTag, const char* pFunction, int lineNumber, const char* pFormat, ...); +_OSP_EXPORT_ void AppLogExceptionTagInternal(const char* pTag, const char* pFunction, int lineNumber, const char* pFormat, ...); + + +#ifdef __cplusplus +} +#endif + +#endif // _FBASE_LOG_H_ diff --git a/inc/FBaseLong.h b/inc/FBaseLong.h new file mode 100644 index 0000000..bcc59e5 --- /dev/null +++ b/inc/FBaseLong.h @@ -0,0 +1,349 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLong.h + * @brief This is the header file for the %Long class. + * + * @see Number() + * + * This header file contains the declarations of the %Long class. + */ +#ifndef _FBASE_LONG_H_ +#define _FBASE_LONG_H_ + +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Long + * @brief This class is the wrapper class for the @c signed @c long built-in type. + * + * @since 2.0 + * + * The %Long class represents an integer value ranging from -2147483648 to 2147483647 + * , that is, -(2^31) to +((2^31)-1). The class is useful when passing a 32-bit @c signed + * integral value to a method that accepts only an instance of Object. Furthermore, + * this class provides methods for converting %Long (and @c long) to String, and %String + * to %Long (and @c long). + * + * The following example demonstrates how to use the %Long class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method checks whether the given string object contains a string + * // representation of the pre-defined minimum 32-bit integral value + * result + * MyClass::Verify(String& string, bool& out) + * { + * static const Long MINIMUM(1230); + * result r = E_SUCCESS; + * + * long l; + * r = Long::Parse(string, l); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * out = (MINIMUM.CompareTo(l) == 0) ? true: false; + * + * return r; + * CATCH: + * return r; + * } + * @endcode + */ +class _OSP_EXPORT_ Long + : public Number +{ +public: + /** + * Initializes this instance of %Long with the specified value. + * + * @since 2.0 + * + * @param[in] value A @c long value + */ + Long(long value = 0); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %Long + */ + Long(const Long& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Long(void); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %Long + */ + Long& operator =(const Long& rhs); + + /** + * Compares two @c long values. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of @c l1 is less than the value of @c l2 + * == 0 if the value of @c l1 is equal to the value of @c l2 + * > 0 if the value of @c l1 is greater than the value of @c l2 + * @endcode + * @param[in] l1 The first @c long value to compare + * @param[in] l2 The second @c long value to compare + */ + static int Compare(long l1, long l2); + + /** + * Compares the value of the current instance with the value of the specified instance of the %Long class. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * + * @code + * < 0 if the value of the current instance is less than the value of the specified instance + * == 0 if the value of the current instance is equal to the value of the specified instance + * > 0 if the value of the current instance is greater than the value of the specified instance + * @endcode + * @param[in] value An instance of the %Long class to compare + */ + int CompareTo(const Long& value) const; + + /** + * Checks whether the value of the specified instance of %Object is equal to the value of the current instance of %Long. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of %Object is equal to the value of the current instance of %Long, @n + * else @c false + * @param[in] obj An instance of %Object to compare + * @see Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance of %Long. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance of %Long + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the value of the current instance. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the hash value of the specified @c long value. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the specified @c long value + * @param[in] val A @c long value to get the hash value + */ + static int GetHashCode(long val); + + /** + * Decodes a string into a @c signed @c long. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @remarks This method accepts decimal, hexadecimal, and octal numbers given by the + * following grammar: + * @code + * - DecodableString: + * Sign[opt] DecimalNumeral + * Sign[opt] 0x HexDigits + * Sign[opt] 0X HexDigits + * Sign[opt] # HexDigits + * Sign[opt] 0 OctalDigits + * - Sign: + * '-' + * @endcode + */ + static result Decode(const String& s, long& ret); + + /** + * Parses the @c signed @c long equivalent of the specified string representing a numeric value. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @remarks This method assumes that the string representing the numeric value + * uses a radix 10. + */ + static result Parse(const String& s, long& ret); + + /** + * Parses the @c signed @c long equivalent of the specified string representing a numeric value using the specified radix. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[in] radix The radix of the string representing a numeric value @n + * It must be either 2, 8, 10, or 16. + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @exception E_OUT_OF_RANGE The specified @c radix is invalid. + */ + static result Parse(const String& s, int radix, long& ret); + + /** + * Gets the @c signed @c char equivalent of the current instance of the %Long class. + * + * @since 2.0 + * + * @return The @c signed @c char equivalent of the current instance + */ + virtual char ToChar(void) const; + + /** + * Gets the @c signed @c short equivalent of the current instance of the %Long class. + * + * @since 2.0 + * + * @return The @c signed @c short equivalent of the current instance + */ + virtual short ToShort(void) const; + + /** + * Gets the @c signed @c int equivalent of the current instance of the %Long class. + * + * @since 2.0 + * + * @return The @c signed @c int equivalent of the current instance + */ + virtual int ToInt(void) const; + + /** + * Gets the @c signed @c long equivalent of the current instance of the %Long class. + * + * @since 2.0 + * + * @return The @c signed @c long equivalent of the current instance + */ + virtual long ToLong(void) const; + + /** + * Gets the @c signed @c long @c long equivalent of the current instance of the %Long class. + * + * @since 2.0 + * + * @return The @c signed @c long @c long equivalent of the current instance + */ + virtual long long ToLongLong(void) const; + + /** + * Gets the @c signed @c float equivalent of the current instance of the %Long class. + * + * @since 2.0 + * + * @return The @c signed @c float equivalent of the current instance + */ + virtual float ToFloat(void) const; + + /** + * Gets the @c signed @c double equivalent of the current instance of the %Long class. + * + * @since 2.0 + * + * @return The @c signed @c double equivalent of the current instance + */ + virtual double ToDouble(void) const; + + /** + * Gets the string representing the value of the current instance of the %Long class. + * + * @since 2.0 + * + * @return The string representing the value of the current instance + */ + virtual String ToString(void) const; + + /** + * Gets the string representing the specified @c signed @c long value. + * + * @since 2.0 + * + * @return The string containing a Unicode representation of the specified @c signed @c long value + * @param[in] value A @c signed @c long value to convert + */ + static String ToString(long value); + + /** + * A constant holding the maximum value a @c short can have; 2^31-1. + * + * @since 2.0 + */ + static const long VALUE_MAX = (long) 0x7FFFFFFF; + + /** + * A constant holding the minimum value a @c short can have; -2^31. + * + * @since 2.0 + */ + static const long VALUE_MIN = (long) 0x80000000; + + /** + * A @c long value of this instance. + * + * @since 2.0 + */ + long value; + + +private: + friend class _LongImpl; + class _LongImpl * __pLongImpl; + +}; // Long + +}} // Tizen::Base + +#endif //_FBASE_LONG_H_ diff --git a/inc/FBaseLongComparer.h b/inc/FBaseLongComparer.h new file mode 100644 index 0000000..80ded5c --- /dev/null +++ b/inc/FBaseLongComparer.h @@ -0,0 +1,129 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLongComparer.h + * @brief This is the header file for the %LongComparer class. + * + * @see Long and Tizen::Base::Collection::IComparer + * + * This header file contains the declarations of the %LongComparer class. + */ +#ifndef _FBASE_LONG_COMPARER_H_ +#define _FBASE_LONG_COMPARER_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class LongComparer + * @brief This class checks for equivalence between 2 instances of the Long type. + * + * @since 2.0 + * + * The %LongComparer class checks for equivalence between 2 instances of the Long type. + * + * For more information on the class features, see Collection Comparisons. + * + * The following example demonstrates how to use the %LongComparer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::LongComparerSample(void) + * { + * Long l1(123); + * Long l2(124); + * LongComparer comparer; + * + * int cmp; + * comparer.Compare(l1, l2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +class _OSP_EXPORT_ LongComparer + : public Object + , public virtual Tizen::Base::Collection::IComparer +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + LongComparer(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~LongComparer(void); + + /** + * Compares two given instances of type Long. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 The first instance of type %Long + * @param[in] obj2 The second instance of type %Long + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + LongComparer(const LongComparer& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + LongComparer& operator =(const LongComparer& rhs); + + friend class _LongComparerImpl; + class _LongComparerImpl * __pLongComparerImpl; + +}; // LongComparer + +}} // Tizen::Base + +#endif // _FBASE_LONG_COMPARER_H_ diff --git a/inc/FBaseLongLong.h b/inc/FBaseLongLong.h new file mode 100644 index 0000000..8fe692b --- /dev/null +++ b/inc/FBaseLongLong.h @@ -0,0 +1,325 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLongLong.h + * @brief This is the header file for the %LongLong class. + * + * @see Tizen::Base::Number + * + * This header file contains the declarations of the %LongLong class. + */ +#ifndef _FBASE_LONG_LONG_H_ +#define _FBASE_LONG_LONG_H_ + +#include + + +namespace Tizen { namespace Base +{ +/** + * @class LongLong + * @brief This class is the wrapper class for the @c signed @c long @c long built-in type. + * + * @since 2.0 + * + * The %LongLong class represents an integer value ranging from -9223372036854775808 to 9223372036854775807 + * , that is, -(2^63) to +((2^63)-1). The class is useful when passing a 64-bit @c signed + * integral value to a method that accepts only an instance of Object. Furthermore, + * this class provides methods for converting %LongLong (and @c long @c long) to String, and %String + * to %LongLong (and @c long @c long). + * + * The following example demonstrates how to use the %LongLong class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method checks whether the given string object contains a string + * // representation of the pre-defined minimum 64-bit integral value + * result + * MyClass::Verify(String& string, bool& out) + * { + * static const LongLong MINIMUM(123456789); + * result r = E_SUCCESS; + * + * long long l; + * r = LongLong::Parse(string, l); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * out = (MINIMUM.CompareTo(l) == 0) ? true: false; + * + * return r; + * CATCH: + * return r; + * } + * @endcode + */ +class _OSP_EXPORT_ LongLong + : public Number +{ +public: + /** + * Initializes this instance of %LongLong with the specified value. + * + * @since 2.0 + * + * @param[in] value A @c long @c long value + */ + LongLong(long long value = 0); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %LongLong + */ + LongLong(const LongLong& value); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~LongLong(void); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %LongLong + */ + LongLong& operator =(const LongLong& rhs); + + /** + * Compares two @c long @c long values. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of @c l1 is less than the value of @c l2 + * == 0 if the value of @c l1 is equal to the value of @c l2 + * > 0 if the value of @c l1 is greater than the value of @c l2 + * @endcode + * @param[in] l1 The first @c long @c long value to compare + * @param[in] l2 The second @c long @c long value to compare + */ + static int Compare(long long l1, long long l2); + + /** + * Compares the value of the current instance with the value of the specified instance of the %LongLong class. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @code + * < 0 if the value of the current instance is less than the value of the specified instance + * == 0 if the value of the current instance is equal to the value of the specified instance + * > 0 if the value of the current instance is greater than the value of the specified instance + * @endcode + * @param[in] value An instance of the %LongLong class to compare + */ + int CompareTo(const LongLong& value) const; + + /** + * Checks whether the value of the specified instance of Object is equal to the value of the current instance of %LongLong. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of Object is equal to the value of the current instance of %LongLong, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @see Tizen::Base::Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance of %LongLong. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance of %LongLong + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the value of the current instance. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the hash value of the specified @c long @c long value. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the specified @c long @c long value + * @param[in] val A @c long @c long value to get the hash value + */ + static int GetHashCode(long long val); + + /** + * Gets the @c signed @c char equivalent of the current instance of the %LongLong class. + * + * @since 2.0 + * + * @return The @c signed @c char equivalent of the current instance + */ + virtual char ToChar(void) const; + + /** + * Gets the @c signed @c short equivalent of the current instance of the %LongLong class. + * + * @since 2.0 + * + * @return The @c signed @c short equivalent of the current instance + */ + virtual short ToShort(void) const; + + /** + * Gets the @c signed @c int equivalent of the current instance of the %LongLong class. + * + * @since 2.0 + * + * @return The @c signed @c int equivalent of the current instance + */ + virtual int ToInt(void) const; + + /** + * Gets the @c signed @c long equivalent of the current instance of the %LongLong class. + * + * @since 2.0 + * + * @return The @c signed @c long equivalent of the current instance + */ + virtual long ToLong(void) const; + + /** + * Gets the @c signed @c float equivalent of the current instance of the %LongLong class. + * + * @since 2.0 + * + * @return The @c signed @c float equivalent of the current instance + */ + virtual float ToFloat(void) const; + + /** + * Gets the @c signed @c double equivalent of the current instance of the %LongLong class. + * + * @since 2.0 + * + * @return The @c signed @c double equivalent of the current instance + */ + virtual double ToDouble(void) const; + + /** + * Gets the @c signed @c long @c long equivalent of the current instance of the %LongLong class. + * + * @since 2.0 + * + * @return The @c signed @c long @c long equivalent of the current instance + */ + virtual long long ToLongLong(void) const; + + /** + * Gets the string representing the value of the current instance of the %LongLong class. + * + * @since 2.0 + * + * @return The string representing the value of the current instance + */ + virtual String ToString(void) const; + + /** + * Gets the string representing the specified @c signed @c long @c long value. + * + * @since 2.0 + * + * @return The string containing a Unicode representation of the specified @c signed @c long @c long value + * @param[in] value A @c signed @c long @c long value to convert + */ + static String ToString(long long value); + + /** + * Parses the specified string representing a numeric value and + * returns the value as a @c signed @c long @c long (as out parameter). + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @remarks This method assumes that the string representing the numeric value + * uses a radix 10. + */ + static result Parse(const String& s, long long& ret); + + /** + * Parses the specified string representing a numeric value using the specified radix and + * returns the value as a @c signed @c long @c long (as out parameter). + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[in] radix The radix of the string representing a unmeric value @n + * It must be either 2, 8, 10 or 16. + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @excpetion E_OUT_OF_RANGE The specified @c radix is invalid. + */ + static result Parse(const String& s, int radix, long long& ret); + + /** + * A constant holding the maximum value a @c long @c long can have; 2^63-1. + * + * @since 2.0 + */ + static const long long VALUE_MAX = (long long) 0x7FFFFFFFFFFFFFFFLL; + + /** + * A constant holding the minimum value a @c long @c long can have; -2^63. + * + * @since 2.0 + */ + static const long long VALUE_MIN = (long long) 0x8000000000000000LL; + + /** + * A @c long @c long value of this instance. + * + * @since 2.0 + */ + long long value; + + +private: + friend class _LongLongImpl; + class _LongLongImpl * __pLongLongImpl; + +}; // LongLong + +}} // Tizen::Base + +#endif //_FBASE_LONG_LONG_H_ diff --git a/inc/FBaseLongLongComparer.h b/inc/FBaseLongLongComparer.h new file mode 100644 index 0000000..0d121b5 --- /dev/null +++ b/inc/FBaseLongLongComparer.h @@ -0,0 +1,128 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLongLongComparer.h + * @brief This is the header file for the %LongLongComparer class. + * + * @see Long and Tizen::Base::Collection::IComparer + * + * This header file contains the declarations of the %LongLongComparer class. + */ +#ifndef _FBASE_LONG_LONG_COMPARER_H_ +#define _FBASE_LONG_LONG_COMPARER_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class LongLongComparer + * @brief This class checks for equivalence between 2 instances of the LongLong type. + * + * @since 2.0 + * + * The %LongLongComparer class checks for equivalence between 2 instances of the %LongLong type. + * + * For more information on the class features, see Collection Comparisons. + * + * The following example demonstrates how to use the %LongComparer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::LongLongComparerSample(void) + * { + * LongLong ll1(123); + * LongLong ll2(124); + * LongLongComparer comparer; + * + * int cmp; + * comparer.Compare(ll1, ll2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +class _OSP_EXPORT_ LongLongComparer + : public Object + , public virtual Tizen::Base::Collection::IComparer +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + LongLongComparer(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~LongLongComparer(void); + + /** + * Compares two given instances of type LongLong. + * + * @since 2.0 + * @return An error code + * @param[in] obj1 The first instance of type LongLong + * @param[in] obj2 The second instance of type LongLong + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + LongLongComparer(const LongLongComparer& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + LongLongComparer& operator =(const LongLongComparer& rhs); + + friend class _LongLongComparerImpl; + class _LongLongComparerImpl * __pLongLongComparerImpl; + +}; // LongLongComparer + +}} // Tizen::Base + +#endif // _FBASE_LONG_LONG_COMPARER_H_ diff --git a/inc/FBaseNumber.h b/inc/FBaseNumber.h new file mode 100644 index 0000000..1a55b74 --- /dev/null +++ b/inc/FBaseNumber.h @@ -0,0 +1,174 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseNumber.h + * @brief This is the header file for the %Number class. + * + * This header file contains the declarations and definitions of the %Number class. @n + * This class is the abstract base class of all wrapped numeric types. + */ +#ifndef _FBASE_NUMBER_H_ +#define _FBASE_NUMBER_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Number + * @brief This class is the base class of all wrapped numeric types. + * + * @since 2.0 + * + * The %Number class is the abstract base class of all wrapped numeric classes. + * The subclasses of %Number must provide methods to convert the represented + * numeric value to @c char, @c short, @c int, @c long, @c float, and @c double. + * + * The following example demonstrates how to use the %Number class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::NumberSample(void) + * { + * Long ld(0x12345678L); + * int i = ld.Toint(); // i == 0x5678 + * char ch = ld.ToChar(); // ch == 0x78 or 120 + * // ... + * Int8 j(ch); + * Float f1(j.ToFloat()); // f1 == 120.0 + * // ... + * Double d(120.100005L); + * Float f2(d.ToFloat()); // f2 == 120.10001 + * Integer k(f2.ToInt()); // k == 120 + * } + * @endcode + */ +class _OSP_EXPORT_ Number + : public Object +{ +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Number(void) { }; + + /** + * Gets the @c signed @c char equivalent of the current instance of the %Number class. + * + * @since 2.0 + * + * @return The @c signed @c char equivalent of the current instance + */ + virtual char ToChar(void) const = 0; + + /** + * Gets the @c signed @c short equivalent of the current instance of the %Number class. + * + * @since 2.0 + * + * @return The @c signed @c short equivalent of the current instance + */ + virtual short ToShort(void) const = 0; + + /** + * Gets the @c signed @c int equivalent of the current instance of the %Number class. + * + * @since 2.0 + * + * @return The @c signed @c int equivalent of the current instance + */ + virtual int ToInt(void) const = 0; + + /** + * Gets the @c signed @c long equivalent of the current instance of the %Number class. + * + * @since 2.0 + * + * @return The @c signed @c long equivalent of the current instance + */ + virtual long ToLong(void) const = 0; + + /** + * Gets the @c signed @c long @c long equivalent of the current instance of the %Number class. + * + * @since 2.0 + * + * @return The @c signed @c long @c long equivalent of the current instance + */ + virtual long long ToLongLong(void) const = 0; + + /** + * Gets the @c signed @c float equivalent of the current instance of the %Number class. + * + * @since 2.0 + * + * @return The @c signed @c float equivalent of the current instance + */ + virtual float ToFloat(void) const = 0; + + /** + * Gets the @c signed @c double equivalent of the current instance of the %Number class. + * + * @since 2.0 + * + * @return The @c signed @c double equivalent of the current instance + */ + virtual double ToDouble(void) const = 0; + + /** + * Gets the string representing the value of the current instance of the %Number class. + * + * @since 2.0 + * + * @return The string representing the value of the current instance + */ + virtual String ToString(void) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Number_Reserved1(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Number_Reserved2(void) { } + +}; // Number + +}} // Tizen::Base + +#endif // _FBASE_NUMBER_H_ diff --git a/inc/FBaseObject.h b/inc/FBaseObject.h new file mode 100644 index 0000000..8451d4c --- /dev/null +++ b/inc/FBaseObject.h @@ -0,0 +1,116 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseObject.h + * @brief This is the header file for the %Object class. + * + * This header file contains the declarations of the %Object class. @n + * This class defines a set of behaviors shared by all Tizen classes. + */ +#ifndef _FBASE_OBJECT_H_ +#define _FBASE_OBJECT_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Object + * @brief This class is the @b root class of Tizen. + * + * @since 2.0 + * + * The %Object class defines a set of behaviors and characteristics shared by all the other classes. + * + * The derived classes can override some of these methods, such as the Equals() method, which tests for object equivalence. + */ +class _OSP_EXPORT_ Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Object(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Object(void); + + /** + * Checks whether the value of the specified instance is equal to the value of the current instance of %Object. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of %Object is equal to the value of the current instance of %Object, @n + * else @c false + * @param[in] obj An instance of %Object to compare + * @remarks The default implementation of this method returns @c true + * if the two instances have the same address. @n + * The method can be overridden to support value equality. Furthermore, this method must return the same result as the equality operator. + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance of %Object. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance of %Object + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the address of the current instance. + */ + virtual int GetHashCode(void) const; + +protected: + /** + * This is the copy constructor for the %Object class. + * + * @param[in] obj An instance of %Object + */ + Object(const Object& obj); + + /** + * Assigns the value of the specified instance to the current instance of %Object. + * + * @param[in] rhs An instance of %Object + */ + Object& operator =(const Object& rhs); + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Object_Reserved1(void) { } + +}; // Object + +}} // Tizen::Base + +#endif //_FBASE_OBJECT_H_ diff --git a/inc/FBaseResult.h b/inc/FBaseResult.h new file mode 100644 index 0000000..e10fda5 --- /dev/null +++ b/inc/FBaseResult.h @@ -0,0 +1,103 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseResult.h + * @brief This is the header file for the %Result class. + * + * This header file contains the declaration of the %Result class. + */ +#ifndef _FBASE_RESULT_H_ +#define _FBASE_RESULT_H_ + +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +#define SetLastResultReturn(r) \ + SetLastResult(r); \ + return r; + + +_OSP_EXPORT_ result GetLastResult(void); + +_OSP_EXPORT_ void SetLastResult(result r); + +_OSP_EXPORT_ void ClearLastResult(void); + +struct ErrorTable +{ + result error; + char errorString[50]; +}; + +_OSP_EXPORT_ void RegisterErrorTable(unsigned long package, struct ErrorTable* pErrorTable); + +_OSP_EXPORT_ const char* GetErrorMessage(result value); + +_OSP_EXPORT_ result TransExceptionsExclusiveInternal(result r, result e, int num,...); + +_OSP_EXPORT_ result TransExceptionsInclusiveInternal(result r, result e, int num,...); + +#define NUMARGS(...) (sizeof((result[]){0, ##__VA_ARGS__})/sizeof(result)-1) + +/** +* This macro returns translated exception when the checked exception doesn't correspond with the conditional exceptions. +* In contrast, this macro returns the checked exception if it corresponds with the conditional exceptions. +* +* @since 2.0 +* +* @return The translated exception +* @param[in] r The result that will be checked +* @param[in] e The translated exception +* @param[in] ... The list of exceptions that will be excluded in translation process @n +* All other exceptions than this list will be translated into @c e. +* +* +*/ + +#define TransExceptionsExclusive(r, e, ...) TransExceptionsExclusiveInternal(r, e, NUMARGS(__VA_ARGS__), __VA_ARGS__) + + +/** +* This macro returns translated exception when the checked exception corresponds with the conditional exceptions. +* In contrast, this macro returns the checked exception if it doesn't correspond with the conditional exceptions. +* +* @since 2.0 +* +* @return The translated exception +* @param[in] r The result that will be checked +* @param[in] e The translated exception +* @param[in] ... The list of exceptions that will be included in translation process @n +* All exceptions in this list will be translated into @c e. +* +*/ + +#define TransExceptionsInclusive(r, e, ...) TransExceptionsInclusiveInternal(r, e, NUMARGS(__VA_ARGS__), __VA_ARGS__) + + +#ifdef __cplusplus +} +#endif + +#endif //_FBASE_RESULT_H_ diff --git a/inc/FBaseRt.h b/inc/FBaseRt.h new file mode 100644 index 0000000..2b80d99 --- /dev/null +++ b/inc/FBaseRt.h @@ -0,0 +1,73 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt.h + * @brief This is the header file for the %Runtime namespace. + * + * This header file contains the declarations of the %Runtime namespace. + * + */ + +#ifndef _FBASE_RT_H_ +#define _FBASE_RT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * @namespace Tizen::Base::Runtime + * @brief This namespace contains classes for running applications. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * + * The %Runtime namespace contains classes for running applications. + * The runtime environment includes threading, synchronization objects, + * and timer. + * + * For more information on the %Base::Runtime namespace features, see Runtime. + * + * The following diagram illustrates the relationships between the classes belonging to the %Runtime namespace. + * @image html base_runtime_namespace_classdiagram.png + * + * + * + */ + +namespace Tizen { namespace Base { namespace Runtime +{ + +}}} // Tizen::Base::Runtime + +#endif // _FBASE_RT_H_ diff --git a/inc/FBaseRtEvent.h b/inc/FBaseRtEvent.h new file mode 100644 index 0000000..b3e1cd4 --- /dev/null +++ b/inc/FBaseRtEvent.h @@ -0,0 +1,177 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtEvent.h + * @brief This is the header file for the %Event class. + * + * This file contains the declarations of the %Event class. + */ + +#ifndef _FBASE_RT_EVENT_H_ +#define _FBASE_RT_EVENT_H_ + +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +class IEventArg; +class IEventListener; +/** +* @class Event +* @brief This class provides methods for delivering an event with an argument synchronously and asynchronously. +* @since 2.0 +* +* @code +* +* #include +* +* using namespace Tizen::Base::Runtime; +* +* class MyEventArg : public IEventArg +* { +* public: +* MyEventArg(int t); +* int type; +* }; +* +* MyEventArg::MyEventArg(int t) +* { +* type = t; +* } +* +* class MyEventListener : public IEventListener +* { +* public: +* void OnEventReceived(const IEventArg& arg); +* }; +* +* void +* MyEventListener::OnEventReceived(const IEventArg& arg) +* { +* const MyEventArg* myarg = dynamic_cast (&arg); +* } +* +* class MyEvent : public Event +* { +* protected: +* virtual void FireImpl(IEventListener& listener, const IEventArg& arg); +* }; +* +* void +* MyEvent::FireImpl(IEventListener& listener, const IEventArg& arg) +* { +* MyEventListener* plistener = dynamic_cast (&listener); +* plistener->OnEventReceived(arg); +* } +* +* void +* MyApplication::Test Code(void) +* { +* MyEventListener* mylistener = new MyEventListener(); +* MyEvent* my = new MyEvent(); +* MyEventArg* myarg = new MyEventArg(3); +* my->AddListener(*mylistener); +* my->Fire(*myarg); +* } +* +* @endcode +*/ +class _OSP_EXPORT_ Event + : virtual public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Event(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Event(void); + + /** + * Adds the listener object. + * The added listener can listen to events when they are fired. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener Listener to add + * @param[in] calledByCallerThread true, to call the listener on the caller thread of this method + * false, to call the listener on the thread in which the event is fired. + * @exception E_SUCCESS This method is successful. + * @exception E_OBJ_ALREADY_EXIST The listener already exists. + * @exception E_INVALID_OPERATION calledByCallerThread is set to true but the caller thread is a worker thread. + */ + result AddListener(IEventListener& listener, bool calledByCallerThread = true); + + /** + * Removes the listener object. + * The removed listener cannot listen to events when they are fired. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener Listener to remove + * @exception E_SUCCESS This method is successful. + * @exception E_OBJ_NOT_FOUND The listener is not found. + */ + result RemoveListener(IEventListener& listener); + + /** + * Fires the event with an argument. + * + * @since 2.0 + * + * @return An error code + * @param[in] arg The event argument. + * @exception E_SUCCESS This method is successful. + * @exception E_INVALID_STATE This event has not been initialized. + * + * @remark This takes the ownership of @c arg. So arg should be created on a heap and should not be deleted by caller. + */ + result Fire(IEventArg& arg); + +protected: + /** + * Implement to call the corresponding event listener's method. + * + * @since 2.0 + * + * @param[in] listener The listener instance which is currently processing + * @param[in] arg The event argument that is fired + * + * @remark A derived class must override this method. + */ + virtual void FireImpl(IEventListener& listener, const IEventArg& arg) = 0; + +private: + friend class _EventImpl; + class _EventImpl* __pEventImpl; + +}; // Event + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_EVENT_H_ diff --git a/inc/FBaseRtEventDrivenThread.h b/inc/FBaseRtEventDrivenThread.h new file mode 100644 index 0000000..c44a1ff --- /dev/null +++ b/inc/FBaseRtEventDrivenThread.h @@ -0,0 +1,276 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtEventDrivenThread.h + * @brief This is the header file for the %EventDrivenThread class. + * + * This header file contains the declarations of the %EventDrivenThread class. + */ +#ifndef _FBASE_RT_EVENT_DRIVEN_THREAD_H_ +#define _FBASE_RT_EVENT_DRIVEN_THREAD_H_ + + +#include +#include +#include + +namespace Tizen { namespace Base { class String; }} + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** + * @class EventDrivenThread + * @brief This class is the fundamental class for the asynchronous execution of a thread. + * + * @since 2.0 + * + * The %EventDrivenThread class is the fundamental class for the asynchronous execution of a thread. + * A Tizen native application can execute several threads during its operation from the multi-threading view. + * + * For more information on the class features, see Thread. + * + * @see Tizen::Base::Runtime::EventDrivenThread + * + * The following example demonstrates how to use the %EventDrivenThread class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Runtime; + * + * class MyTimerThread + * : public EventDrivenThread + * , public ITimerEventListener + * { + * public: + * MyTimerThread(void) + * : __pTimer(null) + * , __count(0) + * { + * } + * + * virtual ~MyTimerThread(void) + * { + * delete __pTimer; + * } + * + * result Construct(void) + * { + * return EventDrivenThread::Construct(); + * } + * + * bool OnStart(void) + * { + * __pTimer = new Timer; + * + * __pTimer->Construct(*this); + * + * __pTimer->StartAsRepeatable(1000); + * + * return true; + * } + * + * void OnStop(void) + * { + * __pTimer->Cancel(); + * } + * + * void OnTimerExpired(Timer& timer) + * { + * // Do repetitive tasks + * AppLog("MyTimerThread: OnTimerExpired: %d", __count++); + * } + * + * private: + * Timer* __pTimer; + * int __count; + * }; + * + * void + * MyApplication::StartEventDrivenThreadSample(void) + * { + * __pMyTimerThread = new MyThread; + * + * __pMyTimerThread->Construct(); + * + * __pMyTimerThread->Start(); + * + * } + * + * void + * MyApplication::StopEventDrivenThreadSample(void) + * { + * + * __pMyTimerThread->Quit(); + * + * __pMyTimerThread->Join(); + * + * delete __pMyTimerThread; + * } + * + * @endcode + */ + +class _OSP_EXPORT_ EventDrivenThread + : public Thread +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks After creating an instance of this class, one of the + * Construct() methods must be called explicitly to initialize this instance. + */ + EventDrivenThread(void); + + /** + * Initializes this instance of %EventDrivenThread with the specified thread type, stack size, and priority. + * + * @since 2.0 + * + * @return An error code + * @param[in] stackSize The thread stack size + * @param[in] priority The thread priority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An invalid argument is passed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(long stackSize = DEFAULT_STACK_SIZE, ThreadPriority priority = THREAD_PRIORITY_MID); + + /** + * Initializes this instance of %EventDrivenThread with the specified name, thread type, stack size, and priority. + * + * @since 2.0 + * + * @return An error code + * @param[in] name The name of the thread + * @param[in] stackSize The thread stack size + * @param[in] priority The thread priority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An invalid argument is passed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const Tizen::Base::String& name, long stackSize = DEFAULT_STACK_SIZE, ThreadPriority priority = THREAD_PRIORITY_MID); + + /** + * This is the destructor for this class. + * + * @since 2.0 + * + */ + virtual ~EventDrivenThread(void); + + /** + * Sends a termination request to the thread. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The thread is in an invalid state. + * @exception E_SYSTEM A system error has occurred. + */ + virtual result Quit(void); + + /** + * Called when the thread is started and runs a message loop. + * + * @since 2.0 + * + * @final Although this method is virtual, it must not be overridden. + * If overridden, it may not work as expected. + * + * @return It is just ignored because there is nowhere to take the returned object + * @remarks The default action of this method returns @c null. + */ + virtual Tizen::Base::Object* Run(void); + + /** + * Called before the message loop is started. @n + * If this method returns @c false, the thread is terminated immediately. + * + * @since 2.0 + * + * @return @c true if this thread can be run, @n + * else @c false + * @remarks You can initialize the event or event listener in this method for running this thread. + * + */ + virtual bool OnStart(void); + + /** + * Called after the message loop is stopped. + * + * @since 2.0 + * + * @remarks You can finalize the event or event listener in this method for running this thread. + * + */ + virtual void OnStop(void); + + /** + * Sends a user event to the event-driven thread. + * + * @since 2.0 + * + * @final Although this method is virtual, it must not be overridden. + * If overridden, it may not work as expected. + * + * @return An error code + * @param[in] requestId The user-defined event ID + * @param[in] pArgs A pointer to a list of arguments + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The thread is in an invalid state. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * + * @see OnUserEventReceivedN() + */ + virtual result SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs); + + /** + * Called when the user event is received. + * + * @since 2.0 + * + * @param[in] requestId The user-defined event ID + * @param[in] pArgs A pointer to a list of arguments + * + * @see SendUserEvent() + */ + virtual void OnUserEventReceivedN(RequestId requestId, Tizen::Base::Collection::IList* pArgs); + +private: + EventDrivenThread(const EventDrivenThread& rhs); + EventDrivenThread& operator = (const EventDrivenThread& rhs); + +private: + class _EventDrivenThreadImpl* __pEventDrivenThreadImpl; + friend class _EventDrivenThreadImpl; + +}; // EventDrivenThread + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_EVENT_DRIVEN_THREAD_H_ + diff --git a/inc/FBaseRtIEventArg.h b/inc/FBaseRtIEventArg.h new file mode 100644 index 0000000..0e47bf6 --- /dev/null +++ b/inc/FBaseRtIEventArg.h @@ -0,0 +1,47 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtIEventArg.h + * @brief This is the header file for the %IEventArg class. + * + * This file contains the declarations of the %IEventArg class. + */ + +#ifndef _FBASE_RT_IEVENT_ARG_H_ +#define _FBASE_RT_IEVENT_ARG_H_ + +namespace Tizen { namespace Base { namespace Runtime +{ +/** +* @interface IEventArg +* @brief This is a tagging interface that all event argument must implement. +* @since 2.0 +*/ +class IEventArg +{ +public: + /** + * This is a virtual destructor for this class. + * @since 2.0 + */ + virtual ~IEventArg(void) {} +}; // IEventArg + +} } } // Tizen::Runtime + +#endif // _FBASE_RT_IEVENT_ARG_H_ diff --git a/inc/FBaseRtIEventListener.h b/inc/FBaseRtIEventListener.h new file mode 100644 index 0000000..a5f7278 --- /dev/null +++ b/inc/FBaseRtIEventListener.h @@ -0,0 +1,58 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtIEventListener.h + * @brief This is the header file for the %IEventListener interface. + * + * This header contains the declarations of the %IEventListener interface. + */ +#ifndef _FBASE_RT_I_EVENT_LISTENER_H_ +#define _FBASE_RT_I_EVENT_LISTENER_H_ + + +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** + * @interface IEventListener + * @brief This is a tagging interface that all event listeners must implement. + * + * @since 2.0 + * + * The %IEventListener interface is a tagging interface that all event listeners must implement. + * The event listener can listen when the specific event occurs. The event listener + * has several methods, and each method is called when a specific event occurs. + * + */ +class _OSP_EXPORT_ IEventListener +{ +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~IEventListener(void); +}; // IEventListener + +} } } // Tizen::Runtime + +#endif // _FBASE_RT_I_EVENT_LISTENER_H_ diff --git a/inc/FBaseRtIRunnable.h b/inc/FBaseRtIRunnable.h new file mode 100644 index 0000000..94c04e2 --- /dev/null +++ b/inc/FBaseRtIRunnable.h @@ -0,0 +1,107 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtIRunnable.h + * @brief This is the header file for the %IRunnable interface. + * + * This header file contains the declarations of the %IRunnable interface. + */ +#ifndef _FBASE_RT_I_RUNNABLE_H_ +#define _FBASE_RT_I_RUNNABLE_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ +/** + * @interface IRunnable + * @brief This interface is the basic unit of the task. Also, it is the execution unit of + * the thread. This interface must be inherited by the class whose instances will + * run on the thread. + * + * @since 2.0 + * + * @remarks Classes which inherit the %IRunnable interface must implement the Run() method. + * + * The %IRunnable interface is the basic unit of the task. Also, it is the execution unit of + * the thread. This interface must be inherited by the class whose instances will + * run on the thread. + * @n + * For more information on the class features, see Thread Programming. + * + * @see Thread + * + * The following example demonstrates how to use the %IRunnable interface. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Runtime; + * + * class MyRun + * : public Tizen::Base::Object + * , public Tizen::Base::Runtime::IRunnable + * { + * public: + * Object* Run(void) + * { + * for (int i = 0; i < 10000; ++i) + * { + * // ... + * } + * + * return null; + * } + * } + * + * @endcode + * + * + * + */ +class _OSP_EXPORT_ IRunnable +{ +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~IRunnable(void); + + /** + * Runs the task. @n + * This method is an executable body of the task. In many cases, this method is called by the thread. + * Although this method can return the result of the execution, the returned value might be discarded + * by the executor of this task. + * + * @since 2.0 + * + * @return A pointer to the result of the task, @n + * else @c null + */ + virtual Tizen::Base::Object* Run(void) = 0; +}; // IRunnable + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_I_RUNNABLE_H_ diff --git a/inc/FBaseRtITimerEventListener.h b/inc/FBaseRtITimerEventListener.h new file mode 100644 index 0000000..8020d99 --- /dev/null +++ b/inc/FBaseRtITimerEventListener.h @@ -0,0 +1,72 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtITimerEventListener.h + * @brief This is the header file for the %ITimerEventListener interface. + * + */ +#ifndef _FBASE_RT_I_TIMER_EVENT_LISTENER_H_ +#define _FBASE_RT_I_TIMER_EVENT_LISTENER_H_ + + +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ +class Timer; + +/** + * @interface ITimerEventListener + * @brief This interface is the listener of the timer event. + * + * @since 2.0 + * + * The %ITimerEventListener interface is the listener of the timer event. + * + * For more information on the class features, see Timer. + * + * @see Timer() + */ +class _OSP_EXPORT_ ITimerEventListener + : virtual public IEventListener +{ +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~ITimerEventListener(void) {} + + /** + * Called when the timer has expired. + * + * @since 2.0 + * + * @param[in] timer The timer that has expired + */ + virtual void OnTimerExpired(Timer& timer) = 0; + +}; // ITimerEventListener + +} } } // Tizen::Runtime + + +#endif // _FBASE_RT_I_TIMER_EVENT_LISTENER_H_ diff --git a/inc/FBaseRtIWaitingLoopCondition.h b/inc/FBaseRtIWaitingLoopCondition.h new file mode 100755 index 0000000..c58e632 --- /dev/null +++ b/inc/FBaseRtIWaitingLoopCondition.h @@ -0,0 +1,57 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/* + * @file FBaseRtIWaitingLoopCondition.h + * @brief This is the header file for the %IWaitingLoopCondition interface. + * + */ +#ifndef _FBASE_RT_WAITING_LOOP_CONDITION_H_ +#define _FBASE_RT_WAITING_LOOP_CONDITION_H_ + + +namespace Tizen { namespace Base { namespace Runtime +{ +/* + * @interface IWaitingLoopCondition + * @brief This interface provides the method to check whether the WaitingLoopCondition is met. + * + * @since 2.0 + */ +class _OSP_EXPORT_ IWaitingLoopCondition +{ +public: + /* + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IWaitingLoopCondition(void) {} + + /* + * Check whether the waiting loop condition is met + * + * @since 2.0 + * + */ + virtual bool IsMet(void) = 0; + +}; // IWaitingLoopCondition + +} } } // Tizen::Runtime + +#endif // _FBASE_RT_WAITING_LOOP_CONDITION_H_ diff --git a/inc/FBaseRtLibrary.h b/inc/FBaseRtLibrary.h new file mode 100644 index 0000000..9d5d1bf --- /dev/null +++ b/inc/FBaseRtLibrary.h @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtLibrary.h + * @brief This is the header file for the dynamic linking library class. + * + * This header file contains the declarations of the %Library (DLL) class. + */ + +#ifndef _FBASE_RT_LIBRARY_H_ +#define _FBASE_RT_LIBRARY_H_ + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ +/** + * @class Library + * @brief This is the class for shared library. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Library class loads the shared library with the given file path. + * It loads the library in current process' memory space, and application can use this library explicitly. + */ +class _OSP_EXPORT_ Library + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Library(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Library(void); + + /** + * Initializes this instance of %Library with the specified library path. @n + * Loads the library in the memory space of the current process. + * + * @since 2.0 + * + * @return An error code + * @param[in] libraryPath The path of the library file + * @exception E_SUCCESS The method is successful. + * @exception E_LIBRARY_NOT_FOUND The library cannot be found. + * @exception E_INVALID_ARG The specified @c libraryPath is an empty string. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * + */ + result Construct(const Tizen::Base::String& libraryPath); + + /** + * Gets the address of the specified symbol from the specified dynamic linking library. + * + * @since 2.0 + * + * @return The address of the specified symbol + * @param[in] symbol The symbol name + * @exception E_SUCCESS The method is successful. + * @exception E_SYMBOL_NOT_FOUND The symbol cannot be found. + * @exception E_INVALID_ARG The specified @c symbol is an empty string. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * + */ + void* GetProcAddress(const Tizen::Base::String& symbol) const; + +private: + Library(const Library& rhs); + Library& operator =(const Library& rhs); + +private: + friend class _LibraryImpl; + class _LibraryImpl * __pLibraryImpl; +}; // Library + + +} } } // Tizen::Runtime + + +#endif // _FBASE_RT_LIBRARY_H_ diff --git a/inc/FBaseRtMemoryManager.h b/inc/FBaseRtMemoryManager.h new file mode 100644 index 0000000..85b91a0 --- /dev/null +++ b/inc/FBaseRtMemoryManager.h @@ -0,0 +1,125 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtMemoryManager.h + * @brief This is the header file for the %MemoryManager class. + * + * This header file contains the declarations of the %MemoryManager class. + */ + +#ifndef _FBASE_RT_MEMORY_MANAGER_H_ +#define _FBASE_RT_MEMORY_MANAGER_H_ + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime { + +/** + * @enum MemoryProtectionMode + * + * Defines the memory protection modes. + * + * @since 2.0 + */ +enum MemoryProtectionMode +{ + MEMORY_PROTECTION_MODE_NONE = 0x0, /**< The memory cannot be accessed */ + MEMORY_PROTECTION_MODE_READ = 0x1, /**< The memory can be read */ + MEMORY_PROTECTION_MODE_WRITE = 0x2, /**< The memory can be modified */ + MEMORY_PROTECTION_MODE_EXEC = 0x4, /**< The memory can be executed */ +}; + +/** + * @class MemoryManager + * @brief This class represents a memory manager for runtime. + * + * @since 2.0 + * + * The %MemoryManager class represents a memory manager for runtime. + * + * The following example demonstrates how to use the %MemoryManager class. + * + * @code + * #include + * + * using namespace Tizen::Base::Runtime; + * + * result + * MyApp::Execute(void) + * { + * result r = E_SUCCESS; + * int size = 1024; + * void* pMemory = (void*)malloc(4096); + * + * // Sets to an aligned page + * pMemory = (void*)(((int)pMemory + size) & ~(size - 1)); + * + * // Prepares for execution + * r = MemoryManager::ProtectMemory(pMemory, size, MEMORY_PROTECTION_MODE_EXEC); + * if (IsFailed(r)) + * { + * // Failed to change memory protection + * } + * + * // Executes code in the memory + * + * } + * + * @endcode + */ +class _OSP_EXPORT_ MemoryManager +{ +public: + /** + * Changes protection on a memory region. + * + * @since 2.0 + * + * @return An error code + * @param[in] pAddress The start address of the memory region aligned on a page boundary. + * @param[in] length The length of the memory region in bytes + * @param[in] protection The memory protection @n + * It is either Tizen::Base::Runtime::MEMORY_PROTECTION_MODE_NONE or a bitwise OR of the + * other values in Tizen::Base::Runtime::MemoryProtectionMode. + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred due to an invalid address. + * @exception E_INVALID_ARG The memory address is not valid, or the length is not a multiple of system page size. + */ + static result ProtectMemory(const void* pAddress, long long length, unsigned long protection); + +private: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + MemoryManager(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + ~MemoryManager(void); + +}; // MemoryManager + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_MEMORY_MANAGER_H_ diff --git a/inc/FBaseRtMonitor.h b/inc/FBaseRtMonitor.h new file mode 100644 index 0000000..3f6b8d0 --- /dev/null +++ b/inc/FBaseRtMonitor.h @@ -0,0 +1,380 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtMonitor.h + * @brief This is the header file for the %Monitor class. + * + * This header file contains the declarations of the %Monitor class. + */ + +#ifndef _FBASE_RT_MONITOR_H_ +#define _FBASE_RT_MONITOR_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _MonitorImpl; + +/** + * @class Monitor + * @brief This represents a monitor; a type of synchronization mechanism that provides acquire/release semantics by Enter() / Exit() as well as wait/notify semantics by Wait() / Notify() / NotifyAll(). + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Monitor class represents a monitor. %Monitor is a synchronization mechanism that provides acquire/release semantics by Enter() / Exit() as well as wait/notify semantics by Wait() / Notify() / NotifyAll(). + * + * For more information on the class features, see Monitor. + * + * The following examples demonstrates how to use the %Monitor class. In the examples, 2 classes, Consumer and Producer, share a space. + * Producer writes some data to this space, and Consumer reads it. Consumer and Producer run simultaneously. + * Consumer must not miss the data which Producer writes. In this case, Consumer and Producer share the monitor. + * Producer notifies Consumer that its writing action is done. Consumer waits for this notification, and reads the data after receiving it. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Runtime; + * + * class Producer + * : public Thread + * { + * public: + * + * // This methods creates a new instance of the Producer thread + * Producer(int* pShared, Monitor* pMonitor); + * virtual ~Producer(void); + * + * // This methods waits for a starting Consumer and sets a value to the shared position + * // Finally it notifies the Consumer thread + * virtual Object* Run(void); + * + * private: + * int* __pShared; + * Monitor* __pMonitor; + * }; + * + * Producer::Producer(int* pShared, Monitor* pMonitor) + * : __pShared(pShared) + * , __pMonitor(pMonitor) + * { + * } + * + * Producer::~Producer(void) + * { + * } + * + * Object* + * Producer::Run(void) + * { + * if (__pShared && __pMonitor) + * { + * // Begins a critical region + * result r = __pMonitor->Enter(); + * if (IsFailed(r)) + * { + * goto CATCH2; + * } + * + * // Waits for a starting Consumer + * r = __pMonitor->Wait(); + * if (IsFailed(r)) + * { + * goto CATCH1; + * } + * + * // Produces a number value 6 times + * for (int i = 0; i < 6; i++) + * { + * *__pShared = i; + * + * // Notifies the consumer thread + * r = __pMonitor->Notify(); + * if (IsFailed(r)) + * { + * goto CATCH1; + * } + * + * AppLog("Producer::Run [%d]: Value at shared resource: %d\n", i, *__pShared); + * if (*__pShared == 5) + * { + * break; + * } + * + * // Waits until the consumer thread reads the value + * r = __pMonitor->Wait(); + * } + * + * CATCH1: + * __pMonitor->Exit(); + * } + * + * CATCH2: + * return null; + * } + * + * class Consumer + * : public Thread + * { + * public: + * + * // This methods creates a new instance of the Consumer thread + * Consumer(int* pShared, Monitor* pMonitor); + * virtual ~Consumer(void); + * + * // This methods waits for a notification from the Producer thread and reads a value From the shared position + * virtual Tizen::Base::Object* Run(void); + * + * private: + * int* __pShared; + * Monitor* __pMonitor; + * + * }; + * + * Consumer::Consumer(int* pShared, Monitor* pMonitor) + * : __pShared(pShared) + * , __pMonitor(pMonitor) + * { + * } + * + * Consumer::~Consumer(void) + * { + * } + * + * Object* + * Consumer::Run(void) + * { + * if (__pShared &&__pMonitor) + * { + * // Begins a critical region + * result r = __pMonitor->Enter(); + * if (IsFailed(r)) + * { + * goto CATCH2; + * } + * + * // Notifies the producer thread + * r = __pMonitor->Notify(); + * if (IsFailed(r)) + * { + * goto CATCH1; + * } + * + * // Waits for a notification + * r = __pMonitor->Wait(); + * while (!IsFailed(r)) + * { + * // Notifies the producer thread + * r = __pMonitor->Notify(); + * if (IsFailed(r)) + * { + * goto CATCH1; + * } + * + * AppLog("Consumer::Run: Value at shared resource: %d\n", *__pShared); + * if (*__pShared == 5) + * { + * break; + * } + * + * // Waits for a notification + * r = __pMonitor->Wait(); + * if (IsFailed(r)) + * { + * goto CATCH1; + * } + * } + * + * CATCH1: + * // Exits the monitor + * r = __pMonitor->Exit(); + * } + * + * CATCH2: + * return null; + * } + * + * void + * MyApp::TestProducerConsumer(void) + * { + * result r = E_SUCCESS; + * Monitor* pMonitor = null; + * int* pShared = null; + * + * pMonitor = new Monitor; + * if (pMonitor) + * { + * r = pMonitor->Construct(); + * if (IsFailed(r)) + * { + * AppLog("Failed at Monitor Construct\n"); + * goto CATCH; + * } + * + * pShared = new int; + * if (pShared) + * { + * Producer producer(pShared, pMonitor); + * Consumer consumer(pShared, pMonitor); + * + * producer.Construct(); + * consumer.Construct(); + * + * producer.Start(); + * consumer.Start(); + * + * producer.Join(); + * consumer.Join(); + * } + * } + * + * CATCH: + * delete pShared; + * delete pMonitor; + * } + * + * @endcode + * + */ + +class _OSP_EXPORT_ Monitor + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks After creating an instance of this class, one of the + * Construct() methods must be called explicitly to initialize this instance. + */ + Monitor(void); + + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Monitor(void); + + + /** + * Initializes this instance of %Monitor. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(void); + + /** + * Acquires a lock for a monitor. @n + * Semantically, this method declares the beginning of the critical region for the monitor. This region + * ends with the Exit() method. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful in acquiring the lock. + * @exception E_SYSTEM A system error has occurred. + * @remarks This method will block if called on already locked monitor object until monitor becomes availalbe. + * @see Exit() + */ + result Enter(void); + + + /** + * Releases a lock for a monitor. @n + * Semantically, it declares the ending of the critical region for the monitor that begins with + * the Enter() method. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful in releasing the lock. + * @exception E_SYSTEM A system error has occurred. + * @remarks This method should be called only after acquiring lock by Enter() call + * @see Enter() + */ + result Exit(void); + + /** + * Releases the lock for the monitor and waits for the notification from the other thread. @n + * After receiving the notification, it tries to acquire the lock. + * Semantically, it waits until the other thread notifies it. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks This method should be called only after acquiring lock by Enter() call + * @see Notify(), NotifyAll() + */ + result Wait(void); + + /** + * Notifies one of the waiting threads. @n + * The selection of the notified thread is determined by the Linux scheduling policy. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @see NotifyAll(), Wait() + */ + result Notify(void); + + + /** + * Notifies all waiting threads. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @see Notify(), Wait() + */ + result NotifyAll(void); + +private: + Monitor(const Monitor& rhs); + Monitor& operator =(const Monitor& rhs); + +private: + friend class _MonitorImpl; + class _MonitorImpl * __pMonitorImpl; +}; // Monitor + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_MONITOR_H_ diff --git a/inc/FBaseRtMonitorGuard.h b/inc/FBaseRtMonitorGuard.h new file mode 100644 index 0000000..e5c5944 --- /dev/null +++ b/inc/FBaseRtMonitorGuard.h @@ -0,0 +1,132 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FBaseRtMonitorGuard.h +* @brief This is the header file for the %MonitorGuard class. +* +* This header file contains the declarations of the %MonitorGuard class. +*/ + +#ifndef _FBASE_RT_MONITOR_GUARD_H_ +#define _FBASE_RT_MONITOR_GUARD_H_ + +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** +* @class MonitorGuard +* @brief This class is the RAII style class for %Monitor class. +* +* @since 2.0 +*/ +class MonitorGuard +{ +public: + /** + * This constructor enters the monitored block in a blocking way. + * + * @since 2.0 + * + * @param[in] m The %Monitor instance to be manipulated + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Monitor::Enter() for detailed exceptions + */ + MonitorGuard(Monitor& m) + : __m(m) + , __entered(false) + { + SetLastResult(SetEnteredAndReturn(__m.Enter())); + } + + /** + * This destructor exits the monitored block when going out of a scope + * + * @since 2.0 + * + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Monitor::Exit() for detailed exceptions + */ + ~MonitorGuard(void) + { + result r = E_SUCCESS; + if (__entered) + { + r = __m.Exit(); + __entered = false; + } + SetLastResult(r); + } + + /** + * Returns whether this instance owns the lock on the given monitor at constructor. + * + * @since 2.0 + * + * @return true if the lock is owned, @n + * false otherwise. + */ + bool IsEntered(void) const + { + return __entered; + } + + /** + * Returns whether this instance owns the lock on the given monitor at constructor. @n + * Have same effects to calling IsEntered(). + * + * @since 2.0 + */ + operator bool() const + { + return IsEntered(); + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private + * to prohibit copying of objects. + * + * @since 2.0 + */ + MonitorGuard(const MonitorGuard& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + * + * @since 2.0 + */ + MonitorGuard& operator =(const MonitorGuard& rhs); + + // helper function + result SetEnteredAndReturn(result r) + { + __entered = (r == E_SUCCESS); + return r; + } + +private: + Monitor& __m; + bool __entered; +}; // MonitorGuard + +}}} // Tizen::Base::Runtime + +#endif // _FBASE_RT_MONITOR_GUARD_H_ diff --git a/inc/FBaseRtMutex.h b/inc/FBaseRtMutex.h new file mode 100644 index 0000000..843761a --- /dev/null +++ b/inc/FBaseRtMutex.h @@ -0,0 +1,191 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtMutex.h + * @brief This is the header file for the %Mutex class. + * + * This header file contains the declarations of the %Mutex class. + */ + +#ifndef _FBASE_RT_MUTEX_H_ +#define _FBASE_RT_MUTEX_H_ + +#include +#include + + + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** + * @class Mutex + * @brief This class represents a mutex; a type of synchronization mechanism. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * The %Mutex class represents a mutex; a type of synchronization mechanism. + * It is a binary semaphore. Only one thread can acquire the %Mutex. + * + * For more information on the class features, see Mutex and Semaphore. + * + * @see Semaphore, Thread + * + * The following example demonstrates how to use the %Mutex class. + * + * @code + * #include + * + * using namespace Tizen::Base::Runtime; + * + * class MyMutexApp + * { + * public: + * MyMutexApp(); + * ~MyMutexApp(); + * + * void UpdateCriticalResource(); + * + * private: + * Mutex __mutex; + * int __count; + * }; + * + * MyMutexApp::MyMutexApp() + * : __count(0) + * { + * __mutex.Create(); + * } + * + * MyMutexApp::~MyMutexApp() + * { + * } + * + * void + * MyMutexApp::UpdateCriticalResource() + * { + * __mutex.Acquire(); + * __count++; + * __mutex.Release(); + * } + * + * @endcode + * + */ + +class _OSP_EXPORT_ Mutex + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks After creating an instance of this class, one of + * the Create() methods must be called explicitly to initialize this instance. + */ + Mutex(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Mutex(void); + + /** + * Creates an unnamed mutex. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Create(void); + + /** + * Creates a named mutex. @n + * If a mutex with the specified name already exists, this creates a mutex which references that particular mutex. + * + * @since 2.0 + * + * @return An error code + * @param[in] name The name of the mutex + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Create(const Tizen::Base::String& name); + + /** + * Releases the mutex. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks This method should be called only after acquiring lock by Acquire()/ TryToAcquire() call + */ + result Release(void); + + /** + * Acquires the mutex if it is not acquired. @n + * If the mutex is already acquired by another thread, + * the current thread is blocked until the mutex is released. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks This method will block if called on already locked monitor object until mutex becomes availalbe. + */ + result Acquire(void); + + /** + * Tries to acquire the mutex if it is not acquired. @n + * If the mutex is already acquired by another thread, E_OBJECT_LOCKED is returned. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OBJECT_LOCKED The mutex is already locked. + * @exception E_SYSTEM A system error has occurred. + * @remarks This method will block if called on already locked monitor object until mutex becomes availalbe. + */ + result TryToAcquire(void); + +private: + Mutex(const Mutex& value); + Mutex& operator =(const Mutex& value); + +private: + friend class _MutexImpl; + class _MutexImpl * __pMutexImpl; +}; // Mutex + +} } } // Tizen::Base::Runtime + + +#endif // _FBASE_RT_MUTEX_H_ diff --git a/inc/FBaseRtMutexGuard.h b/inc/FBaseRtMutexGuard.h new file mode 100644 index 0000000..541481b --- /dev/null +++ b/inc/FBaseRtMutexGuard.h @@ -0,0 +1,323 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FBaseRtMutexGuard.h +* @brief This is the header file for the %MutexGuard class. +* +* This header file contains the declarations of the %MutexGuard class. +*/ + +#ifndef _FBASE_RT_MUTEX_GUARD_H_ +#define _FBASE_RT_MUTEX_GUARD_H_ + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** +* @class MutexGuard +* @brief This class is the RAII style class for %Mutex class. +* +* @since 2.0 +* +* The following example demonstrates how to use this %MutexGuard class +* +* @code +* +* #include +* #include +* +* using namespace std; +* using namespace Tizen::Base::Runtime; +* +* class SynchronizedCounter +* { +* public: +* explicit SynchronizedCounter(long long initialValue = 0) +* : __m() +* , __count(initialValue) +* { +* __m.Create(); +* } +* +* SynchronizedCounter(const SynchronizedCounter& rhs) +* : __m() +* , __count(rhs.__count) +* { +* __m.Create(); +* } +* +* SynchronizedCounter& operator =(SynchronizedCounter rhs) +* { +* __count = rhs.__count; +* return *this; +* } +* +* SynchronizedCounter& operator ++() +* { +* IncrementImpl(1); +* return *this; +* } +* +* SynchronizedCounter& operator --() +* { +* IncrementImpl(-1); +* return *this; +* } +* +* bool TryToIncrement(void) +* { +* return TryToIncrementImpl(1); +* } +* +* bool TryToDecrement(void) +* { +* return TryToIncrementImpl(-1); +* } +* +* long long GetCount() const +* { +* return __count; +* } +* +* private: +* void IncrementImpl(int amount) +* { +* MutexGuard lock(__m); +* __count += amount; +* } // The acquired lock will be released when going out of scope +* +* bool TryToIncrementImpl(int amount) +* { +* MutexGuard lock(__m, Try); // Uses predefined Try const object for non-blocking mode locking +* TryReturn(lock.IsLocked(), false, “Failed to lock mutex”); +* __count += amount; +* return true; +* } +* +* Mutex __m; +* long long __count; +* }; +* +* class MyThread +* : public Thread +* { +* public: +* static SynchronizedCounter counter; +* static const long long LOOP_COUNT = 10000000; +* +* virtual Object* Run(void) +* { +* for (long long i = 0; i < LOOP_COUNT; ++i) +* { +* ++counter; +* } +* +* return null; +* } +* }; +* +* SynchronizedCounter MyThread::counter; +* +* void +* ButtonPanel::OnActionPerformed(const Tizen::Ui::Control& source, int actionId) +* { +* switch (actionId) +* { +* case ID_BUTTON: +* { +* static const int NUM_THREADS = 10; +* MyThread thrs[NUM_THREADS]; +* +* __pLabel->SetText(L"Button is clicked!"); +* AppLog("Button is pressed!"); +* +* for (int i = 0; i < NUM_THREADS; ++i) +* { +* thrs[i].Construct(); +* thrs[i].Start(); +* } +* +* for (int i = 0; i < NUM_THREADS; ++i) +* { +* thrs[i].Join(); +* } +* +* AppLog("Total Count = [%lld]", MyThread::counter.GetCount()); +* AppAssertf(MyThread::counter.GetCount() == NUM_THREADS * MyThread::LOOP_COUNT, +* "[Assert] Count is wrong"); +* } +* break; +* } +* Invalidate(true); +* } +* +* @endcode +*/ + +class MutexGuard +{ +public: + /** + * This constructor acquires the lock in a blocking way. + * + * @since 2.0 + * + * @param[in] m The %Mutex instance to be manipulated + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Mutex::Acquire() for detailed exceptions + */ + MutexGuard(Mutex& m) + : __m(m) + , __locked(false) + { + SetLastResult(Lock()); + } + + /** + * This constructor acquires the lock in a non-blocking way. + * + * @since 2.0 + * + * @param[in] m The %Mutex instance to be manipulated + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Mutex::TryToAcquire() for detailed exceptions + */ + MutexGuard(Mutex& m, TryTag) + : __m(m) + , __locked(false) + { + SetLastResult(TryToLock()); + } + + /** + * This destructor releases the lock if acquired when going out of a scope + * + * @since 2.0 + * + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Mutex::Release() for detailed exceptions + */ + ~MutexGuard(void) + { + SetLastResult(Unlock()); + } + + /** + * Returns whether this instance owns the lock on the given mutex at constructor. + * + * @since 2.0 + * + * @return true if the lock is owned, @n + * false otherwise. + */ + bool IsLocked(void) const + { + return __locked; + } + + /** + * Returns whether this instance owns the lock on the given mutex at constructor. @n + * Have same effects to calling IsLocked(). + * + * @since 2.0 + */ + operator bool() const + { + return IsLocked(); + } + + /** + * Acquires the lock manually on the given mutex at constructor in a blocking way + * + * @since 2.0 + * + * @return An error code. + * @see Mutex::Acquire() for detailed exceptions + */ + result Lock(void) + { + return SetLockedAndReturn(__m.Acquire()); + } + + /** + * Acquires the lock manually on the given mutex at constructor in a non-blocking way + * + * @since 2.0 + * + * @return An error code. + * @see Mutex::TryToAcquire() for detailed exceptions + */ + result TryToLock(void) + { + return SetLockedAndReturn(__m.TryToAcquire()); + } + + /** + * Releases the lock manually + * + * @since 2.0 + * + * @return An error code. + * @see Mutex::Release() for detailed exceptions + */ + result Unlock(void) + { + result r = E_SUCCESS; + if (__locked) + { + r = __m.Release(); + __locked = false; + } + return r; + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private + * to prohibit copying of objects. + * + * @since 2.0 + */ + MutexGuard(const MutexGuard& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + * + * @since 2.0 + */ + MutexGuard& operator =(const MutexGuard& rhs); + + // helper function + result SetLockedAndReturn(result r) + { + __locked = (r == E_SUCCESS); + return r; + } + +private: + Mutex& __m; + bool __locked; +}; // MutexGuard + +}}} // Tizen::Base::Runtime + +#endif // _FBASE_RT_MUTEX_GUARD_H_ diff --git a/inc/FBaseRtSemaphore.h b/inc/FBaseRtSemaphore.h new file mode 100644 index 0000000..f4c9f84 --- /dev/null +++ b/inc/FBaseRtSemaphore.h @@ -0,0 +1,193 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtSemaphore.h + * @brief This is the header file for the %Semaphore class. + * + * This header file contains the declarations of the %Semaphore class. + */ + +#ifndef _FBASE_RT_SEMAPHORE_H_ +#define _FBASE_RT_SEMAPHORE_H_ + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ +/** + * @class Semaphore + * @brief This class represents semaphore, a type of synchronization mechanisms. It can provide the acquiring semantics. @n + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Semaphore class represents a semaphore; a type of synchronization mechanism. + * It can provide the acquiring semantics. The semaphore allows the N threads to acquire the semaphore simultaneously. + * + * For more information on the class features, see Mutex and Semaphore. + * + * The following example demonstrates how to use the %Semaphore class. + * + * @code + * #include + * + * using namespace Tizen::Base::Runtime; + * + * class MySemaphoreApp + * { + * public: + * MySemaphoreApp(int count); + * ~MySemaphoreApp(); + * + * void* AccessCriticalResource(); + * + * private: + * Semaphore __sem; + * int __resourceCount; + * }; + * + * MySemaphoreApp::MySemaphoreApp(int count) + * : __resourceCount(count) + * { + * __sem.Create(count); + * } + * + * MySemaphoreApp::~MySemaphoreApp() + * { + * } + * + * void + * MySemaphoreApp::AccessCriticalResource() + * { + * __sem.Acquire(); + * // Code to access critical resource, at max, + * // The number of '__resourceCount' users can enter this section at same time, + * __sem.Release(); + * } + * + * @endcode + * + */ +class _OSP_EXPORT_ Semaphore + : Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks After creating an instance of this class, one of + * the Create() methods must be called explicitly to initialize this instance. + */ + Semaphore(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Semaphore(void); + + + /** + * Creates an unnamed semaphore. + * + * @since 2.0 + * + * @return An error code + * @param[in] count The number of threads that can acquire the semaphore simultaneously @n + * If the count is @c 1, then it is the same as a mutex. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c count is less than @c 0. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Create(int count = 1); + + + /** + * Creates a named semaphore. @n + * If a semaphore with the specified name already exists, this creates a semaphore which references that particular semaphore. + * + * @since 2.0 + * + * @return An error code + * @param[in] name The name of the semaphore + * @param[in] count The number of threads that can acquire the semaphore simultaneously + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c count is less than @c 0. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Create(const Tizen::Base::String& name, int count = 1); + + /** + * Acquires the semaphore if it is not acquired. @n + * If the semaphore is already acquired, the current thread is blocked until the semaphore is released. + * + * @since 2.0 + * + * @return An error code + * @param[in] timeout The period during which the thread tries to acquire the semaphore + * @exception E_SUCCESS The method is successful. + * @exception E_TIMEOUT The operation cannot be completed within the specified time period. @n + * The method has failed to acquire the semaphore because the given time has elapsed. + * @exception E_SYSTEM A system error has occurred. + */ + result Acquire(long timeout = INFINITE); + + /** + * Tries to acquire the semaphore. @n + * If the semaphore is already acquired by another thread, E_OBJECT_LOCKED is returned. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OBJECT_LOCKED The semaphore is already locked. + * @exception E_SYSTEM A system error has occurred. + */ + result TryToAcquire(void); + + /** + * Releases the semaphore. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + result Release(void); + +private: + Semaphore(const Semaphore& rhs); + Semaphore& operator =(const Semaphore& rhs); + +private: + friend class _SemaphoreImpl; + class _SemaphoreImpl * __pSemaphoreImpl; +}; // Semaphore + +} } } // Tizen::Base::Runtime + + +#endif // _FBASE_RT_SEMAPHORE_H_ diff --git a/inc/FBaseRtSemaphoreGuard.h b/inc/FBaseRtSemaphoreGuard.h new file mode 100644 index 0000000..d5c787a --- /dev/null +++ b/inc/FBaseRtSemaphoreGuard.h @@ -0,0 +1,188 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FBaseRtSemaphoreGuard.h +* @brief This is the header file for the %SemaphoreGuard class. +* +* This header file contains the declarations of the %SemaphoreGuard class. +*/ + +#ifndef _FBASE_RT_SEMAPHORE_GUARD_H_ +#define _FBASE_RT_SEMAPHORE_GUARD_H_ + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** +* @class SemaphoreGuard +* @brief This class is the RAII style class for %Semaphore class. +* +* @since 2.0 +*/ +class SemaphoreGuard +{ +public: + /** + * This constructor acquires a semaphore count in a blocking way. + * + * @since 2.0 + * + * @param[in] s The %Semaphore instance to be manipulated + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Semaphore::Acquire() for detailed exceptions + */ + SemaphoreGuard(Semaphore& s) + : __s(s) + , __acquired(false) + { + SetLastResult(Acquire()); + } + + /** + * This constructor acquires a semaphore count in a non-blocking way. + * + * @since 2.0 + * + * @param[in] s The %Semaphore instance to be manipulated + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Semaphore::TryToAcquire() for detailed exceptions + */ + SemaphoreGuard(Semaphore& s, TryTag) + : __s(s) + , __acquired(false) + { + SetLastResult(TryToAcquire()); + } + + /** + * This destructor releases the acquired semaphore count when going out of a scope + * + * @since 2.0 + * + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Semaphore::Release() for detailed exceptions + */ + ~SemaphoreGuard(void) + { + SetLastResult(Release()); + } + + /** + * Returns whether this instance owns a semaphore count on the given semaphore at constructor. + * + * @since 2.0 + * + * @return true if a semaphore is owned, @n + * false otherwise. + */ + bool IsAcquired(void) const + { + return __acquired; + } + + /** + * Returns whether this instance owns a semaphore count on the given semaphore at constructor. @n + * Have same effects to calling IsAcquired(). + * + * @since 2.0 + */ + operator bool() const + { + return IsAcquired(); + } + + /** + * Acquires a semaphore count manually on the given semaphore at constructor in a blocking way + * + * @since 2.0 + * + * @return An error code. + * @see Semaphore::Acquire() for detailed exceptions + */ + result Acquire(void) + { + return SetAcquiredAndReturn(__s.Acquire()); + } + + /** + * Acquires a semaphore count manually on the given semaphore at constructor in a non-blocking way + * + * @since 2.0 + * + * @return An error code. + * @see Semaphore::TryToAcquire() for detailed exceptions + */ + result TryToAcquire(void) + { + return SetAcquiredAndReturn(__s.TryToAcquire()); + } + + /** + * Releases the acquired semaphore count manually + * + * @since 2.0 + * + * @return An error code. + * @see Semaphore::Release() for detailed exceptions + */ + result Release(void) + { + result r = E_SUCCESS; + if (__acquired) + { + r = __s.Release(); + __acquired = false; + } + return r; + } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private + * to prohibit copying of objects. + * + * @since 2.0 + */ + SemaphoreGuard(const SemaphoreGuard& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + * + * @since 2.0 + */ + SemaphoreGuard& operator =(const SemaphoreGuard& rhs); + + // helper function + result SetAcquiredAndReturn(result r) + { + __acquired = (r == E_SUCCESS); + return r; + } + +private: + Semaphore& __s; + bool __acquired; +}; // SemaphoreGuard + +}}} // Tizen::Base::Runtime + +#endif // _FBASE_RT_SEMAPHORE_GUARD_H_ diff --git a/inc/FBaseRtThread.h b/inc/FBaseRtThread.h new file mode 100644 index 0000000..95d9c0c --- /dev/null +++ b/inc/FBaseRtThread.h @@ -0,0 +1,495 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtThread.h + * @brief This is the header file for the %Thread class. + * + * This header file contains the declarations of the %Thread class. + */ +#ifndef _FBASE_RT_THREAD_H_ +#define _FBASE_RT_THREAD_H_ + + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +#if defined(Yield) // For preventing compile errors +#undef Yield +#endif + +namespace Tizen { namespace Base { class String; }} + +namespace Tizen { namespace Base { namespace Runtime +{ + + +/** + * @if OSPDEPREC + * @enum ThreadType + * + * Defines the type of thread. + * + * @brief [Deprecated] + * @deprecated This enum is deprecated. + * + * @since 2.0 + * + * @endif + */ +enum ThreadType +{ + THREAD_TYPE_WORKER = 0, /**< @if OSPDEPREC The worker thread mode @endif */ + THREAD_TYPE_EVENT_DRIVEN, /**< @if OSPDEPREC The event-driven thread mode @endif */ + THREAD_TYPE_MAIN // This enum value is for internal use only. Using this enum value can cause behavioral, + // security-related, and consistency-related issues in the application. + // The main thread mode +}; + +/** + * @enum ThreadPriority + * + * Defines the priority of the thread. + * + * @since 2.0 + * + */ +enum ThreadPriority +{ + THREAD_PRIORITY_HIGH, /**< The high priority*/ + THREAD_PRIORITY_MID, /**< The mid priority*/ + THREAD_PRIORITY_LOW, /**< The low priority*/ +}; + +/** + * @class Thread + * @brief This class is the fundamental class for the asynchronous execution of a thread. + * + * @since 2.0 + * + * @remarks This class supports only worker threads. For event-driven threads, use the EventDrivenThread class. + * + * The %Thread class is the fundamental class for the asynchronous execution of a thread. + * A Tizen native application can execute several threads during its operation from the multi-threading view. + * + * For more information on the class features, see Thread. + * + * @see Tizen::Base::Runtime::EventDrivenThread + * + * The following example demonstrates how to use the %Thread class. + * + * @code + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Runtime; + * + * class MyThread + * : public Thread + * { + * public: + * MyThread(void) + * { + * } + * + * virtual ~MyThread(void) + * { + * } + * + * result Construct(void) + * { + * return Thread::Construct(); + * } + * + * Object* Run(void) + * { + * // Do some task... + * return null; + * } + * }; + * + * void + * MyApplication::ThreadSample(void) + * { + * MyThread* pMyThread = new MyThread; + * + * pMyThread->Construct(); + * + * pMyThread->Start(); + * + * pMyThread->Join(); // Waits until the thread finished the task + * + * delete pMyThread; + * } + * + * @endcode + * + */ + +class _OSP_EXPORT_ Thread + : public Object + , public Tizen::Base::Runtime::IRunnable + +{ +public: + /** + * Default stack size of the thread. + * + * @since 2.0 + * + */ + const static unsigned long DEFAULT_STACK_SIZE = 64 * 1024; + +public: + /** + * Suspends the execution of the current thread for the specified interval. + * + * @since 2.0 + * + * @return An error code + * @param[in] milliSeconds The time, in milliseconds, for which to suspend the execution @n + * A value of zero causes the thread to relinquish the remainder of its time + * slice to any other thread that is ready to run. The time cannot be negative. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A negative time value is passed. + */ + static result Sleep(long milliSeconds); + + /** + * Causes the current thread context to be temporarily paused and allows other threads to execute. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + static result Yield(void); + + /** + * Ends a thread. + * After this method is called, the thread's execution is stopped. + * + * @since 2.0 + * + * @return An error code + * @param[in] exitCode The exit code for the thread @n + * @exception E_SUCCESS The method is successful. + * @remarks Use GetExitCode() for getting the exit code set by this method. + */ + static result Exit(int exitCode = 0x00); + + /** + * Gets the pointer of the currently running %Thread instance. + * + * @since 2.0 + * + * @return A pointer to the currently running thread + */ + static Thread* GetCurrentThread(void); + + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks After creating an instance of this class, one of the + * Construct() methods must be called explicitly to initialize this instance. + */ + Thread(void); + + /** + * @if OSPDEPREC + * Initializes this instance of %Thread with the specified thread type, stack size, and priority. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because the %Thread class does not support event-driven thread any more. Instead, use the EventDrivenThread class instead. + * + * @since 2.0 + * + * @return An error code + * @param[in] threadType The thread type + * @param[in] stackSize The thread stack size + * @param[in] priority The thread priority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An invalid argument is passed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @endif + */ + result Construct(ThreadType threadType, long stackSize = DEFAULT_STACK_SIZE, ThreadPriority priority = THREAD_PRIORITY_MID); + + /** + * @if OSPDEPREC + * Initializes this instance of %Thread with the specified name, thread type, stack size, and priority. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because the %Thread class does not support event-driven thread any more. Instead, use the EventDrivenThread class instead. + * + * @since 2.0 + * + * @return An error code + * @param[in] name The name of the thread + * @param[in] threadType The thread type + * @param[in] stackSize The thread stack size + * @param[in] priority The thread priority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An invalid argument is passed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @endif + */ + result Construct(const Tizen::Base::String& name, ThreadType threadType, + long stackSize = DEFAULT_STACK_SIZE, ThreadPriority priority = THREAD_PRIORITY_MID); + + /** + * Initializes this instance of %Thread with the specified stack size, and priority. + * + * @since 2.0 + * + * @return An error code + * @param[in] stackSize The thread stack size + * @param[in] priority The thread priority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An invalid argument is passed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(long stackSize = DEFAULT_STACK_SIZE, ThreadPriority priority = THREAD_PRIORITY_MID); + + /** + * Initializes this instance of %Thread with the specified name, stack size, and priority. + * + * @since 2.0 + * + * @return An error code + * @param[in] name The name of the thread + * @param[in] stackSize The thread stack size + * @param[in] priority The thread priority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An invalid argument is passed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const Tizen::Base::String& name, + long stackSize = DEFAULT_STACK_SIZE, ThreadPriority priority = THREAD_PRIORITY_MID); + + /** + * Initializes this instance of %Thread with the specified IRunnable instance, stack size, and priority. + * + * @since 2.0 + * + * @return An error code + * @param[in] target An instance of %IRunnable + * @param[in] stackSize The thread stack size + * @param[in] priority The thread priority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An invalid argument is passed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(IRunnable& target, long stackSize = DEFAULT_STACK_SIZE, ThreadPriority priority = THREAD_PRIORITY_MID); + + /** + * Initializes this instance of %Thread with the specified name, IRunnable instance, stack size, and priority. + * + * @since 2.0 + * + * @return An error code + * @param[in] name The name of the thread + * @param[in] target An instance of IRunnable + * @param[in] stackSize The thread stack size + * @param[in] priority The thread priority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An invalid argument is passed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const Tizen::Base::String& name, IRunnable& target, + long stackSize = DEFAULT_STACK_SIZE, ThreadPriority priority = THREAD_PRIORITY_MID); + + + /** + * This is the destructor for this class. + * + * @since 2.0 + * + */ + virtual ~Thread(void); + + /** + * Waits until the thread execution is terminated. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION An other thread is calling this method. + * @exception E_SYSTEM A system error has occurred. + */ + result Join(void); + + /** + * Starts the thread. @n + * The Run() method is called when the thread starts. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + result Start(void); + + /** + * @if OSPDEPREC + * Forces the thread to stop executing. + * + * @brief [Deprecated] + * @deprecated This method is deprecated. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks This is only available for event-driven threads. + * @endif + */ + result Stop(void); + + /** + * Called when the thread is started without the IRunnable instance. @n + * The body for thread execution is specified by inheriting the %Thread class and implementing this method. + * + * @since 2.0 + * + * @return It is just ignored because there is nowhere to take the returned object + * @remarks The default action of this method returns @c null. + */ + virtual Tizen::Base::Object* Run(void); + + /** + * Gets an exit code of the thread which is given by calling the Exit() method. + * + * @since 2.0 + * + * @return An error code + * @param[out] exitCode The exit code for the thread + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The thread is in an invalid state. + * @exception E_SYSTEM A system error has occurred. + */ + result GetExitCode(int& exitCode) const; + + /** + * Gets the name of the thread. + * + * @since 2.0 + * + * @return The name of the thread + * @exception E_SUCCESS The method is successful. + */ + const Tizen::Base::String& GetName(void) const; + + + /** + * @if OSPDEPREC + * Called before the Run() method is executed. @n + * The Run() method is executed if this method returns @c true, and @n + * if this method returns @c false, the thread is terminated immediately. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because the %Thread class does not support event-driven threads. + * + * @since 2.0 + * + * @return @c true if this thread can be run, @n + * else @c false + * @remarks You can initialize the event or event listener in this method for running this + * thread in an event-driven mode. + * @endif + */ + virtual bool OnStart(void); + + /** + * @if OSPDEPREC + * Called after the Run() method is executed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because the %Thread class does not support event-driven threads. + * @since 2.0 + * + * @remarks You can finalize the event or event listener in this method for running this + * thread in an event-driven mode. + * + * @endif + */ + virtual void OnStop(void); + + /** + * @if OSPDEPREC + * Sends a user event to the event-driven thread. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because the %Thread class does not support event-driven threads. + * + * @since 2.0 + * + * @return An error code + * @param[in] requestId The user-defined event Id + * @param[in] pArgs A pointer to a list of arguments + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_OPERATION The thread is not an event-driven thread. + * + * @remarks This is only available for event-driven threads. + * @see OnUserEventReceivedN() + * @endif + */ + virtual result SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs); + + /** + * @if OSPDEPREC + * Called when the user event is received. + * + * @brief [Deprecated] + * @deprecated This method is deprecated because the %Thread class does not support event-driven threads. + * + * @since 2.0 + * + * @param[in] requestId The user-defined event Id + * @param[in] pArgs A pointer to a list of arguments + * @see SendUserEvent() + * @endif + */ + virtual void OnUserEventReceivedN(RequestId requestId, Tizen::Base::Collection::IList* pArgs); + +private: + Thread(const Thread& rhs); + Thread& operator =(const Thread& rhs); + +private: + friend class _ThreadImpl; + class _ThreadImpl* __pThreadImpl; +}; // Thread + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_THREAD_H_ + diff --git a/inc/FBaseRtTimer.h b/inc/FBaseRtTimer.h new file mode 100644 index 0000000..dd15295 --- /dev/null +++ b/inc/FBaseRtTimer.h @@ -0,0 +1,226 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtTimer.h + * @brief This is the header file for the %Timer class. + * + * This header file contains the declarations of the %Timer class. + */ + +#ifndef _FBASE_RT_TIMER_H_ +#define _FBASE_RT_TIMER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ +/** + * @class Timer + * @brief This class provides the timer service. + * + * @since 2.0 + * + * The %Timer class can activate the timer and notify the listeners. + * + * For more information on the class features, see Timer. + * + * The following example demonstrates how to use the %Timer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Runtime; + * + * class MyTimerApp + * : public ITimerEventListener + * , public Object + * { + * public: + * MyTimerApp(); + * ~MyTimerApp(); + * + * void OnTimerExpired(Timer& timer); + * bool IsTimerExpired() const; + * int GetCount() {return __count;}; + * void StartApp(); + * + * private: + * bool __bTimerExpired; + * int __count; + * Timer __timer; + * }; + * + * MyTimerApp::MyTimerApp() + * : __bTimerExpired(false) + * , __count(10) + * { + * __timer.Construct(*this); + * } + * + * MyTimerApp::~MyTimerApp() + * { + * } + * + * void + * MyTimerApp::OnTimerExpired(Timer& timer) + * { + * __count--; + * if (__count == 0) + * { + * __bTimerExpired = true; + * } + * else + * { + * timer.Start(100); + * } + * + * AppLog("TimerApp: Current count: %d\n", __count); + * } + * + * bool + * MyTimerApp::IsTimerExpired() const + * { + * return __bTimerExpired; + * } + * + * void + * MyTimerApp::StartApp() + * { + * __timer.Start(10); + * } + * + * @endcode + * + * @see ITimerEventListener + */ + +class _OSP_EXPORT_ Timer + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Timer(void); + + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Timer(void); + + /** + * Initializes this instance of %Timer with the specified listener. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The event listener + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(ITimerEventListener& listener); + + /** + * Starts the timer. + * + * @if OSPCOMPACT + * @brief [Compatibility] + * @endif + * + * @since 2.0 + * + * @if OSPCOMPACT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompTimerStartPage "here". + * @endif + * + * @return An error code + * @param[in] timeout A timeout interval in milliseconds + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks Once it has been started, it cannot be started again until it expires. @n + * You must cancel it if you want to re-start the timer. + * @see Cancel() + */ + result Start(int timeout); + + /** + * @page CompTimerStartPage Compatibility for Start(int timeout) + * @section CompTimerStartPageIssueSection Issues + * Implementing this method in OSP compatible applications has the following issues: @n + * -# The method returns E_INVALID_ARG if timeout is equal to zero. + * + * @section CompTimerStartPageSolutionSection Resolutions + * This issue has been resolved in Tizen. @n + * -# In case of zero, Timer sets timeout to the best-effort minimum interval without returning E_INVALID_ARG. + */ + + /** + * Starts the timer. @n + * The timer is expired repeatedly until it is canceled. + * + * @since 2.0 + * + * @return An error code + * @param[in] interval A timeout interval in milliseconds + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks To stop timer expiration or restart a timer, the timer must be canceled. + * @see Cancel() + */ + result StartAsRepeatable(int interval); + + /** + * Cancels the timer. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks The timer cannot be canceled if it is not started. + */ + result Cancel(void); + +private: + Timer(const Timer& rhs); + + Timer& operator =(const Timer& rhs); + +private: + friend class _TimerImpl; + class _TimerImpl * __pTimerImpl; + +}; // Timer + +} } } // Tizen::Runtime + +#endif // _FBASE_RT_TIMER_H_ diff --git a/inc/FBaseRtTypes.h b/inc/FBaseRtTypes.h new file mode 100644 index 0000000..9c9b324 --- /dev/null +++ b/inc/FBaseRtTypes.h @@ -0,0 +1,85 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtTypes.h + * @brief This is the header file for types in the Runtime package. + * + * This header file defines the types in the Runtime package. + */ +#ifndef _FBASE_RT_TYPES_H_ +#define _FBASE_RT_TYPES_H_ + +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** +* This method is for internal use only. Using this method can cause behavioral, security-related, +* and consistency-related issues in the application. +* +* @since 2.0 +*/ +enum TimerStatus +{ + TIMER_STATUS_NOT_ACTIVATED, // This enum value is for internal use only. Using this enum can cause behavioral, security-related, and consistency-related issues in the application. + TIMER_STATUS_ACTIVATED, // This enum value is for internal use only. Using this enum can cause behavioral, security-related, and consistency-related issues in the application. + TIMER_STATUS_CANCELED, // This enum value is for internal use only. Using this enum can cause behavioral, security-related, and consistency-related issues in the application. + TIMER_STATUS_EXPIRED, // This enum value is for internal use only. Using this enum can cause behavioral, security-related, and consistency-related issues in the application. + TIMER_STATUS_ACTIVATED_REPEATABLE, // This enum value is for internal use only. Using this enum can cause behavioral, security-related, and consistency-related issues in the application. +}; + +/** +* @struct TryTag +* @brief This struct is used only for supporting non-blocking acquisition of a resource +* +* This struct is used for just discriminating between blocking and non-blocking acquisition +* of a resource. So, the definition is empty. +* +* @since 2.0 +* +* @see MutexGuard, SemaphoreGuard, Try +*/ +struct TryTag +{ +}; + +/** +* @brief Used only for for just discriminating between blocking and non-blocking acquisition +* +* @code +* Mutex m; +* m.Create(); +* { +* MutexGuard guard(m, Try); +* // Access to shared resources +* } +* +* Semaphore s; +* s.Create(); +* { +* SemaphoreGuard guard(s, Try); +* // Access to multiple shared resources +* } +* @endcode +*/ +static const TryTag Try = {}; + +} } } // Tizen::Runtime + +#endif // _FBASE_RT_TYPES_H_ diff --git a/inc/FBaseRtWaitingLoop.h b/inc/FBaseRtWaitingLoop.h new file mode 100755 index 0000000..5ec4eb5 --- /dev/null +++ b/inc/FBaseRtWaitingLoop.h @@ -0,0 +1,151 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/* + * @file FBaseRtWaitingLoop.h + * @brief This is the header file for the %WaitingLoop class. + * + * This file contains the declarations of the %WaitingLoop class. + */ + +#ifndef _FBASE_RT_WAITING_LOOP_H_ +#define _FBASE_RT_WAITING_LOOP_H_ + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +class IWaitingLoopCondition; +/* + * @class WaitingLoop + * @brief This class allows developers to make the current thread wait for callback events. This class should be used only for test codes and don't use this class for commercial applications + * @since 2.0 + * + * @final This class is not intended for extension. + */ +class _OSP_EXPORT_ WaitingLoop + : public Tizen::Base::Object +{ +public: + /* + * Gets the WaitingLoop instance. + * + * @since 2.0 + * + * @return A pointer to the WaitingLoop instance, @n + * else @c null if it fails + * @remarks Once the WaitingLoop instance has been created, you must not use the instance between threads. Especially, the methods for waiting should be called on the thread you get the instance at first time. + */ + static WaitingLoop* GetInstance(void); + + /* + * Starts the waiting loop and waits until the time is expired. + * + * @since 2.0 + * + * @param[in] timeout The timeout period in milliseconds + * @exception E_SUCCESS The method is successful. + * @exception E_TIMEOUT The time is expired. + * @exception E_INVALID_STATE The waiting loop has already been waiting on a callback event. In order to wait again, you must quit the waiting loop. + * @remarks The timeout set to min(timeout, maximum), where the maximum is set using SetMaxTimeoutForWaiting(). + * @see Notify(), SetMaxTimoutForWaiting() + */ + result Wait(int timeout); + + /* + * Starts the waiting loop and waits until the specified condition is met. + * + * @since 2.0 + * + * @param[in] condition The expiring condition + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The waiting loop has already been waiting on a callback event. In order to wait again, you must quit the waiting loop. + * @remarks In order to use this method correctly, you have to implement a class inheriting from %IWaitingLoopCondition. + */ + result Wait(IWaitingLoopCondition& condition); + + /* + * Starts the waiting loop and waits until either the expiring condition occurs or the time is expired. + * + * @since 2.0 + * + * @param[in] timeout The timeout period in milliseconds + * @param[in] condition The expiring condition + * @exception E_TIMEOUT The time is expired. + * @exception E_INVALID_STATE The waiting loop is waiting on a thread. In order to wait again, you must quit the waiting loop. + * @remarks If the timeout is over the maximum, the expired time goes together with the maximum timeout. In order to use this method correctly, you have to implement a class inheriting from %IWaitingLoopCondition interface + */ + result Wait(int timeout, IWaitingLoopCondition& condition); + + /* + * Notify the waiting thread that the related callback has completed the job. + * + * @since 2.0 + * + * @remarks This method is recommended to use when the waiting condition is not explicitly specified with Wait(). + */ + void Notify(void); + + /* + * Sets the maximum timeout for waiting. + * + * @since 2.0 + * + * @param[in] timeout The timeout period in milliseconds + * else @c false + * @remarks If the timeout is considered as a small number, it will be replaced with the specified number provided by platform. + */ + static void SetMaxTimeoutForWaiting(int timeout); + +private: + // + // This default constructor is intentionally declared as private to implement the %Singleton semantic. + // + // @since 2.0 + // + WaitingLoop(void); + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + WaitingLoop(const WaitingLoop& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and delcared as private to prohibit copying of objects. + // + // @since 2.0 + // + WaitingLoop& operator =(const WaitingLoop& rhs); + + // + // This destructor is intentionally declared as private to implement the %Singleton semantic. + // + // @since 2.0 + // + virtual ~WaitingLoop(void); + + friend class _WaitingLoopImpl; + class _WaitingLoopImpl* __pWaitingLoopImpl; +}; // WaitingLoop + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_WAITING_LOOP_H_ diff --git a/inc/FBaseShort.h b/inc/FBaseShort.h new file mode 100644 index 0000000..d006439 --- /dev/null +++ b/inc/FBaseShort.h @@ -0,0 +1,368 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseShort.h + * @brief This is the header file for the %Short class. + * + * @see Number() + * + * This header file contains the declarations of the %Short class. + */ +#ifndef _FBASE_SHORT_H_ +#define _FBASE_SHORT_H_ + +#include + + +namespace Tizen { namespace Base +{ +/** + * @class Short + * @brief This class is the wrapper class for the @c signed @c short built-in type. + * + * @since 2.0 + * + * The %Short class represents an integer value ranging from -32768 to 32767. The class is useful when passing + * a 16-bit @c signed integral value to a method that accepts only an instance of Object. Furthermore, + * this class provides methods for converting a %Short (and @c short) to a String, and a %String to %Short + * (and @c short). + * + * The following example demonstrates how to use the %Short class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * // This method checks whether the given string object contains a string + * // representation of the pre-defined minimum 16-bit integral value + * result + * MyClass::Verify(String& string, bool& out) + * { + * static const Short MINIMUM(1230); + * + * result r = E_SUCCESS; + * + * short s; + * r = Short::Parse(string, s) + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * out = (MINIMUM.Compare(s) == 0) ? true: false; + * + * return r; + * CATCH: + * return r; + * } + * @endcode + */ +class _OSP_EXPORT_ Short + : public Number +{ +public: + /** + * Initializes this instance of %Short with the specified @c value. + * + * @since 2.0 + * + * @param[in] value A @c short value + */ + Short(short value = 0); + + /** + * This is the copy constructor for the %Short class. + * + * @since 2.0 + * + * @param[in] value An instance of %Short + */ + Short(const Short& value); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~Short(void); + + /** + * Assigns the value of the specified instance to the current instance of %Short. + * + * @since 2.0 + * + * @param[in] rhs An instance of %Short + */ + Short& operator =(const Short& rhs); + + /** + * Compares the specified @c short values. + * + * @since 2.0 + * + * @return A 32-bit @c signed @c integer value + * @param[in] s1 The first @c short value to compare + * @param[in] s2 The second @c short value to compare + * + * @code + * < 0 if @c s1 is less than @c s2 + * == 0 if @c s1 is equal to @c s2 + * > 0 if @c s1 is greater than @c s2 + * @endcode + */ + static int Compare(short s1, short s2); + + /** + * Compares the value of the current instance of the %Short class + * with the value of the specified instance of the %Short class. + * + * @since 2.0 + * + * @return A @c signed 32-bit @c integer value + * @param[in] value An instance of the %Short class to compare + * + * @code + * < 0 if the value of the current instance is less than that of the specified instance + * == 0 if the value of the current instance is equal to that of the specified instance + * > 0 if the value of the current instance is greater than that of the specified instance + * @endcode + */ + int CompareTo(const Short& value) const; + + /** + * Checks whether the value of the specified instance of Object is equal to the value of the current instance of %Short. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of Object is equal to the value of the current instance of %Short, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @remarks The method returns @c false if the specified object is not of the + * type @c short. + * @see Tizen::Base::Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + + /** + * Checks whether the value of the current instance is equal to the specified @c short value. + * + * @since 2.0 + * + * @return @c true if the value of the current instance is equal to the specified @c short value, @n + * else @c false + * @param[in] value A @c short value to compare + */ + bool Equals(short value) const; + + /** + * Gets the hash value of the current instance of %Short. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance of %Short + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the value of the current instance. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the hash value of the specified @c short value. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the specified @c short value + * @param[in] val A @c short value to get the hash value + */ + static int GetHashCode(short val); + + /** + * Decodes a string into a @c signed @c short. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @remarks This method accepts decimal, hexadecimal, and octal numbers given by the + * following grammar: + * + * @code + * - DecodableString: + * Sign[opt] DecimalNumeral + * Sign[opt] 0x HexDigits + * Sign[opt] 0X HexDigits + * Sign[opt] # HexDigits + * Sign[opt] 0 OctalDigits + * - Sign: + * '-' + * @endcode + */ + static result Decode(const String& s, short& ret); + + /** + * Parses the specified string representing a numeric value and + * returns the value as @c signed @c short. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @remarks The method assumes that the string representing the numeric value + * uses radix 10. + */ + static result Parse(const String& s, short& ret); + + /** + * Parses the specified string representing a numeric value + * using the specified radix and returns the value as @c signed @c short. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A string representing a numeric value + * @param[in] radix The radix of the string representing a numeric value @n + * It must either be @c 2, @c 8, @c 10, or @c 16. + * @param[out] ret The result of the operation + * @exception E_SUCCESS The method is successful. + * @exception E_NUM_FORMAT The specified string does not contain a number that can be parsed. + * @exception E_OUT_OF_RANGE The specified @c radix is invalid. + */ + static result Parse(const String& s, int radix, short& ret); + + /** + * Gets the @c signed @c char equivalent of the current instance of the %Short class. + * + * @since 2.0 + * + * @return A @c signed @c char equivalent of the current instance + */ + virtual char ToChar(void) const; + + /** + * Gets the @c signed @c short equivalent of the current instance of the %Short class. + * + * @since 2.0 + * + * @return A @c signed @c short equivalent of the current instance + */ + virtual short ToShort(void) const; + + /** + * Gets the @c signed @c int equivalent of the current instance of the %Short class. + * + * @since 2.0 + * + * @return A @c signed @c int equivalent of the current instance + */ + virtual int ToInt(void) const; + + /** + * Gets the @c signed @c long equivalent of the current instance of the %Short class. + * + * @since 2.0 + * + * @return A @c signed @c long equivalent of the current instance + */ + virtual long ToLong(void) const; + + /** + * Gets the @c signed @c long @c long equivalent of the current instance of the %Short class. + * + * @since 2.0 + * + * @return A @c signed @c long @c long equivalent of the current instance + */ + virtual long long ToLongLong(void) const; + + /** + * Gets the @c signed @c float equivalent of the current instance of the %Short class. + * + * @since 2.0 + * + * @return A @c signed @c float equivalent of the current instance + */ + virtual float ToFloat(void) const; + + /** + * Gets the @c signed @c double equivalent of the current instance of the %Short class. + * + * @since 2.0 + * + * @return A @c signed @c double equivalent of the current instance + */ + virtual double ToDouble(void) const; + + /** + * Gets the string representing the value of the current instance of the %Short class. + * + * @since 2.0 + * + * @return A string representing the value of the current instance + */ + virtual String ToString(void) const; + + /** + * Gets the string representing the specified @c signed @c short value. + * + * @since 2.0 + * + * @return A string containing a Unicode representation of the specified @c signed @c short value + * @param[in] value A @c signed @c short value to convert + */ + static String ToString(short value); + + /** + * A constant holding the maximum value a @c short will be equal to 2^15-1. + * + * @since 2.0 + */ + static const short VALUE_MAX = (short) 0x7FFF; + + /** + * A constant holding the minimum value a @c short will be equal to -2^15. + * + * @since 2.0 + */ + static const short VALUE_MIN = (short) 0x8000; + + /** + * A @c short value of this instance. + * + * @since 2.0 + */ + short value; + + +private: + friend class _ShortImpl; + class _ShortImpl * __pShortImpl; + +}; // Short + +}} // Tizen::Base + +#endif //_FBASE_SHORT_H_ diff --git a/inc/FBaseShortComparer.h b/inc/FBaseShortComparer.h new file mode 100644 index 0000000..41257f7 --- /dev/null +++ b/inc/FBaseShortComparer.h @@ -0,0 +1,130 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseShortComparer.h + * @brief This is the header file for the %ShortComparer class. + * + * @see Short + * @see Tizen::Base::Collection::IComparer + * + * This header file contains the declarations of the %ShortComparer class. + */ +#ifndef _FBASE_SHORT_COMPARER_H_ +#define _FBASE_SHORT_COMPARER_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class ShortComparer + * @brief This class compares 2 instances of the Short type for equivalence. + * + * @since 2.0 + * + * The %ShortComparer class compares 2 instances of the Short type for equivalence. + * + * For more information on the class features, see Collection Comparisons. + * + * The following example demonstrates how to use the %ShortComparer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::ShortComparerSample(void) + * { + * Short s1(123); + * Short s2(124); + * ShortComparer comparer; + * + * int cmp; + * comparer.Compare(s1, s2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +class _OSP_EXPORT_ ShortComparer + : public Object + , public virtual Tizen::Base::Collection::IComparer +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + ShortComparer(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~ShortComparer(void); + + /** + * Compares two given instances of type Short. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 An object of Short to compare + * @param[in] obj2 An object of Short to compare + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + ShortComparer(const ShortComparer& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + ShortComparer& operator =(const ShortComparer& rhs); + + friend class _ShortComparerImpl; + class _ShortComparerImpl * __pShortComparerImpl; + +}; // ShortComparer + +}} // Tizen::Base + +#endif // _FBASE_SHORT_COMPARER_H_ diff --git a/inc/FBaseString.h b/inc/FBaseString.h new file mode 100644 index 0000000..37fbb36 --- /dev/null +++ b/inc/FBaseString.h @@ -0,0 +1,1111 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseString.h + * @brief This is the header file for the %String class. + * + * This header file contains the declarations of the %String class. + */ +#ifndef _FBASE_STRING_H_ +#define _FBASE_STRING_H_ + +#include + + +namespace Tizen { namespace Base +{ +/** + * @class String + * @brief This class represents a mutable sequence of Unicode characters. + * + * @since 2.0 + * + * The %String class represents a mutable sequence of Unicode characters. Operations that change the Unicode text, such as append, insert, and remove, are contained in the %String class. + * + * For more information on the class features, see String. + * + * The following example demonstrates how to use the %String class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::StringSample(void) + * { + * String str; // capacity == 16, length == 0 + * + * str.Append((int)100); // str == L"100" + * + * str.Insert(L"abc", 0); // str == L"abc100" + * + * String str2(L"STRING TEST"); + * + * String subStr; + * + * str2.SubString(7, 4, subStr); // subStr == L"TEST" + * } + * @endcode + */ +class _OSP_EXPORT_ String + : public Object +{ +public: + /** + * This is the default constructor for this class. @n + * It creates an empty %String instance with the default capacity of @c 16 bytes. + * + * @since 2.0 + */ + String(void); + + /** + * Initializes this instance of %String with the specified capacity. + * + * @since 2.0 + * + * @param[in] capacity The default capacity of this instance + */ + String(int capacity); + + /** + * Initializes this instance of %String with the specified Unicode character. + * + * @since 2.0 + * + * @param[in] ch A Unicode character + */ + String(const wchar_t ch); + + /** + * Initializes this instance of %String with the specified Unicode string. + * + * @since 2.0 + * + * @param[in] pValue A pointer to an array of Unicode characters + */ + String(const wchar_t* pValue); + + /** + * Initializes this instance of %String with the specified character string. + * + * @since 2.0 + * + * @param[in] pValue A pointer to an array of UTF-8 characters + */ + String(const char* pValue); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %String + */ + String(const String& value); + + /** + * TThis destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + * + * @remarks The internally allocated memory block is freed when the instance is destroyed. + */ + virtual ~String(void); + + /** + * Returns the Unicode character at the specified @c index. + * + * @since 2.0 + * + * @return A const reference to the Unicode character + * @param[in] index An index within the current instance of %String + */ + const wchar_t& operator [](int index) const; + + /** + * Returns a reference to the Unicode character at the specified @c index. + * + * @since 2.0 + * + * @return A reference to the Unicode character + * @param[in] index An index within the current instance of %String + */ + wchar_t& operator [](int index); + + /** + * Copies the text from the specified + * Unicode string to the calling instance of %String. + * + * @since 2.0 + * + * @return A reference to the %String instance + * @param[in] pRhs A pointer to an array of Unicode characters + */ + String& operator =(const wchar_t* pRhs); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return A reference to the %String instance + * @param[in] rhs An instance of %String + */ + String& operator =(const String& rhs); + + /** + * Appends the text from the specified array of Unicode characters + * to the calling instance of %String. + * + * @since 2.0 + * + * @return A reference to the %String instance + * @param[in] pRhs A pointer to an array of Unicode characters + */ + String& operator +=(const wchar_t* pRhs); + + /** + * Appends the text from the specified instance of %String + * to the calling instance of %String. + * + * @since 2.0 + * + * @return A reference to the %String instance + * @param[in] rhs An instance of %String to copy + */ + String& operator +=(const String& rhs); + + /** + * Concatenates the two strings. + * + * @since 2.0 + * + * @return The concatenated %String instance + * @param[in] lhs A reference to the %String instance on the left-hand side of the operator + * @param[in] rhs A reference to the %String instance on the right-hand side of the operator + */ + _OSP_EXPORT_ friend String operator +(const String& lhs, const String& rhs); + + /** + * Checks the two strings for equality. + * + * @since 2.0 + * + * @return @c true if the text of the specified %String instance equals the calling instance's text, @n + * else @c false + * @param[in] rhs A reference to the %String instance on the right-hand side of the operator + * @remarks The operator performs an ordinal comparison of each Unicode character. + */ + bool operator ==(const String& rhs) const; + + /** + * Checks the two strings for inequality. + * + * @since 2.0 + * + * @return @c true if the text of the specified %String instance is not equal to the calling instance's text, @n + * else @c false + * @param[in] rhs A reference to the %String instance on the right-hand side of the operator + * @remarks The operator performs an ordinal comparison of each Unicode character. + */ + bool operator !=(const String& rhs) const; + + /** + * Checks whether the string is empty. + * + * @since 2.0 + * + * @return @c true if the current instance is a zero-length %String instance L"", @n + * else @c false + */ + bool IsEmpty(void) const; + + /** + * Appends the specified @c wchar_t value to this %String instance after converting it. + * + * @since 2.0 + * + * @return An error code + * @param[in] ch A @c wchar_t value to insert + * @exception E_SUCCESS The method is successful. + */ + result Append(wchar_t ch); + + /** + * Appends the specified @c char value to this %String instance after converting it. + * + * @since 2.0 + * + * @return An error code + * @param[in] ch A @c char value to insert + * @exception E_SUCCESS The method is successful. + */ + result Append(char ch); + + /** + * Appends the string representing the specified 32-bit @c int value to this + * instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] i A 32-bit integer value to insert + * @exception E_SUCCESS The method is successful. + */ + result Append(int i); + + /** + * Appends the string representing the specified @c short value to this + * instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A @c short value to insert + * @exception E_SUCCESS The method is successful. + */ + result Append(short s); + + /** + * Appends the string representing the specified @c long value to this + * instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] l A @c long value to insert + * @exception E_SUCCESS The method is successful. + */ + result Append(long l); + + /** + * Appends the string representing the specified @c long @c long value to this + * instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] ll A @c long @c long value to insert + * @exception E_SUCCESS The method is successful. + */ + result Append(long long ll); + + /** + * Appends the string representing the specified @c float value to this + * instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] f A @c float value to insert + * @exception E_SUCCESS The method is successful. + */ + result Append(float f); + + /** + * Appends the string representing the specified @c double value to this + * instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] d A @c double value to insert + * @exception E_SUCCESS The method is successful. + */ + result Append(double d); + + /** + * Appends the specified null-terminated Unicode text to this instance + * of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] p A pointer to a Unicode character array + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A @c null pointer is passed. + */ + result Append(const wchar_t* p); + + /** + * Appends the specified instance of %String to this instance + * of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] str An instance of %String to append + * @exception E_SUCCESS The method is successful. + */ + result Append(const String& str); + + /** + * Clears the current instance and sets it to an empty %String instance. @n + * The capacity is set to @c 16 bytes, which is the default capacity. + * + * @since 2.0 + */ + void Clear(void); + + /** + * Compares the values of the two strings. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @param[in] str0 The first %String instance to compare + * @param[in] str1 The second %String instance to compare + * @remarks The method performs an ordinal comparison of each Unicode + * character contained in the two given %String instances. + * For instance, "U+xxx" is greater than "U+XXX", but smaller than "U+yyy". + * + * @code + * < 0 if the value of the first instance is less than the value of the second instance + * == 0 if the value of the first instance is equal to the value of the second instance + * > 0 if the value of the first instance is greater than the value of the second instance + * @endcode + */ + static int Compare(const String& str0, const String& str1); + + /** + * Compares the value of the current instance to the value of the specified instance + * of %String. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + *@code + * < 0 if the value of the current instance is less than the value of the specified %String instance + * == 0 if the value of the current instance is equal to the value of the specified %String instance + * > 0 if the value of the current instance is greater than the value of the specified %String instance + *@endcode + * @param[in] str An instance of %String to compare + * @remarks The method performs an ordinal comparison of each Unicode character. For instance, + * L"U+xxx" is greater than L"U+XXX", but smaller than L"U+yyy". + */ + int CompareTo(const String& str) const; + + /** + * Ensures that the specified length is less than or equal to the capacity of + * the current instance of %String. @n + * Otherwise, it expands the capacity of the internal buffer to a value that is greater than or equal to the specified length. + * + * @since 2.0 + * + * @return An error code + * @param[in] minLength A minimum length to ensure + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c minLength is negative. + */ + result EnsureCapacity(int minLength); + + /** + * Checks whether the value of the specified instance of Object is equal to the value of the current instance of %String. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of Object is equal to the value of the current instance of %String, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @remarks The method returns @c false if the specified @c obj is not a string. + * @see Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Checks whether the value of the specified instance is equal to the value of the current instance of %String. @n + * Case sensitivity can be controlled. + * + * @since 2.0 + * + * @return @c true if the values match, @n + * else @c false + * @param[in] str An instance of %String to compare with the + * calling instance + * @param[in] caseSensitive Set to @c true to perform a case sensitive ordinal comparison of the strings, @n + * else @c false + * + * @remarks The method performs an ordinal comparison of each Unicode + * character contained in the two given %String instances. + */ + bool Equals(const String& str, bool caseSensitive) const; + + /** + * Formats the inputs as per the specified format and sets the value of the calling instance to the resultant string. + * + * @since 2.0 + * + * @return An error code + * @param[in] length The maximum number of wide characters to write, including the terminating @c null character + * @param[in] pFormat The wide character format specifier + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c length is negative or @c pFormat is @c null. + * @remarks If an "l" modifier is present in @c pFormat (for example, L"@%ls"), it is a pointer to an array of wide characters. @n + * @remarks A pointer to an array of UTF-8 characters is not allowed in the Format() method (for example, Format(20, L"@%s", pUTF8Str)). + * The following format specifiers are supported in this method: + * @code + * specifier Output + * --------- ------ + * c single byte character + * d(or i) signed decimal integer + * u unsigned decimal integer + * x unsigned hexadecimal integer + * f decimal floating point + * e scientific notation using e character + * g use the shorter of %e or %f + * s single byte character string + * ls(or S) wide-character string + * lld 64-bit signed decimal integer + * + * @endcode + * + * The following example demonstrates how to use the %Format() method. + * @code + * + * String str; + * + * int value = 10; + * wchar_t* testStr = L"TEST"; + * + * str.Format(25, L"FORMAT %d %ls", value, testStr); // str == L"FORMAT 10 TEST" + * + * @endcode + */ + result Format(int length, const wchar_t* pFormat, ...); + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the hash function used must generate a random distribution + * for all inputs. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the character at the specified position. + * + * @since 2.0 + * + * @return An error code + * @param[in] indexAt The position of the character + * @param[out] ch The character at the specified index + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result GetCharAt(int indexAt, wchar_t& ch) const; + + /** + * Searches for a character in the calling instance. @n + * Gets the index of the first character that matches to + * the specified character in this instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] ch The Unicode character to locate + * @param[in] startIndex The starting position of search + * @param[out] indexOf The index of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified character is not found. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c startIndex is either greater than or equal to the length of the current instance or less than @c 0. + */ + result IndexOf(wchar_t ch, int startIndex, int& indexOf) const; + + /** + * Searches for a specified substring in the calling instance. @n + * Gets the starting index of the first occurrence of the specified substring. + * + * @since 2.0 + * + * @return An error code + * @param[in] str An instance of %String to locate + * @param[in] startIndex The starting position of the search + * @param[out] indexOf The index of the substring + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified string is not found. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c startIndex is either greater than or equal to the length of the current instance or less than @c 0. + */ + result IndexOf(const String& str, int startIndex, int& indexOf) const; + + /** + * Inserts the string representing the specified Unicode character + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * + * @param[in] ch A Unicode character to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(wchar_t ch, int indexAt); + + /** + * Inserts the string representing the specified @c char value + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * + * @param[in] ch A @c char value to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(char ch, int indexAt); + + /** + * Inserts the string representing the specified 16-bit integer + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] s A 16-bit integer value to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(short s, int indexAt); + + /** + * Inserts the string representing the specified 32-bit integer + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] i A 32-bit integer value to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(int i, int indexAt); + + /** + * Inserts the string representing the specified @c long value + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] l A @c long value to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(long l, int indexAt); + + /** + * Inserts the string representing the specified @c long @c long value + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] ll A @c long @c long value to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(long long ll, int indexAt); + + /** + * Inserts the string representing the specified @c float value + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] f A @c float value to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(float f, int indexAt); + + /** + * Inserts the string representing the specified @c double value + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] d A @c double value to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(double d, int indexAt); + + /** + * Inserts the string representing the specified @c null-terminated + * string at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] p An instance of %String to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + * @exception E_INVALID_ARG A @c null pointer is passed. + */ + result Insert(const wchar_t* p, int indexAt); + + /** + * Inserts the string representing the specified instance of %String + * at the specified position in the calling instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] str An instance of %String to insert + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Insert(const String& str, int indexAt); + + /** + * Searches the calling instance for the last occurrence of the specified character and returns its index. @n + * The search begins at the @c startIndex position and proceeds backward towards the beginning. + * + * @since 2.0 + * + * @return An error code + * @param[in] ch The Unicode character to locate + * @param[in] startIndex The starting position of search + * @param[out] indexOf The index of character + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified character is not found. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c startIndex is either greater than or equal to the length of the current instance or less than @c 0. + */ + result LastIndexOf(wchar_t ch, int startIndex, int& indexOf) const; + + /** + * Searches the calling instance for the last occurrence of the specified substring and returns its index. @n + * The search begins at the @c startIndex position and proceeds backward towards the beginning. + * + * @since 2.0 + * + * @return An error code + * @param[in] str An instance of %String to locate + * @param[in] startIndex The starting position of search + * @param[out] indexOf The index of the substring + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified character is not found. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c startIndex is either greater than or equal to the length of the current instance or less than @c 0. + * @remarks If the substring is empty, E_SUCCESS is returned and the value of @c indexOf is set to @c startIndex. + */ + result LastIndexOf(const String& str, int startIndex, int& indexOf) const; + + /** + * Removes the characters within the specified range. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The position where the removal begins + * @param[in] length The number of characters to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is out of range. @n + * - The specified @c startIndex is either greater than or equal to the length of the current instance or less than @c 0. @n + * - The specified @c count is either greater than the length of substring starting from @c startIndex or less than @c 0. + */ + result Remove(int startIndex, int length); + + /** + * Replaces all occurrences of the specified characters. + * + * @since 2.0 + * + * @param[in] original The character to replace + * @param[in] replace The character to replace all occurrences of @c original + */ + void Replace(wchar_t original, wchar_t replace); + + /** + * Replaces all occurrences of the specified string. + * + * @since 2.0 + * + * @return An error code + * @param[in] original An instance of %String to replace + * @param[in] replace An instance of %String to replace all occurrences of @c original + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c original is an empty string. + */ + result Replace(const String& original, const String& replace); + + /** + * Replaces all occurrences of the specified string within the substring + * of this instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] original An instance of %String to replace + * @param[in] replace An instance of %String to replace all occurrences of @c original + * @param[in] startIndex The starting position of the substring + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c original is an empty string. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c startIndex is either greater than or equal to the length of the current instance or less than @c 0. + */ + result Replace(const String& original, const String& replace, int startIndex); + + /** + * Reverses the sequence of characters in the calling instance. + * + * @since 2.0 + * + */ + void Reverse(void); + + /** + * Sets the capacity of this instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] newCapacity The new capacity + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c capacity is negative. + * @remarks If the new capacity is smaller than the current length, then + * the text contained in this instance is truncated. + */ + result SetCapacity(int newCapacity); + + /** + * Sets the character at the specified index with the given character. + * + * @since 2.0 + * + * @return An error code + * @param[in] ch A new character + * @param[in] indexAt The position of the character + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c indexAt is either greater than or equal to the length of the current instance or less than @c 0. + */ + result SetCharAt(wchar_t ch, int indexAt); + + /** + * Sets the length of this instance of %String. + * + * @since 2.0 + * + * @return An error code + * @param[in] newLength The new length + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c newLength is negative. + * @remarks If the new length is greater than the current length, the + * string is padded with spaces. On the other hand, + * if the new length is smaller than the current length, then + * the text contained in this instance is truncated. + */ + result SetLength(int newLength); + + /** + * Gets a substring starting from the given index. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting index of the substring + * @param[out] out The substring + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified index is out of range, or + * the specified @c startIndex is either greater than or equal to the length of the current instance or less than @c 0. + */ + result SubString(int startIndex, String& out) const; + + /** + * Gets a substring of the given length starting from the specified index. + * + * @since 2.0 + * + * @return An error code + * @param[in] startIndex The starting position of the substring + * @param[in] length The length of the substring + * @param[out] out The substring + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE Either of the following conditions has occurred: @n + * - The specified index is out of range. @n + * - The specified @c startIndex is either greater than or equal to the length of the current instance or less than @c 0. @n + * - The specified @c length is either greater than the length of substring starting from @c startIndex or less than @c 0. + */ + result SubString(int startIndex, int length, String& out) const; + + /** + * Checks whether this instance contains the specified text from the given index. + * + * @since 2.0 + * + * @return @c true if this instance starts with the specified text, @n + * else @c false + * @param[in] str The string to match + * @param[in] startIndex The start position of the string + */ + bool StartsWith(const String& str, int startIndex) const; + + /** + * Checks whether the given string is present at the end of the calling instance. + * + * @since 2.0 + * + * @return @c true if this instance ends with the specified text, @n + * else @c false + * @param[in] str An instance of %String to match + */ + bool EndsWith(const String& str) const; + + /** + * @if OSPDEPREC + * Gets the lowercase form of the string in the calling instance. @n + * Unicode characters other than the English alphabets are not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use the ToLowerCase(%String& out) method that supports Unicode characters other than the English alphabets. + * @since 2.0 + * + * @return An error code + * @param[out] out An instance of %String that contains the modified value of the calling instance + * @exception E_SUCCESS The method is successful. + * @endif + */ + result ToLower(String& out) const; + + /** + * Gets the lowercase form of the string in the calling instance. @n + * Unicode characters other than the English alphabets are also supported. + * + * @since 2.0 + * + * @return An error code + * @param[out] out An instance of %String that contains the modified value of the calling instance + * @exception E_SUCCESS The method is successful. + */ + result ToLowerCase(String& out) const; + + /** + * @if OSPDEPREC + * Gets the uppercase form of the string in the calling instance. @n + * Unicode characters other than the English alphabets are not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use the ToUpperCase(%String& out) method that supports Unicode characters other than the English alphabets. + * @since 2.0 + * + * @return An error code + * @param[out] out An instance of %String that contains the modified value of the calling instance + * @exception E_SUCCESS The method is successful. + * @endif + */ + result ToUpper(String& out) const; + + /** + * Gets the uppercase form of the string in the calling instance. @n + * Unicode characters other than the English alphabets are also supported. + * + * @since 2.0 + * + * @return An error code + * @param[out] out An instance of %String that contains the modified value of the calling instance + * @exception E_SUCCESS The method is successful. + */ + result ToUpperCase(String& out) const; + + /** + * @if OSPDEPREC + * Converts all the letters in this instance to lowercase. @n + * Unicode characters other than the English alphabets are not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use the ToLowerCase() method that supports Unicode characters other than the English alphabets. + * + * @since 2.0 + * @endif + */ + void ToLower(void); + + /** + * Converts all the letters in this instance to lowercase. @n + * Unicode characters other than the English alphabets are also supported. + * + * @since 2.0 + */ + void ToLowerCase(void); + + /** + * @if OSPDEPREC + * Converts all the letters in this instance to uppercase. @n + * Unicode characters other than the English alphabets are not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a new method has been introduced. + * Instead of using this method, use the ToUpperCase() method that supports Unicode characters other than the English alphabets. + * + * @since 2.0 + * @endif + */ + void ToUpper(void); + + /** + * Converts all the letters in this instance to uppercase. @n + * Unicode characters other than the English alphabets are also supported. + * + * @since 2.0 + */ + void ToUpperCase(void); + + /** + * Trims the leading and trailing whitespace characters. + * + * @since 2.0 + */ + void Trim(void); + + /** + * Gets the current capacity of this %String instance. + * + * @since 2.0 + * + * @return The capacity of this %String instance + */ + int GetCapacity(void) const; + + /** + * Gets the length of the text contained in this %String instance. + * + * @since 2.0 + * + * @return The length of this %String instance + */ + int GetLength(void) const; + + /** + * Gets a pointer to the instance's internal buffer. + * + * @since 2.0 + * + * @return A Unicode pointer to the calling instance's internal buffer + * @remarks GetPointer() does not guarantee that every call to this function returns same address. + */ + const wchar_t* GetPointer(void) const; + + /** + * Checks whether this instance contains the specified substring. + * + * @since 2.0 + * + * @return @c true if this instance contains the specified substring, @n + * else @c false + * @param[in] str The string to match + */ + bool Contains(const String& str) const; + + /** + * A constant holding the default capacity of %String. + * + * @since 2.0 + */ + static const unsigned long DEFAULT_CAPACITY = 16; + +private: + // + // Allocates an internal buffer with the specified capacity. + // @return An error code + // @param[in] capacity The initial capacity of this instance of %String + // + bool AllocateCapacity(int capacity); + + // + // Expands the size of the internal buffer that is greater than or equal + // to the specified capacity. + // @return @c true if the capacity is expanded, @n + // else @c false + // @param[in] capacity The new capacity of this instance of %String + // + bool ExpandCapacity(int minCapacity); + + // + // Initializes __pValue and __pRefCount + // + // @since 2.0 + // + result InitializeToDefault(int capacity); + + // + // Copies __pValue and subtract and initialize __pRefCount + // + // @since 2.0 + // + result CopyOnWrite(int capacity); + + // + // Swaps member-wisely + // + // @since 2.0 + // + void Swap(String& str); + + int __capacity; + int __length; + mutable int __hash; + mutable int* __pRefCount; + mutable wchar_t* __pValue; + + static const float GROWTH_FACTOR; + + class _StringImpl * __pStringImpl; + friend class _StringImpl; +}; // String + +}} // Tizen::Base +#endif // _FBASE_STRING_H_ diff --git a/inc/FBaseStringComparer.h b/inc/FBaseStringComparer.h new file mode 100644 index 0000000..c0a8f4d --- /dev/null +++ b/inc/FBaseStringComparer.h @@ -0,0 +1,129 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseStringComparer.h + * @brief This is the header file for the %StringComparer class. + * + * @see String and Tizen::Base::Collection::IComparer + * + * This header file contains the declarations of the %StringComparer class. + */ +#ifndef _FBASE_STRING_COMPARER_H_ +#define _FBASE_STRING_COMPARER_H_ + +// includes +#include +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class StringComparer + * @brief This class checks for equivalence between 2 instances of the String type. + * + * @since 2.0 + * + * The %StringComparer class checks for equivalence between 2 instances of the String type. + * + * For more information on the class features, see Collection Comparisons. + * + * The following example demonstrates how to use the %StringComparer class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::StringComparerSample(void) + * { + * String s1(L"ABC"); + * String s2(L"abc"); + * StringComparer strComparer; + * + * int cmp; + * strComparer.Compare(s1, s2, cmp); + * if (cmp < 0) + * { + * // ... + * } + * } + * @endcode + */ +class _OSP_EXPORT_ StringComparer + : public Object + , public virtual Tizen::Base::Collection::IComparer +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + StringComparer(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~StringComparer(void); + + /** + * Compares two given instances of type String. + * + * @since 2.0 + * + * @return An error code + * @param[in] obj1 An object of String to compare + * @param[in] obj2 An object of String to compare + * @param[out] cmp The result of comparison + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified object instances are not of the expected type. + * @remarks The value of @c cmp can be: + * + * @code + * < 0 if the value of @c obj1 is less than the value of @c obj2 + * == 0 if the value of @c obj1 is equal to the value of @c obj2 + * > 0 if the value of @c obj1 is greater than the value of @c obj2 + * @endcode + */ + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + StringComparer(const StringComparer& obj); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + StringComparer& operator =(const StringComparer& rhs); + + friend class _StringComparerImpl; + class _StringComparerImpl * __pStringComparerImpl; + +}; // StringComparer + +}} // Tizen::Base + +#endif // _FBASE_STRING_COMPARER_H_ diff --git a/inc/FBaseSys.h b/inc/FBaseSys.h new file mode 100755 index 0000000..61f97b3 --- /dev/null +++ b/inc/FBaseSys.h @@ -0,0 +1,25 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// This file assures the compatibility of the log macro with Tizen 2.0. + +#ifndef _FBASE_SYS_H_ +#define _FBASE_SYS_H_ + +#include + +#endif // _FBASE_SYS_H_ diff --git a/inc/FBaseSysLog.h b/inc/FBaseSysLog.h new file mode 100644 index 0000000..762783a --- /dev/null +++ b/inc/FBaseSysLog.h @@ -0,0 +1,685 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseSysLog.h + * @brief This is the header file for the %Log macros. + * + * This header file defines the %Log macros. + */ + +#ifndef _FBASE_SYS_LOG_H_ +#define _FBASE_SYS_LOG_H_ + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +#ifndef likely +#define likely(x) __builtin_expect(!!(x), 1) +#endif +#ifndef unlikely +#define unlikely(x) __builtin_expect(!!(x), 0) +#endif + +/** + * @mainpage Tizen Platform API Reference + * + * The Tizen platform API Reference provides descriptions of APIs for the platform developers. + */ + +/** + * @defgroup GroupMacros Debugging Macros + * + * This page describes Tizen debugging macros used by the Tizen modules. + * These debugging macros should use specific NID ( Namespace ID ) to distinguish each Tizen modules. + * + * @since 2.0 + */ + + +/** + * @addtogroup GroupMacros + * + * @{ + */ + +/** + * This macro allows display of informative log messages. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysLog macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * SysLog(NID, "Initialization successful."); + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define SysLog(NID, ...) SysLogInternal(NID, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) + +/** + * This macro allows display of exception log messages with a tag and sets the last result. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] r The last result to set + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysLogException macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * if (something_wrong) // The Try family macros can be used instead. + * { + * SysLogException(NID, E_INVALID_ARG, "An unexpected error has occurred."); + * + * return false; + * } + * //... + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define SysLogException(NID, r, ...) SysLogExceptionInternal(NID, r, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) + +/** + * This macro allows display of informative log messages with a tag. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] tag The user defined tag + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysLogTag macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * SysLogTag(NID, "MyTag", "Initialization successful."); + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define SysLogTag(NID, tag, ...) SysLogTagInternal(NID, tag, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) + +/** + * This macro allows display of exception log messages with a tag and sets the last result. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] tag The user defined tag + * @param[in] r The last result to set + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysLogTagException macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * SysLogExceptionTag(NID, "MyTag", E_INVALID_ARG, "Initialization successful."); + * + * return true; + * } + * @endcode + * @hideinitializer + */ +#define SysLogExceptionTag(NID, tag, r, ...) SysLogExceptionTagInternal(NID, tag, r, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) + + + +/** + * This macro allows display of informative log message with a tag, when the condition is @c false. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] condition The condition that is expected to be true + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysTryLog macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysTryLog(NID, condition, "An unexpected error has occurred."); + * + * //... + * } + * @endcode + * @hideinitializer + */ +#define SysTryLog(NID, condition, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysLog(NID, __VA_ARGS__); \ + } \ + } while (0); + +/** + * This macro allows display of informative log message, when the condition is @c false. + * Executes statements and goes to label. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] condition The condition that is expected to be true + * @param[in] expr Expressions that are evaluated before going to CATCH label + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysTryLogCatch macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysTryLogCatch(NID, condition, r=E_INVALID_ARG, "An unexpected error has occurred."); + * + * //... + * CATCH: + * return false; + * } + * @endcode + * @hideinitializer + */ +#define SysTryLogCatch(NID, condition, expr, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysLog(NID, __VA_ARGS__); \ + expr; \ + goto CATCH; \ + } \ + } while (0); + +/** + * This macro allows display of informative log message and returns returnValue, when the condition is @c false. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] condition The condition that is expected to be true + * @param[in] returnValue The value to return when the condition is @c false + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysTryLogReturn macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysTryLogReturn(NID, condition, false, "An unexpected error has occurred."); + * + * //... + * return true; + * } + * @endcode + * @hideinitializer + */ +#define SysTryLogReturn(NID, condition, returnValue, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysLog(NID, __VA_ARGS__); \ + return returnValue; \ + } \ + } while (0); + + +/** + * This macro allows display of exception log message with a tag and sets the last result, when the condition is @c false. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] condition The condition that is expected to be true + * @param[in] returnValue The value to return when the condition is @c false + * @param[in] r The last result to set + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysTryReturn macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysTryReturn(NID, condition, false, E_INVALID_ARG, "An unexpected error has occurred."); + * + * //... + * return true; + * } + * @endcode + * @hideinitializer + */ +#define SysTryReturn(NID, condition, returnValue, r, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysLogException(NID, r, __VA_ARGS__); \ + return returnValue; \ + } \ + } while (0); + +/** + * This macro allows display of exception log message with a tag and sets the last result, when the condition is @c false. + * This is a shorthand macro for SysTryReturn(NID, condition, r, r, "[" # r "] " ...). + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] condition The condition that is expected to be true + * @param[in] r The last result to set + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysTryReturnResult macro. + * + * @code + * #define E_UNKNOWN_ERROR 1 + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysTryReturnResult(NID, condition, E_UNKNOWN_ERROR, "An unexpected error has occurred."); + * + * //... + * return true; + * } + * @endcode + * @hideinitializer + */ +#define SysTryReturnResult(NID, condition, r, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysTryReturnResultInternal(NID, r, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__); \ + return r; \ + } \ + } while (0); + +/** + * This macro allows display of exception log message with a tag and sets the last result, when the condition is @c false. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] condition The condition that is expected to be true + * @param[in] r The last result to set + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysTryReturnVoidResult macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysTryReturnVoidResult(NID, condition, E_INVALID_ARG, "An unexpected error has occurred."); + * + * //... + * return true; + * } + * @endcode + * @hideinitializer + */ +#define SysTryReturnVoidResult(NID, condition, r, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysLogException(NID, r, __VA_ARGS__); \ + return; \ + } \ + } while (0); + +/** + * This macro allows display of exception log message with a tag, when the condition is @c false. + * Executes statements, sets the last result and goes to label. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] condition The condition that is expected to be true + * @param[in] expr Expressions that are evaluated before going to CATCH label + * @param[in] r The last result to set + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysTryCatch macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysTryCatch(NID, condition, r=E_INVALID_ARG, E_INVALID_ARG, "An unexpected error has occurred."); + * + * //... + * CATCH: + * return false; + * } + * @endcode + * @hideinitializer + */ +#define SysTryCatch(NID, condition, expr, r, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysLogException(NID, r, __VA_ARGS__); \ + expr; \ + goto CATCH; \ + } \ + } while (0); + +/** + * This macro allows display of exception log message with a tag, when the condition is @c false. + * Executes statements, sets the last result and goes to label. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] condition The condition that is expected to be true + * @param[in] expr Expressions that are evaluated before going to catchLabel label + * @param[in] catchLabel The label for goto operation + * @param[in] r The last result to set + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysTryCatchLabel macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysTryCatchLabel(NID, condition, r=E_INVALID_ARG, LABEL, E_INVALID_ARG, "An unexpected error has occurred."); + * + * //... + * LABEL: + * return false; + * } + * @endcode + * @hideinitializer + */ +#define SysTryCatchLabel(NID, condition, expr, catchLabel, r, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysLogException(NID, r, __VA_ARGS__); \ + expr; \ + goto catchLabel; \ + } \ + } while (0); + + +/** + * This macro allows display of exception log message and the program will expire, when the condition is @c false. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * + * The following example demonstrates how to use the SysAssert macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysAssert(condition); + * + * //... + * } + * @endcode + * @hideinitializer + */ +#define SysAssert(condition) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysAssertInternal(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ + } \ + } while (0); + +/** + * This macro allows display of exception log message with a tag and the program will expire, when the condition is @c false. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * @param[in] ... The message to display + * + * The following example demonstrates how to use the SysAssertf macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysAssertf(condition, ""); + * + * //... + * } + * @endcode + * @hideinitializer + */ +#define SysAssertf(condition, ...) \ + do \ + { \ + if (unlikely(!(condition))) { \ + SysAssertfInternal(# condition, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__); \ + } \ + } while (0); + + +/** + * This macro generates an error message during compile time, when the condition is @c false. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] condition The condition that is expected to be true + * + * The following example demonstrates how to use the SysStaticAssert macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysStaticAssert(condition); + * + * //... + * } + * @endcode + * @hideinitializer + */ +#define SysStaticAssert(condition) switch (0) { \ +case 0: \ +case condition: \ + ; \ +} + + +/** + * This macro allows display of exception log messages. + * This system log macro is for the platform modules. + * + * @since 2.0 + * + * @param[in] NID The Tizen namespace + * @param[in] r The last result to set + * + * The following example demonstrates how to use the SysPropagate macro. + * + * @code + * Bool + * MyEngine::Init(int value) + * { + * //... + * + * SysPropagate(NID, E_INVALID_ARG); + * + * //... + * } + * @endcode + * @hideinitializer + */ +#define SysPropagate(NID, r) SysPropagateInternal(__PRETTY_FUNCTION__, __LINE__, NID, r) + + +/** + * Defines the log ID. + */ +enum LogID +{ +//Tizen Namespace ID =============================================================== + NID_APP = 0, + + NID_BASE = 10, + NID_BASE_COL = 11, + NID_BASE_RT = 12, + NID_BASE_UTIL = 13, + + NID_CNT = 20, + + NID_CTXT = 30, + + NID_GRP = 40, + + NID_IO = 50, + + NID_LCL = 60, + + NID_LOC = 70, + NID_LOC_CTRL = 71, + NID_LOC_SVC = 72, + + NID_MEDIA = 80, + + NID_MSG = 90, + + NID_NET = 100, + NID_NET_BT = 101, + NID_NET_HTTP = 102, + NID_NET_NFC = 103, + NID_NET_SOCK = 104, + NID_NET_WIFI = 105, + + NID_SEC = 110, + NID_SEC_CERT = 111, + NID_SEC_CRYPTO = 112, + + NID_SCL = 120, + + NID_SYS = 130, + + NID_TEL = 140, + + NID_TEXT = 150, + + NID_UI = 160, + NID_UI_ANIM = 161, + NID_UI_CTRL = 162, + NID_UI_EFFECT = 163, + NID_UI_IME = 164, + NID_UI_SCENES = 165, + + NID_UIX = 170, + NID_UIX_SPEECH = 171, + + NID_WEB = 180, + NID_WEB_CTRL = 181, + NID_WEB_JSON = 182 +}; + +/** +* +@} */ + +_OSP_EXPORT_ void SysLogInternal(unsigned long id, const char* pFunction, int lineNumber, const char* pFormat, ...); +_OSP_EXPORT_ void SysLogExceptionInternal(unsigned long id, result r, const char* pFunction, int lineNumber, const char* pFormat, ...); + +_OSP_EXPORT_ void SysLogTagInternal(unsigned long id, const char* pTag, const char* pFunction, int lineNumber, const char* pFormat, ...); +_OSP_EXPORT_ void SysLogExceptionTagInternal(unsigned long id, const char* pTag, result r, const char* pFunction, int lineNumber, const char* pFormat, ...); + +_OSP_EXPORT_ void SysAssertInternal(const char* pFileName, int lineNumber, const char* pFunction); +_OSP_EXPORT_ void SysAssertfInternal(const char* expr, const char* pFunction, int lineNumber, const char* pFormat, ...); + +_OSP_EXPORT_ void SysPropagateInternal(const char* pFunction, int lineNumber, unsigned long nid, result r); + +_OSP_EXPORT_ void SysTryReturnResultInternal(unsigned long id, result r, const char* pFunction, int lineNumber, const char* pFormat, ...); + +#ifdef __cplusplus +} +#endif // __cplusplus + + +#endif // _FBASE_SYS_LOG_H_ diff --git a/inc/FBaseTimeSpan.h b/inc/FBaseTimeSpan.h new file mode 100644 index 0000000..841df25 --- /dev/null +++ b/inc/FBaseTimeSpan.h @@ -0,0 +1,432 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseTimeSpan.h + * @brief This is the header file for the %TimeSpan class. + * + * This header file contains the declarations of the %TimeSpan class. + */ +#ifndef _FBASE_TIME_SPAN_H_ +#define _FBASE_TIME_SPAN_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ +/** + * @class TimeSpan + * @brief This class represents a time interval. + * + * @since 2.0 + * + * The %TimeSpan class represents a time interval. An instance of %TimeSpan represents a period of time measured in ticks. A tick is the smallest + * unit of time used by the platform or system. In Tizen, it is a millisecond. + * + * For more information on the class features, see DateTime and TimeSpan. + * + * The following example demonstrates how to use the %TimeSpan class. + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::TimeSpanSample(void) + * { + * TimeSpan span1(1, 1, 1); // one hour + one minute + one second + * TimeSpan span2(1, 23, 70, 100); // 1 days + 23 hours + 70 minutes + 100 seconds + * + * if (span2 > span1) + * { + * TimeSpan span3 = (span2 - span1); + * if (TimeSpan::Compare(span1, span3) == 0) + * { + * // ... + * } + * } + * + * + * long long days, hours, minutes, seconds; + * + * days = span2.GetDays(); // 2 days + * hours = span2.GetHours(); // 0 hours + * minutes = span2.GetMinutes(); // 11 minutes + * seconds = span2.GetSeconds(); // 40 seconds + * + * } + * @endcode + */ +class _OSP_EXPORT_ TimeSpan + : public Object +{ +public: + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %TimeSpan to copy + */ + TimeSpan(const TimeSpan& value); + + + /** + * Initializes an instance of %TimeSpan with the specified parameters. + * + * @since 2.0 + * + * @param[in] hours The number of hours + * @param[in] minutes The number of minutes + * @param[in] seconds The number of seconds + */ + TimeSpan(int hours, int minutes, int seconds); + + + /** + * Initializes an instance of %TimeSpan with the specified parameters. + * + * @since 2.0 + * + * @param[in] days The number of days + * @param[in] hours The number of hours + * @param[in] minutes The number of minutes + * @param[in] seconds The number of seconds + */ + TimeSpan(int days, int hours, int minutes, int seconds); + + + /** + * Initializes an instance of %TimeSpan with the specified parameters. + * + * @since 2.0 + * + * @param[in] days The number of days + * @param[in] hours The number of hours + * @param[in] minutes The number of minutes + * @param[in] seconds The number of seconds + * @param[in] milliseconds The number of milliseconds + */ + TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds); + + + /** + * Initializes an instance of %TimeSpan with the specified number of ticks. + * + * @since 2.0 + * + * @param[in] ticks The number of ticks (in milliseconds) + */ + TimeSpan(long long ticks); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~TimeSpan(void); + + /** + * Adds the values of the two instances of %TimeSpan. + * + * @since 2.0 + * + * @return An instance of %TimeSpan + * @param[in] rhs An instance of %TimeSpan to add + */ + TimeSpan operator +(const TimeSpan& rhs) const; + + /** + * Subtracts the values of the two instances of %TimeSpan. + * + * @since 2.0 + * + * @return An instance of %TimeSpan + * @param[in] rhs An instance of %TimeSpan to subtract + */ + TimeSpan operator -(const TimeSpan& rhs) const; + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return A reference to the current instance of %TimeSpan + * @param[in] rhs An instance of %TimeSpan + */ + TimeSpan& operator =(const TimeSpan& rhs); + + /** + * Checks whether the value of this instance is equal to the value of the + * specified instance of %TimeSpan. + * + * @since 2.0 + * + * @return @c true if the two values are equal, @n + * else @c false + * @param[in] rhs An instance of %TimeSpan to compare + */ + bool operator ==(const TimeSpan& rhs) const; + + /** + * Checks whether the value of this instance is not equal to + * the value of the specified instance of %TimeSpan. + * + * @since 2.0 + * + * @return @c true if the two values are not equal, @n + * else @c false + * @param[in] rhs An instance of %TimeSpan to compare + */ + bool operator !=(const TimeSpan& rhs) const; + + /** + * Checks whether the value of the calling instance is less than that of + * the specified instance of %TimeSpan. + * + * @since 2.0 + * + * @return @c true if the value of the calling instance is less than that of the specified instance of %TimeSpan, @n + * else @c false + * @param[in] rhs An instance of %TimeSpan to compare + */ + bool operator <(const TimeSpan& rhs) const; + + /** + * Checks whether the value of the calling instance is greater than that of + * the specified instance of %TimeSpan. + * + * @since 2.0 + * + * @return @c true if the value of the calling instance is greater than that of the specified instance of %TimeSpan, @n + * else @c false + * @param[in] rhs An instance of %TimeSpan to compare + */ + bool operator >(const TimeSpan& rhs) const; + + /** + * Checks whether the value of the calling instance is less than or equal to + * the value of the specified instance of %TimeSpan. + * + * @since 2.0 + * + * @return @c true if the value of the calling instance is less than or equal to the value of the specified instance of %TimeSpan, @n + * else @c false + * @param[in] rhs An instance of %TimeSpan to compare + */ + bool operator <=(const TimeSpan& rhs) const; + + /** + * Checks whether the value of the calling instance is greater than or equal to + * the value of the specified instance of %TimeSpan. + * + * @since 2.0 + * + * @return @c true if the value of the calling instance is greater than or equal to the value of the specified instance of %TimeSpan, @n + * else @c false + * @param[in] rhs An instance of %TimeSpan to compare + */ + bool operator >=(const TimeSpan& rhs) const; + + /** + * Compares the two specified instances of %TimeSpan. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @param[in] t1 An instance of %TimeSpan to compare + * @param[in] t2 An instance of %TimeSpan to compare + * + * @code + * < 0 if the value of @c t1 is less than the value of @c t2 + * == 0 if the value of @c t1 is equal to the value of @c t2 + * > 0 if the value of @c t1 is greater than the value of @c t2 + * @endcode + */ + static int Compare(const TimeSpan& t1, const TimeSpan& t2); + + /** + * Compares the value of the calling instance to the value of the specified instance. + * + * @since 2.0 + * + * @return A 32-bit @c signed integer value + * @param[in] value An instance of %TimeSpan to compare + * + * @code + * < 0 if the value of the current instance is less than the value of @c obj + * == 0 if the value of the current instance is equal to the value of @c obj + * > 0 if the value of the current instance is greater than the value of @c obj + * @endcode + */ + int CompareTo(const TimeSpan& value) const; + + /** + * Checks whether the specified instance of Object is equal to the current instance of %TimeSpan. + * + * @since 2.0 + * + * @return @c true if the specified instance of Object is equal to the current instance of %TimeSpan, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @see Tizen::Base::Object::GetHashCode() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the absolute value of the calling instance. + * + * @since 2.0 + * + * @return An instance of %TimeSpan containing the absolute value + * @remarks This method is used to get absolute difference between two %TimeSpan instances. + * + * @code + * TimeSpan t1(1000); // 1000 milliseconds + * TimeSpan t2(2000); // 2000 milliseconds + * TimeSpan t3 = t1 - t2; // t3 == -1000 + * TimeSpan t4 = t3.Duration(); // t4 == 1000 + * @endcode + */ + TimeSpan Duration(void) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @see Tizen::Base::Object::Equals() + */ + virtual int GetHashCode(void) const; + + /** + * Gets the negative value of the calling instance. + * + * @since 2.0 + * + * @return An instance of %Timespan containing the negative value of the calling instance + */ + TimeSpan Negate(void) const; + + /** + * Gets the number of whole days represented by the calling instance. + * + * @since 2.0 + * + * @return The number of whole days represented by the calling instance + */ + long long GetDays(void) const; + + /** + * Gets the number of hours represented by the calling instance. + * + * @since 2.0 + * + * @return The number of hours represented by the calling instance + */ + long long GetHours(void) const; + + /** + * Gets the number of minutes represented by the calling instance. + * + * @since 2.0 + * + * @return The number of minutes represented by the calling instance + */ + long long GetMinutes(void) const; + + /** + * Gets the number of seconds represented by the calling instance. + * + * @since 2.0 + * + * @return The number of seconds represented by the calling instance + */ + long long GetSeconds(void) const; + + /** + * Gets the number of milliseconds represented by the calling instance. + * + * @since 2.0 + * + * @return The number of milliseconds represented by the calling instance + */ + long long GetMilliseconds(void) const; + + /** + * Gets the number of ticks represented by the calling instance. + * + * @since 2.0 + * + * @return The number of ticks represented by the calling instance + */ + long long GetTicks(void) const; + + /** + * A constant holding the number of ticks in a day. + * + * @since 2.0 + */ + static const long long NUM_OF_TICKS_IN_DAY = 86400000; + + /** + * A constant holding the number of ticks in an hour. + * + * @since 2.0 + */ + static const long long NUM_OF_TICKS_IN_HOUR = 3600000; + + /** + * A constant holding the number of ticks in a minute. + * + * @since 2.0 + */ + static const long long NUM_OF_TICKS_IN_MINUTE = 60000; + + /** + * A constant holding the number of ticks in a second. + * + * @since 2.0 + */ + static const long long NUM_OF_TICKS_IN_SECOND = 1000; + +private: + // + // Gets the numbers of ticks. + // @return The numbers of ticks + // @param[in] days The number of whole days + // @param[in] hours The number of hours + // @param[in] minutes The number of minutes + // @param[in] seconds The number of seconds + // @param[in] milliseconds The number of milliseconds + // + static long long CalcTicks(int days, int hours, int minutes, int seconds, int milliseconds); + + long long __ticks; + + friend class _TimeSpanImpl; + class _TimeSpanImpl * __pTimeSpanImpl; + +}; // TimeSpan + +}} // Tizen::Base + +#endif //_FBASE_TIME_SPAN_H_ diff --git a/inc/FBaseTypes.h b/inc/FBaseTypes.h new file mode 100644 index 0000000..8e165fb --- /dev/null +++ b/inc/FBaseTypes.h @@ -0,0 +1,89 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseTypes.h + * @brief This is the header file for the built-in data types. + * + * This header file contains the declarations of the commonly used built-in data types. + * + */ +#ifndef _FBASE_TYPES_H_ +#define _FBASE_TYPES_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ + +/** + * @enum SortOrder + * + * Defines the order of sorting. + * + * @since 2.0 + */ +enum SortOrder +{ + SORT_ORDER_ASCENDING = 0, /**< A constant for sorting the results in ascending order */ + SORT_ORDER_DESCENDING, /**< A constant for sorting the results in descending order */ + SORT_ORDER_NONE /**< A constant for indicating the results are not sorted */ +}; + + +/** + * @enum StringMatchCriteria + * + * Defines the matching criteria for strings. + * + * @since 2.0 + */ +enum StringMatchCriteria +{ + STRING_MATCH_CRITERIA_EXACT = 0, /**< A constant for matching the strings exactly */ + STRING_MATCH_CRITERIA_START_WITH, /**< A constant for matching the strings starting with the specified characters */ + STRING_MATCH_CRITERIA_CONTAIN, /**< A constant for matching the strings partially */ + STRING_MATCH_CRITERIA_WILDCARD /**< A constant for matching the strings supporting the wildcard characters */ +}; + + +/** + * @enum ComparisonOperator + * + * Defines a set of comparison operators whose semantics follow the SQL standards by default, + * but can be overridden by each API that uses this type, depending on the semantics and intention of the API. + * + * @since 2.0 + */ +enum ComparisonOperator +{ + COMPARISON_OP_EQUAL = 0, /**< A comparison operator that checks the value equality */ + COMPARISON_OP_NOT_EQUAL, /**< A comparison operator that checks the value inequality */ + COMPARISON_OP_GREATER_THAN, /**< A comparison operator that checks whether a value is greater than the other */ + COMPARISON_OP_LESS_THAN, /**< A comparison operator that checks whether a value is less than the other */ + COMPARISON_OP_GREATER_THAN_EQUAL_TO, /**< A comparison operator that checks whether a value is greater than or equal to the other */ + COMPARISON_OP_LESS_THAN_EQUAL_TO, /**< A comparison operator that checks whether a value is less than or equal to the other */ + COMPARISON_OP_LIKE, /**< A comparison operator that checks whether a value is like the other, where the exact matching condition may vary depending on the definition of each specific API */ + COMPARISON_OP_IS_NULL, /**< A comparison operator that returns @c true when a value does not exist for the given operand */ + COMPARISON_OP_IS_NOT_NULL /**< A comparison operator that returns @c true when a value exists for the given operand */ +}; + +}} // Tizen::Base + +#endif // _FBASE_TYPES_H_ diff --git a/inc/FBaseUtil.h b/inc/FBaseUtil.h new file mode 100644 index 0000000..1ac4782 --- /dev/null +++ b/inc/FBaseUtil.h @@ -0,0 +1,91 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtil.h + * @brief This is the header file for the %Utility namespace. + * + * This header file contains the declarations of the %Utility namespace. + * + */ +#ifndef _FBASE_UTIL_H_ +#define _FBASE_UTIL_H_ + +// Math +#include + +// StringTokenizer +#include + +// StringUtil +#include + +// Uri +#include + +// Inflator +#include + +// Deflator +#include + +// UrlEncoder +#include + +// Url Decoder +#include + +// FileZip +#include + +// FileUnzip +#include + +// ZipEntry +#include + +// Regular expression +#include + +// LinkInfo +#include + +/** + * @namespace Tizen::Base::Utility + * @brief This namespace contains classes for various utilities. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %Utility namespace contains interfaces and classes that + * define various utilities of an object, such as Math and StringTokenizer. + * It also contains methods to perform some common functions needed by the applications, such as file zipping and URL encoding and decoding. + * + * For more information on the %Base::Utility namespace features, see Utility. + * + * The following diagram illustrates the relationships between the classes belonging to the %Utility namespace. + * @image html base_utility_namespace_classdiagram.png + * + **/ + +namespace Tizen { namespace Base { namespace Utility +{ + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_H_ diff --git a/inc/FBaseUtilDeflator.h b/inc/FBaseUtilDeflator.h new file mode 100644 index 0000000..b967302 --- /dev/null +++ b/inc/FBaseUtilDeflator.h @@ -0,0 +1,162 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilDeflator.h + * @brief This is the header file for the %Deflator class. + * + * This header file contains the declarations of the %Deflator class. + */ +#ifndef _FBASE_UTIL_DEFLATOR_H_ +#define _FBASE_UTIL_DEFLATOR_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class Deflator + * @brief This class provides the deflate functionality using zlib. + * + * @since 2.0 + * + * The %Deflator class provides the deflate functionality using zlib. + * + * For more information on the class features, see Utility. + * + * The following example demonstrates how to use the %Deflator class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::DeflatorSample(ByteBuffer &buf) + * { + * ByteBuffer* pBuf1 = null; + * ByteBuffer* pBuf2 = null; + * ByteBuffer* pBuf3 = null; + * + * // Deflates the buf from the current position to limit of the buf + * pBuf1 = Deflator::DeflateN(buf); + * if (null == pBuf1) + * { + * // Error case handling... + * } + * // pBuf1: Deflated data of buf + * + * // Deflates the buf from the current position to (limit-2) of the buf + * pBuf2 = Deflator::DeflateN(buf, (buf.GetLimit()-2)); + * if (null == pBuf2) + * { + * // Error case handling... + * } + * + * // Deflates the buf from the current position to limit of the buf for BEST_COMPRESSION + * pBuf3 = Deflator::DeflateN(buf, BEST_COMPRESSION); + * if (null == pBuf3) + * { + * // Error case handling... + * } + * + * + * delete pBuf1; + * delete pBuf2; + * delete pBuf3; + * } + * + * @endcode + */ +class _OSP_EXPORT_ Deflator +{ +public: + /** + * Deflates the number of bytes from the source byte buffer to the output byte buffer. + * + * @since 2.0 + * + * @return A pointer to the ByteBuffer instance with the deflated equivalent of the source buffer @n + * The buffer's limit is the length of the deflated data, @n + * else @c null if an exception occurs. + * @param[in] src The buffer to deflate + * @param[in] byteCount The number of bytes to deflate from the source buffer + * @param[in] level Set to @c BEST_SPEED or @c BEST_COMPRESSION @n + * By default, it is set to @c DEFAULT_COMPRESSION. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Utility::Inflator + */ + static ByteBuffer* DeflateN(const ByteBuffer& src, int byteCount, CompressionLevel level = DEFAULT_COMPRESSION); + + /** + * Deflates data from the source byte buffer to the output byte buffer. + * + * @since 2.0 + * + * @return A pointer to the ByteBuffer instance with the deflated equivalent of the source buffer @n + * The buffer's limit is the length of the deflated data, @n + * else @c null if an exception occurs. + * @param[in] src The buffer to deflate + * @param[in] level Set to @c BEST_SPEED or @c BEST_COMPRESSION @n + * By default, it is set to @c DEFAULT_COMPRESSION. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Utility::Inflator + */ + static ByteBuffer* DeflateN(const ByteBuffer& src, CompressionLevel level = DEFAULT_COMPRESSION); + +private: + static ByteBuffer* __DeflateN(const ByteBuffer& src, int byteCount, CompressionLevel level); + + /** + * This default constructor is intentionally declared as private because this class cannot be constructed. + */ + Deflator(void); + + /** + * This destructor is intentionally declared as private because this class cannot be constructed. + */ + ~Deflator(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %Deflator + */ + Deflator(const Deflator& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %Deflator + */ + Deflator& operator =(const Deflator& rhs); + +}; // Deflator + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_DEFLATOR_H_ diff --git a/inc/FBaseUtilFileUnzipper.h b/inc/FBaseUtilFileUnzipper.h new file mode 100644 index 0000000..c71b239 --- /dev/null +++ b/inc/FBaseUtilFileUnzipper.h @@ -0,0 +1,287 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilFileUnzipper.h + * @brief This is the header file for %FileUnzipper class. + * + * This header file contains the declarations of the %FileUnzipper class. + */ + +#ifndef _FBASE_UTIL_FILE_UNZIPPER_H_ +#define _FBASE_UTIL_FILE_UNZIPPER_H_ + + +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +/** + * @class FileUnzipper + * @brief This class provides methods that decompress data from a zip-archive using zlib. + * + * @since 2.0 + * + * The %FileUnzipper class provides an unzip operation for a simple and efficient file-based access to a zip-archive. + * It is possible to extract a zipped file completely or partially and access the entry of a zip-archive. + * + * For more information on the class features, see Utility. + * + * The following example demonstrates how to use the %FileUnzipper class. + * @code + * #include + * + * using namespace Tizen::App; + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::FileUnzipperSample(void) + * { + * int count = 0; + * + * FileUnzipper unzip; + * String dataPath = App::GetInstance()->GetAppDataPath(); + * unzip.Construct(dataPath + L"sample.zip"); + * + * // Unzips the zip-archive fully + * unzip.UnzipTo(dataPath); + * + * // Unzips the file from the zip-archive + * unzip.UnzipTo(dataPath + L"Sample/", L"data1.txt"); + * + * // Gets the number of entries + * count = unzip.GetEntryCount(); + * + * } + * @endcode + */ + +class _OSP_EXPORT_ FileUnzipper + : public Tizen::Base::Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. @n + * For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + FileUnzipper(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~FileUnzipper(void); + + /** + * Initializes this instance of %FileUnzipper with the specified filepath. @n + * This method opens a zip file in the read mode. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param [in] filePath The path of the file to open or create + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path contains prohibited character(s). @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS The specified file path is inaccessible as per the Tizen platform policy. + * @exception E_FILE_NOT_FOUND The specified file cannot be found or accessed. + * @exception E_IO An unexpected device failure has occurred. + * @remarks The paths for @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"data" and @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"trusted" are not supported. + * @see Tizen::Io::File + */ + result Construct(const String& filePath); + + /** + * Unzips a zip file at the specified path or destination. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param [in] dirPath A directory path to unzip + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path contains prohibited character(s). @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS The specified path is not permitted, or + * access is denied due to insufficient permission. + * @exception E_IO An unexpected device failure has occurred. + * @remarks The paths for @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"data" and @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"trusted" are not supported. + * @remarks This operation consumes a lot of time if the zip-archive contains large number of files or + * directories. + * In such cases, it is recommended to call this method in a separate thread. + * @see Tizen::Io::File + */ + result UnzipTo(const String& dirPath) const; + + /** + * Unzips a zip entry from a zip-archive to the specified path. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param [in] dirPath A directory path to unzip + * @param [in] zipEntryName A zip entry name that could be a file or directory name + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path contains prohibited character(s). @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS The specified path is not permitted, or + * access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The entry of the specified file or path cannot be found in the archive. + * @exception E_IO An unexpected device failure has occurred. + * @remarks The paths for @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"data" and @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"trusted" are not supported. + * @remarks If the value of @c zipEntryName is a directory name present in the archive, this method + * creates an empty directory. @n + * For example, UnzipTo(Tizen::App::App::GetInstance()->GetAppDataPath() + L"Test/", L"/someDir/") will create @b '[AppDataPath]/Test/someDir' + * directory only, and the files or subdirectories under @b 'someDir' will not be extracted. + * @see Tizen::Io::File + */ + result UnzipTo(const String& dirPath, const String& zipEntryName) const; + + /** + * Gets the number of entries present in a zip-archive. + * + * @since 2.0 + * + * @return The number of entries present in a zip-archive, @n + * else @c -1 in case of an error + * @exception E_SUCCESS The method is successful. + * @exception E_IO An unexpected device failure has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + int GetEntryCount(void) const; + + /** + * Gets the number of files present in a zip-archive. + * + * @since 2.0 + * + * @return The number of files present in a zip-archive, @n + * else @c -1 in case of an error + * @exception E_SUCCESS The method is successful. + * @exception E_IO An unexpected device failure has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + int GetFileCount(void) const; + + /** + * Gets the number of directories present in a zip-archive. + * + * @since 2.0 + * + * @return The number of directories present in a zip-archive, @n + * else @c -1 in case of an error + * @exception E_SUCCESS The method is successful. + * @exception E_IO An unexpected device failure has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + int GetDirectoryCount(void) const; + + /** + * Gets a zip entry associated with the file or directory name passed as parameter. + * + * @since 2.0 + * + * @return An error code + * @param [in] zipEntryName A zip entry name that could be a file or directory name + * @param [out] entry A reference to the ZipEntry + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path contains prohibited character(s). @n + * - The specified path is invalid. + * @exception E_FILE_NOT_FOUND The entry of the specified file or path cannot be found in the archive. + * @exception E_IO An unexpected device failure has occurred. + * @remarks If the value of @c zipEntryName is a directory name, it must have a suffix '/'. + * For example, @b Tizen::App::App::GetInstance()->GetAppDataPath() + L"Test/" or @b Tizen::App::App::GetInstance()->GetAppDataPath() + L"Test/DATA/". + */ + result GetEntry(const String& zipEntryName, ZipEntry& entry) const; + + /** + * Gets a zip entry associated with the index from the root directory. + * + * @since 2.0 + * + * @return An error code + * @param [in] index An index of the zip entry to access @n + * The index starts from @c 0. + * @param [out] entry A reference to the ZipEntry + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified index is out of range, or an invalid index is passed. + * @exception E_IO An unexpected device failure has occurred. + */ + result GetEntry(int index, ZipEntry& entry) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param [in] fileUnzipper The instance of the %FileUnzipper class to copy from + * @remarks This constructor is hidden. + */ + FileUnzipper(const FileUnzipper& fileUnzipper); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param [in] fileUnzipper An instance of %FileUnzipper + * @remarks This operator is hidden. + */ + FileUnzipper& operator =(const FileUnzipper& fileUnzipper); + + + friend class _FileUnzipperImpl; + class _FileUnzipperImpl* __pFileUnzipperImpl; + +}; // FileUnzipper + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_FILE_UNZIPPER_H_ diff --git a/inc/FBaseUtilFileZipper.h b/inc/FBaseUtilFileZipper.h new file mode 100644 index 0000000..75ee81c --- /dev/null +++ b/inc/FBaseUtilFileZipper.h @@ -0,0 +1,201 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilFileZipper.h + * @brief This is the header file for the %FileZipper class. + * + * This header file contains the declarations of the %FileZipper class. + */ + +#ifndef _FBASE_UTIL_FILE_ZIPPER_H_ +#define _FBASE_UTIL_FILE_ZIPPER_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class FileZipper + * @brief This class provides methods that compress data to a zip-archive using zlib. + * + * @since 2.0 + * + * The %FileZipper class provides a zip operation for a simple and efficient file-based access to a zip-archive. + * It is possible to create a zip file, and add the file to an already existing zip-archive. + * + * For more information on the class features, see Utility. + * + * The following example demonstrates how to use the %FileZipper class. + * + * @code + * #include + * + * using namespace Tizen::App; + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::FileZipperSample(void) + * { + * FileZipper zip; + * String dataPath = App::GetInstance()->GetAppDataPath(); + * zip.Construct(dataPath + L"sample.zip"); + * + * // Adds files to the zip file-archive + * zip.AddToZip(dataPath + L"data1.txt"); + * zip.AddToZip(dataPath + L"dataDir/data2.txt"); + * } + * @endcode + */ +class _OSP_EXPORT_ FileZipper + : public Tizen::Base::Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. @n + * For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + FileZipper(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~FileZipper(void); + + /** + * Initializes this instance of %FileZipper with the specified filepath. @n + * This method opens an existing zip file in append mode. If the file does not exist, it creates and opens the file in + * append mode. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param [in] filePath The path of the zip file to open or create + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path contains prohibited character(s). @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS The specified path is not permitted, or + * access is denied due to insufficient permission. + * @exception E_IO An unexpected device failure has occurred. + * @remarks The paths for @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"data" and @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"trusted" are not supported. + * @see Tizen::Io::File + */ + result Construct(const String& filePath); + + /** + * Adds a new file to an already opened zip file. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param [in] filePath The path of the file to add to the zip file + * @param [in] excludePath Set to @c true to exclude the path and to store only the file name, @n + * else @c false to insert the entire path name in the zip-archive + * @param [in] level Set to @c BEST_SPEED or @c BEST_COMPRESSION @n + * By default, it is set to @c DEFAULT_COMPRESSION. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path contains prohibited character(s). @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS The specified path is not permitted, or + * access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The specified file cannot be found. + * @exception E_FILE_ALREADY_EXIST The specified file already exists in the zip-archive, but the + * flag for overwriting the file is not set. + * @exception E_IO An unexpected device failure has occurred. + * @remarks The paths for @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"data" and @b Tizen::App::AppManager::GetAppSharedPath(appId) + L"trusted" are not supported. + * @remarks If the value of @c excludePath is set to @c false, full path name is inserted to the zip- + * archive. Therefore, developers should handle the path name carefully. @n + * For example, if you add @b '/Test/data.txt' file to the zip-archive, and if the + * @c excludePath parameter is set to @c false, while unzipping the file in @b '/Test' + * directory, then the file is extracted in @b '/Test/Test/data.txt'. + * @see Tizen::Io::File + */ + result AddToZip(const String& filePath, bool excludePath = true, CompressionLevel level = DEFAULT_COMPRESSION); + + /** + * Gets the value of the overwritten flag. @n + * If @c true, it overwrites the existing file. + * + * @since 2.0 + * + * @return The value of the overwrite flag for the zip file + */ + bool GetOverwriteFlag(void) const; + + /** + * Sets the value of the overwritten flag. @n + * If @c true, the existing file gets overwritten during file addition. + * The default value of this flag is @c false. + * + * @since 2.0 + * + * @param [in] flag The flag value to set + */ + void SetOverwriteFlag(bool flag); + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param [in] fileZipper The instance of the FileZip class to copy from + * @remarks This constructor is hidden. + */ + FileZipper(const FileZipper& fileZipper); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param [in] fileZipper An instance of %FileZipper + * @remarks This operator is hidden. + */ + FileZipper& operator =(const FileZipper& fileZipper); + + + friend class _FileZipperImpl; + class _FileZipperImpl* __pFileZipperImpl; + +}; // FileZipper + +}}} // Tizen::Base::FileZipper + +#endif // _FBASE_UTIL_FILE_ZIPPER_H_ diff --git a/inc/FBaseUtilInflator.h b/inc/FBaseUtilInflator.h new file mode 100644 index 0000000..0b85624 --- /dev/null +++ b/inc/FBaseUtilInflator.h @@ -0,0 +1,150 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilInflator.h + * @brief This is the header file for the %Inflator class. + * + * This header file contains the declarations of the %Inflator class. + */ +#ifndef _FBASE_UTIL_INFLATOR_H_ +#define _FBASE_UTIL_INFLATOR_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class Inflator + * @brief This class provides the inflate functionality using zlib. + * + * @since 2.0 + * + * The %Inflator class provides the inflate functionality using zlib. + * + * For more information on the class features, see Utility. + * + * The following example demonstrates how to use the %Inflator class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::InflatorSample(ByteBuffer &buf) + * { + * ByteBuffer* pBuf1 = null; + * ByteBuffer* pBuf2 = null; + * + * // Inflates the buf from the current position to limit of the buf + * pBuf1 = Inflator::InflateN(buf); + * if (null == pBuf1) + * { + * // Error case handling... + * } + * // pBuf1 : Inflated Data of buf + * + * + * // Inflates the buf from the current position to (limit-2) of the buf + * pBuf2 = Inflator::InflateN(buf, (buf.GetLimit()-2)); + * if (null == pBuf2) + * { + * // Error case handling... + * } + * + * + * delete pBuf1; + * delete pBuf2; + * } + * + * @endcode + */ +class _OSP_EXPORT_ Inflator +{ +public: + /** + * Inflates the number of bytes from the source byte buffer to the output byte buffer. + * + * @since 2.0 + * + * @return A pointer to the ByteBuffer instance with the inflated equivalent of the source buffer @n + * The buffer's limit is the length of the inflated data, @n + * else @c null if an exception occurs. + * @param[in] src The buffer to inflate + * @param[in] byteCount The number of bytes to inflate from the source buffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Utility::Deflator + */ + static ByteBuffer* InflateN(const ByteBuffer& src, int byteCount); + + /** + * Inflates data from the source byte buffer to the output byte buffer. + * + * @since 2.0 + * + * @return A pointer to the ByteBuffer instance with the inflated equivalent of the source buffer @n + * The buffer's limit is the length of the inflated data, @n + * else @c null if an exception occurs. + * @param[in] src The buffer to inflate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::Utility::Deflator + */ + static ByteBuffer* InflateN(const ByteBuffer& src); + +private: + static ByteBuffer* __InflateN(const ByteBuffer& src, int byteCount); + + /** + * This default constructor is intentionally declared as private because this class cannot be constructed. + */ + Inflator(void); + + /** + * This destructor is intentionally declared as private because this class cannot be constructed. + */ + ~Inflator(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %Inflator + */ + Inflator(const Inflator& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %Inflator + */ + Inflator& operator =(const Inflator& rhs); + +}; // Inflator + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_INFLATOR_H_ diff --git a/inc/FBaseUtilLinkInfo.h b/inc/FBaseUtilLinkInfo.h new file mode 100644 index 0000000..5810aae --- /dev/null +++ b/inc/FBaseUtilLinkInfo.h @@ -0,0 +1,183 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilLinkInfo.h + * @brief This is the header file for the %LinkInfo class. + * + * This header file contains the declarations of the %LinkInfo class. + */ +#ifndef _FBASE_UTIL_LINK_INFO_H_ +#define _FBASE_UTIL_LINK_INFO_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +/** +* @class LinkInfo +* @brief This class provides methods for accessing the link, its type, and a string that represents the link. +* +* @since 2.0 +* +* The %LinkInfo class provides information regarding a link. It contains methods +* for accessing the link, its type, and a string that represents the link. +*/ +class _OSP_EXPORT_ LinkInfo + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks The link and text are set to empty strings and the link type is set to @c LINK_TYPE_NONE. + */ + LinkInfo(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~LinkInfo(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] value An instance of %LinkInfo + */ + LinkInfo(const LinkInfo& value); + + /** + * Initializes an instance of %LinkInfo with the specified parameters. + * + * @since 2.0 + * + * @param[in] linkType The link type + * @param[in] link The link + * @remarks The link's @c text is set to the same string as @c link. + * @see Tizen::Base::Utility::LinkType + */ + LinkInfo(LinkType linkType, const Tizen::Base::String& link); + + /** + * Initializes an instance of %LinkInfo with the specified parameters. + * + * @since 2.0 + * + * @param[in] linkType The link type + * @param[in] link The link + * @param[in] text A string that represents the link + * @see Tizen::Base::Utility::LinkType + */ + LinkInfo(LinkType linkType, const Tizen::Base::String& link, const Tizen::Base::String& text); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return A reference to the calling instance + * @param[in] rhs An instance of %LinkInfo + */ + LinkInfo& operator =(const LinkInfo& rhs); + + /** + * Gets the link. + * + * @since 2.0 + * + * @return The string that contains the link + * @see SetLink() + */ + Tizen::Base::String GetLink(void) const; + + /** + * Sets the link. + * + * @since 2.0 + * + * @param[in] link The string that contains the link + * @see GetLink() + */ + void SetLink(const Tizen::Base::String& link); + + /** + * Gets the type of the link. + * + * @since 2.0 + * + * @return The link type + * @see SetLinkType() + * @see Tizen::Base::Utility::LinkType + */ + LinkType GetLinkType(void) const; + + /** + * Sets the type of the link. + * + * @since 2.0 + * + * @param[in] linkType The link type + * @see GetLinkType() + * @see Tizen::Base::Utility::LinkType + */ + void SetLinkType(LinkType linkType); + + /** + * Gets the string that represents the link. + * + * @since 2.0 + * + * @return The string that represents the link + * @see SetText() + */ + Tizen::Base::String GetText(void) const; + + /** + * Sets the string that represents the link. + * + * @since 2.0 + * + * @return An error code + * @param[in] text The string that represents the link + * @see GetText() + */ + void SetText(const Tizen::Base::String& text); + + +private: + LinkType __linkType; + Tizen::Base::String __link; + Tizen::Base::String __text; + + friend class _LinkInfoImpl; + class _LinkInfoImpl* __pLinkInfoImpl; + +}; // LinkInfo + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_LINK_INFO_H_ diff --git a/inc/FBaseUtilMath.h b/inc/FBaseUtilMath.h new file mode 100644 index 0000000..37fa714 --- /dev/null +++ b/inc/FBaseUtilMath.h @@ -0,0 +1,402 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilMath.h + * @brief This is the header file for the %Math class. + * + * This header file contains the declarations of the %Math class. + */ +#ifndef _FBASE_UTIL_MATH_H_ +#define _FBASE_UTIL_MATH_H_ + +#include + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class Math + * @brief This class is the wrapper class for %Math Library. + * + * @since 2.0 + * + * The %Math class provides various mathematical methods. + * + * For more information on the class features, see Utility. + * + * The following example demonstrates how to use the %Math class. + * + * @code + * #include + * + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::MathSample(void) + * { + * double radius = 5.0; + * + * double area = Math::GetPi() * Math::Pow(radius, 2.0L); + * } + * @endcode + */ + +class _OSP_EXPORT_ Math +{ +public: + /** + * Gets the absolute value of the specified integer. + * + * @since 2.0 + * + * @return The absolute value of the specified integer + * @param[in] x An integer value + */ + static int Abs(int x); + + /** + * Gets the arc sine of the specified @c double integer. @n + * Returns a value between @c -PI/2 and @c PI/2. + * + * @since 2.0 + * + * @return The arc sine of the input, @n + * else Not-a-Number if @c x is out of range + * @param[in] x A radian angle @n + * It must be within the range @c -1 to @c 1 (inclusive). + * @see Acos() + * @see Atan() + */ + static double Asin(double x); + + /** + * Gets the arc cosine of the specified double integer. @n + * Returns a value between @c 0 and @c PI. + * + * @since 2.0 + * + * @return The arc cosine of the input, @n + * else Not-a-Number if @c x is out of range + * @param[in] x A radian angle @n + * It must be within the range @c -1 to @c 1 (inclusive). + * @see Asin() + * @see Atan() + */ + static double Acos(double x); + + /** + * Gets the arc tangent of the specified @c double integer. @n + * Returns a value between @c -PI/2 and @c PI/2. + * + * @since 2.0 + * + * @return The arc tangent of the input + * @param[in] x A radian angle + * @see Asin() + * @see Acos() + */ + static double Atan(double x); + + /** + * Gets the smallest integer that is greater than or equal to the specified @c double integer. @n + * For example, if @c x is @c 3.9, Ceiling(double) returns @c 4.0. @n + * The returned value is an integer but the type is @c double. + * + * @since 2.0 + * + * @return The smallest integer that is greater than or equal to the input + * @param[in] x A floating point value + */ + static double Ceiling(double x); + + /** + * Gets the cosine of the specified @c double integer. @n + * Returns a value between @c -1 and @c 1. + * + * @since 2.0 + * + * @return The cosine of the input + * @param[in] x A radian angle + * @see Sin() + * @see Tan() + */ + static double Cos(double x); + + /** + * Gets the hyperbolic cosine of the specified @c double integer. + * + * @since 2.0 + * + * @return The hyperbolic cosine of the input + * @param[in] x A radian angle + */ + static double Cosh(double x); + + /** + * Gets the exponential value of the specified @c double integer. + * + * @since 2.0 + * + * @return The exponential value of the input + * @param[in] x A floating point value + */ + static double Exp(double x); + + /** + * Gets the largest integer that is less than or equal to the input. @n + * For example, if @c x is @c 3.3 then Floor(double) returns @c 3.0. @n + * The returned value is an integer but the type is @c double. + * + * @since 2.0 + * + * @return The largest @c double integer that is less than or equal to the input + * @param[in] x A floating point value + */ + static double Floor(double x); + + /** + * Gets the natural logarithm of the specified number. + * + * @since 2.0 + * + * @return The natural logarithm of the input + * @param[in] x A floating point value + */ + static double Log(double x); + + /** + * Gets the logarithm to the base 10 of the specified number. + * + * @since 2.0 + * + * @return The logarithm to the base 10 of the input + * @param[in] x A floating point value + */ + static double Log10(double x); + + /** + * Gets the greater of the two specified integer values. @n + * If both inputs have the same value, this method returns the same value. + * + * @since 2.0 + * + * @return The greater of the two integer values + * @param[in] x An integer value + * @param[in] y An integer value + * @see Min() + */ + static int Max(int x, int y); + + /** + * Gets the greater of the two floating point values. @n + * If both inputs have the same value, this method returns the same value. @n + * If either value is not a valid number, then this method returns Not-a-Number. + * + * @since 2.0 + * + * @return The greater of the two floating point values + * @param[in] x A floating point value + * @param[in] y A floating point value + * @see Min() + */ + static double Max(double x, double y); + + /** + * Gets the smaller of the two integer values. @n + * If both inputs have the same value, this method returns the same value. + * + * @since 2.0 + * + * @return The smaller of the two integer values + * @param[in] x An integer value + * @param[in] y An integer value + * @see Max() + */ + static int Min(int x, int y); + + /** + * Gets the smaller of the two @c double values. @n + * If both inputs have the same value, this method returns the same value. @n + * If either value is not a valid number, this method returns Not-a-Number. + * + * @since 2.0 + * + * @return The smaller of the two @c double values + * @param[in] x A floating point value + * @param[in] y A floating point value + * @see Max() + */ + static double Min(double x, double y); + + /** + * Gets the value of @c x raised to the power of @c y. + * + * @since 2.0 + * + * @return @c x raised to the power of @c y, @n + * else Not-a-Number if @c x and @c y do not satisfy the conditions described below + * @param[in] x A floating point value + * @param[in] y A floating point value + * @remarks @li @c x cannot be negative if @c y is a fractional value. + * @li @c x cannot be @c 0 if @c y is less than or equal to @c 0. + */ + static double Pow(double x, double y); + + /** + * Gets the nearest integer to the specified number. + * + * @since 2.0 + * + * @return The closest integer to the specified input + * @param[in] x A floating point value + */ + static double Round(double x); + + /** + * Gets the sine of the specified @c double integer. @n + * Returns a value between @c -1 and @c 1. + * + * @since 2.0 + * + * @return The sine of the input + * @param[in] x A radian angle + * @see Cos() + * @see Tan() + */ + static double Sin(double x); + + /** + * Gets the hyperbolic sine of the specified @c double integer. + * + * @since 2.0 + * + * @return The hyperbolic sine of the input + * @param[in] x A radian angle + */ + static double Sinh(double x); + + /** + * Gets the square root of the specified number. + * + * @since 2.0 + * + * @return The square root of the input, @n + * else Not-a-Number if @c x is a negative number + * @param[in] x A non-negative floating point value + */ + static double Sqrt(double x); + + /** + * Gets the tangent of the specified @c double integer. + * + * @since 2.0 + * + * @return The tangent of the input + * @param[in] x A radian angle + * @see Sin() + * @see Cos() + */ + static double Tan(double x); + + /** + * Gets the hyperbolic tangent of the specified @c double integer. + * + * @since 2.0 + * + * @return The hyperbolic tangent of the input + * @param[in] x A radian angle + */ + static double Tanh(double x); + + + /** + * Initializes a random number generator. + * + * @since 2.0 + * + * @param[in] seed An integer value to use as seed by the pseudo-random number generator algorithm + * @see Rand() + */ + static void Srand(unsigned int seed); + + + /** + * Gets a random integral number in the range @c 0 to @c RAND_VALUE_MAX. + * + * @since 2.0 + * + * @return An integer value between @c 0 and @c RAND_VALUE_MAX + * @remarks This method uses a seed to generate the pseudo-random numbers, that must be initialized to some distinctive value using Srand(). + * @see Srand() + */ + static int Rand(void); + + /** + * Gets the constant value of E (the base of natural logarithms). + * + * @since 2.0 + * + * @return The constant value of E + */ + static const double GetE(void); + + /** + * Gets the constant value of PI. + * + * @since 2.0 + * + * @return The constant value of PI + */ + static const double GetPi(void); + + /** + * The maximum value that can be returned by the Rand() method. + * + * @since 2.0 + */ + static const int RAND_VALUE_MAX = 32767; // 0x7fff + + +private: + /** + * This default constructor is intentionally declared as private because this class cannot be constructed. + */ + Math(void); + + /** + * This destructor is intentionally declared as private because this class cannot be constructed. + */ + virtual ~Math(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs The instance of the Math + */ + Math(const Math& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %Math + */ + Math& operator =(const Math& rhs); +}; // Math + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_MATH_H_ diff --git a/inc/FBaseUtilRegularExpression.h b/inc/FBaseUtilRegularExpression.h new file mode 100644 index 0000000..7bd3c02 --- /dev/null +++ b/inc/FBaseUtilRegularExpression.h @@ -0,0 +1,445 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilRegularExpression.h + * @brief This is the header file for the %RegularExpression class. + * + * This header file contains the declarations of the %RegularExpression class. + */ +#ifndef _FBASE_UTIL_REGULAR_EXPRESSION_H_ +#define _FBASE_UTIL_REGULAR_EXPRESSION_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +/** + * @enum RegularExpressionOptions + * + * Defines the options available for a regular expression. + * + * @since 2.0 + */ +enum RegularExpressionOptions +{ + REGEX_CASELESS = 0x00000001, /**< The case insensitive match option */ + REGEX_MULTI_LINE = 0x00000002, /**< The multiple lines match option @n + Without this option, (^) matches only at the start of the string, while ($) matches only at + the end of the string, or before a terminating newline. */ + REGEX_DOTALL = 0x00000004, /**< The dot matches newlines option @n + Without this option, a dot does not match when the current position is at a newline. */ + REGEX_EXTENDED = 0x00000008, /**< The ignored whitespaces in a pattern */ + REGEX_DOLLAR_ENDONLY = 0x00000020, /**< The option to match the dollar symbol ($) only at the end @n + Without this option, a dollar symbol also matches immediately before a newline. */ + REGEX_UNGREEDY = 0x00000200, /**< The option to reverse the (*) and (*?) symbols @n + If this option is set, the quantifiers are not greedy by default, however they are, if followed by a question mark. */ + REGEX_UNICODE = 0x01000000, /**< The option to support the unicode characters @n + Without this option, only the ASCII characters are recognized. */ +}; + +/** + * @class RegularExpression + * @brief This class provides the functionality for a regular expression. + * + * @since 2.0 + * + * The %RegularExpression class provides operations of a regular expression based on PCRE and the syntax based on + * the Perl regular expression. + * The various supported operations are Match(), Replace(), and Consume(). + * + * For more information on the class features, see Regular Expression. + * + * The following example demonstrates how to use the %RegularExpression class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Collection; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass:RegularExpressionSample(void) + * { + * bool ret = false; + * + * String pattern(L"the quick brown fox"); + * String text(L"What do you know about the quick brown fox?"); + * String out; + * + * RegularExpression regex; + * regex.Construct(pattern, REGEX_CASELESS); + * + * ret = regex.Match(text, false); // This returns true value + * } + * + * @endcode + */ +class _OSP_EXPORT_ RegularExpression + : public Tizen::Base::Object +{ +public: + /** + * The object is not fully constructed after this constructor is called. @n + * For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + RegularExpression(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~RegularExpression(void); + + /** + * Initializes this instance of %RegularExpression with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] pattern The pattern to use + * @param[in] options The option for the regular expression + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has already been constructed. + * @exception E_INVALID_ARG The length of the specified @c pattern parameter is @c 0. + * + * The following example demonstrates how to use the %Construct() method. + * @code + * + * bool ret = false; + * + * String pattern(L"^CRUEL$"); + * String text(L"Hello\ncruel\nworld"); + * + * RegularExpression regex; + * regex.Construct(pattern, REGEX_CASELESS | REGEX_MULTI_LINE); + * ret = regex.Match(text, false); // This returns true value + * + * @endcode + */ + result Construct(const Tizen::Base::String& pattern, unsigned long options = 0x0); + + /** + * Checks whether the specified text matches completely or partially. + * + * @since 2.0 + * + * @return @c true if the text matches successfully, @n + * else @c false + * @param[in] text The text to match + * @param[in] fullMatch Set to @c true to match exactly, @n + * else @c false to match any substring of the text + * @param[out] pMatchedString A list of the matched string instances @n + The count of the matched items is acquired from IList::GetCount() and + * the maximum count of the items is @c 16. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been constructed as yet. + * @exception E_INVALID_ARG The length of the specified @c text parameter is @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the grouping subpatterns are used in a pattern, + * the @c pMatchedString list will contain the grouping data. @n + * For example, if the pattern has two grouping subpatterns, + * there will be three data sets in the @c pMatchedString list. @n + * The first data set will be a full grouping data and the second + * and the third data sets will contain individual grouping data. + * + * The following example demonstrates how to use the %Match() method. + * + * @code + * + * bool ret = false; + * + * String pattern(L"(\\d\\d)-(\\d\\d)-(\\d\\d\\d\\d)"); + * String text(L"04-12-1979"); + * String out; + * + * RegularExpression regex; + * regex.Construct(pattern); + * + * ArrayList list; + * list.Construct(); + * + * // Match + * ret = regex.Match(text, true, &list); // The list will contain four string instances + * + * out = *(String *)list.GetAt(0); // L"04-12-1979" + * out = *(String *)list.GetAt(1); // L"04" + * out = *(String *)list.GetAt(2); // L"12" + * out = *(String *)list.GetAt(3); // L"1979" + * + * list.RemoveAll(true); + * @endcode + */ + bool Match(const Tizen::Base::String& text, bool fullMatch, Tizen::Base::Collection::IList* pMatchedString = null) const; + + /** + * Matches the pattern from the starting point of the text and removes the matched string. @n + * If the pattern does not match the text at the starting point, it will return @c false. + * + * @since 2.0 + * + * @return @c true if the text matches successfully, @n + * else @c false + * @param[in, out] text The text to consume + * @param[out] pMatchedString A list of matched string instances @n + * The count of the matched items is acquired from IList::GetCount() and + * the maximum count of the items is @c 16. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been constructed as yet. + * @exception E_INVALID_ARG The length of the specified @c text parameter is @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the grouping subpatterns are used in a pattern, the @c pMatchedString list will + * contain the grouping data. @n + * For example, if the pattern has two grouping subpatterns, + * there will be three data sets in the @c pMatchedString list. @n + * The first data set will be a full grouping data and the second + * and the third data sets will contain individual grouping data. + + * + * The following example demonstrates how to use the %Consume() method. + * @code + * + * bool ret = false; + * String out; + * + * String pattern(L"(\\s+)([a-z]+)(\\d+)"); + * String text(L" abcd1234test"); + * ArrayList list; + * list.Construct(); + * + * RegularExpression regex; + * regex.Construct(pattern); + * ret = regex.Consume(text, &list); // The list will contain four string instances + * // and the text instance will be changed to L"test" + * out = *(String *)list.GetAt(0); // L" abcd1234" + * out = *(String *)list.GetAt(1); // L" " + * out = *(String *)list.GetAt(2); // L"abcd" + * out = *(String *)list.GetAt(3); // L"1234" + * + * list.RemoveAll(true); + * @endcode + */ + bool Consume(Tizen::Base::String& text, Tizen::Base::Collection::IList* pMatchedString = null) const; + + /** + * Matches the pattern in strings similar to the Consume() method but does not anchor the match at the beginning of the string. @n + * This operation can be used to find certain patterns in the text and extract the required information. + * + * @since 2.0 + * + * @return @c true if the text matches successfully, @n + * else @c false + * @param[in, out] text The text to find and consume + * @param[out] pMatchedString A list of matched string instances @n + * The count of the matched items is acquired from IList::GetCount() and + * the maximum count of the items is @c 16. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been constructed as yet. + * @exception E_INVALID_ARG The length of the specified @c text parameter is @c 0. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the grouping subpatterns are used in a pattern, + * the @c pMatchedString list will contain the grouping data. @n + * For example, if the pattern has two grouping subpatterns, + * there will be three data sets in the @c pMatchedString list. @n + * The first data set will be a full grouping data and the second + * and the third data sets will contain individual grouping data. + * + * The following example demonstrates how to use the %FindAndConsume() method. + * + * @code + * + * bool ret = false; + * String out; + * + * String pattern(L"(\\s+)([a-z]+)(\\d+)"); + * String text(L"test abcd1234test"); + * ArrayList list; + * list.Construct(); + * + * RegularExpression regex; + * regex.Construct(pattern); + * ret = regex.FindAndConsume(text, &list); // The list will contain four String instances + * // and text instance will be changed to L"test" + * out = *(String *)list.GetAt(0); // L" abcd1234" + * out = *(String *)list.GetAt(1); // L" " + * out = *(String *)list.GetAt(2); // L"abcd" + * out = *(String *)list.GetAt(3); // L"1234" + * + * list.RemoveAll(true); + * @endcode + */ + bool FindAndConsume(Tizen::Base::String& text, Tizen::Base::Collection::IList* pMatchedString = null) const; + + /** + * Replaces either the first match of a pattern in the text with the @c rewrite string or + * all the occurrences of a pattern in the text. + * + * @since 2.0 + * + * @return @c true if the text is replaced successfully, @n + * else @c false + * @param[in, out] text The text to replace when it is matched to a pattern + * @param[in] rewrite The text with which to replace + * @param[in] globalReplace Set to @c true to replace globally, @n + * else @c false to replace the first match of the pattern in the text + * @param[in] startPos The starting position of the text + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been constructed as yet. + * @exception E_INVALID_ARG The length of the specified @c pattern parameter is @c 0, or + * the size of @c pMatchedString exceeds limitations. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * The following example demonstrates how to use the %Replace() method. + * + * @code + * + * bool ret = false; + * + * String pattern(L"replace"); + * String text(L"test replace method"); + * String rewrite(L"REPLACE"); + * + * RegularExpression regex; + * regex.Construct(pattern); + * ret = regex.Replace(text, rewrite, false); // text = L"test REPLACE method" + * + * @endcode + */ + bool Replace(Tizen::Base::String& text, const Tizen::Base::String& rewrite, bool globalReplace, int startPos = 0) const; + + /** + * Extracts the first match of the pattern in the text. @n + * Similar to Replace() but @c rewrite is copied to @c out with substitutions. + * + * @since 2.0 + * + * @return @c true if the text is extracted successfully, @n + * else @c false + * @param[in] text The text to match + * @param[in] rewrite The text to replace + * @param[out] out The text to extract + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance has not been constructed as yet. + * @exception E_INVALID_ARG The length of the specified @c pattern parameter is @c 0, or + * the size of @c pMatchedString exceeds limitations. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * The following example demonstrates how to use the %Extract() method. + * + * @code + * + * bool ret = false; + * String out; + * + * String pattern(L"(.*)@([^.]*)"); + * String text(L"test@email.com"); + * String rewrite(L"\\2!\\1"); + * + * RegularExpression regex; + * regex.Construct(pattern); + * ret = regex.Extract(text, rewrite, out); // out = L"email!test" + * + * @endcode + */ + bool Extract(const Tizen::Base::String& text, const Tizen::Base::String& rewrite, Tizen::Base::String& out) const; + + /** + * Compares the specified instance to the calling instance. + * + * @since 2.0 + * + * @return @c true if the specified instance is equal to the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks The method returns @c true if all the attributes in the instance are the same. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Gets the pattern used to compile the regular expression. + * + * @since 2.0 + * + * @return The pattern used to compile the regular expression @n An empty string if this instance is not initialized + */ + Tizen::Base::String GetPattern(void) const; + + + /** + * Sets the value of the regular expression options. + * + * @since 2.0 + * + * @param[in] options The logical OR operator values of RegularExpressionOptions + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The value of @c options is invalid. + */ + result SetOptions(unsigned long options); + + + /** + * Gets the value of the regular expression options. + * + * @since 2.0 + * + * @return The logical OR operator values of RegularExpressionOptions + */ + unsigned long GetOptions(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param [in] regularExpression The instance of the %RegularExpression class to copy from + * @remarks This constructor is hidden. + */ + RegularExpression(const RegularExpression& regularExpression); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param [in] regularExpression An instance of %RegularExpression + * @remarks This operator is hidden. + */ + RegularExpression& operator =(const RegularExpression& regularExpression); + + + friend class _RegularExpressionImpl; + class _RegularExpressionImpl* __pRegularExpressionImpl; + +}; // RegularExpression + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_REGULAR_EXPRESSION_H_ diff --git a/inc/FBaseUtilStringTokenizer.h b/inc/FBaseUtilStringTokenizer.h new file mode 100644 index 0000000..8e80524 --- /dev/null +++ b/inc/FBaseUtilStringTokenizer.h @@ -0,0 +1,212 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilStringTokenizer.h + * @brief This is the header file for the %StringTokenizer class. + * + * @see String() + * + * This header file contains the declarations of the %StringTokenizer class. + */ + +#ifndef _FBASE_UTIL_STRING_TOKENIZER_H_ +#define _FBASE_UTIL_STRING_TOKENIZER_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class StringTokenizer + * @brief This class is used to break a String into tokens. + * + * @since 2.0 + * + * The %StringTokenizer class is used to break a String into tokens. It also provides ways to count the number of tokens. + * + * For more information on the class features, see String Tokenizer. + * + * The following example demonstrates how to use the %StringTokenizer class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::StringTokenizerSample(void) + * { + * String str(L"Tizen-StringTokenizer/Sample code"); + * String delim(L" /-"); + * + * // Creates a StringTokenizer instance + * StringTokenizer strTok(str, delim); + * + * int count = strTok.GetTokenCount(); // count == 4 + * + * String token; + * while (strTok.HasMoreTokens()) + * { + * strTok.GetNextToken(token); // Tizen, StringTokenizer, Sample, code + * } + * } + * @endcode + * + * + */ + +class _OSP_EXPORT_ StringTokenizer + : public Object +{ +public: + /** + * Initializes an instance of %StringTokenizer with the specified parameters. + * + * @since 2.0 + * + * @param[in] value An instance of String to parse + * @param[in] delimiters The delimiters + * @param[in] isToken A flag indicating whether to return the delimiters as tokens @n + * Set to @c true to treat the delimiters as tokens, @n + * else @c false to skip the delimiters. + * + */ + StringTokenizer(const String& value, const String& delimiters = L" \t\n\r\f", bool isToken = false); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + * + * @remarks The internally allocated memory block is freed when the instance is destroyed. + */ + virtual ~StringTokenizer(void); + + /** + * Gets the token count indicating the number of times the GetNextToken() method can be called before it returns an error code. + * + * @since 2.0 + * + * @return An integer value indicating the number of times the GetNextToken() method can be called + */ + int GetTokenCount(void); + + /** + * Checks whether there are any more tokens in the string after the current position. + * + * @since 2.0 + * + * @return @c true if there is at least one more token in the string after the current position, @n + * else @c false + */ + bool HasMoreTokens(void); + + /** + * Gets the next token from the string tokenizer. + * + * @since 2.0 + * + * @return An error code + * @param[out] token The next token + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The string tokenizer has no more tokens. + */ + result GetNextToken(String& token); + + /** + * Sets the new delimiters. + * + * @since 2.0 + * + * @return An error code + * @param[in] delimiters The new delimiters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * + * The following example demonstrates how to use the %SetDelimiters() method. + * + * @code + * + * String str(L"Tizen-Framework-Utility::StringTokenizer/class"); + * String delim(L":-"); + * + * String token; + * + * StringTokenizer strTok(str, delim); + * + * for (int i = 0; i < 3; i++) + * { + * strTok.GetNextToken(token); // Tizen, Framework, Utility + * } + * + * String newDelim(L"/"); + * + * strTok.SetDelimiters(newDelim); + * strTok.GetNextToken(token); // token == L"::StringTokenizer" + * + * @endcode + */ + result SetDelimiters(const String& delimiters); + +private: + // + // Sets the maximum characters of delimiters. + // + // @return An @c wchar_t value indicating the maximum characters + // + wchar_t SetMaxDelimChar(void); + + // + // Skips the delimiters starting from the specified position. + // + // @return If the delimiter is not regarded as a token, the method returns the index of the first non-delimiter character. @n + // If the delimiter is regarded as a token, the method returns the starting position. + // @param[in] position The position from where the delimiters need to skip + // + int SkipDelimiters(int position); + + // + // Scans the tokens starting from the specified position. + // + // @return The index of the next delimiter after the specified position + // @param[in] position The position to start scan + // + int ScanToken(int position); + + +private: + String __string; + String __delimiters; + int __curPosition; + int __newPosition; + int __maxStrLen; + wchar_t __maxDelimChar; + bool __isToken; + bool __isDelimChanged; + + friend class _StringTokenizerImpl; + class _StringTokenizerImpl* __pStringTokenizerImpl; + +}; // StringTokenizer + +}}} // Tizen::Base::Utility + +#endif //_FBASE_UTIL_STRING_TOKENIZER_H_ diff --git a/inc/FBaseUtilStringUtil.h b/inc/FBaseUtilStringUtil.h new file mode 100644 index 0000000..388ce63 --- /dev/null +++ b/inc/FBaseUtilStringUtil.h @@ -0,0 +1,375 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilStringUtil.h + * @brief This is the header file for the %StringUtil class. + * + * This header file contains the declarations of the %StringUtil class. + */ +#ifndef _FBASE_UTIL_STRING_UTIL_H_ +#define _FBASE_UTIL_STRING_UTIL_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class StringUtil + * @brief This class provides various utility methods for String. + * + * @since 2.0 + * + * The %StringUtil class provides various utility methods for String. + * + * For more information on the class features, see Utility. + * + * The following example demonstrates how to use the %StringUtil class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::StringUtilSample(void) + * { + * String str1(L"Sigma and Pi : \u03A0 and \u03A3"); + * String str2; + * + * // String to McharBuffer + * McharBuffer* pMb = StringUtil::StringToMbN(str1); + * + * // Gets a length of string in McharBuffer + * int length = StringUtil::GetStringLengthInMb(*pMb); + * + * // McharBuffer to String + * StringUtil::MbToString(*pMb, str2); + * + * if (str1.Equals(str2)) + * { + * // ... + * } + * + * delete pMb; + * } + * @endcode + */ +class _OSP_EXPORT_ StringUtil +{ +public: + /** + * @if OSPDEPREC + * Converts an McharBuffer to a null-terminated string. @n + * The position of the buffer is not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the WcharBufferToString(const WcharBuffer& mb, String& str) method. + * @since 2.0 + * + * @return An error code + * @param[in] mb An instance of McharBuffer + * @param[out] str The current position + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * @c null does not exist between the position and limit of buffer. + * @endif + */ + static result MbToString(const McharBuffer& mb, String& str); + + /** + * Converts an WcharBuffer to a null-terminated string. @n + * The position of the buffer is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] wb An instance of WcharBuffer + * @param[out] str The current position + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * @c null does not exist between the position and limit of buffer. + */ + static result WcharBufferToString(const WcharBuffer& wb, String& str); + + /** + * @if OSPDEPREC + * Gets a new McharBuffer from the specified string. @n + * The buffer's limit is the length of the string plus one and the starting position is @c 0. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the StringToWcharBufferN(const String& str) method. + * @since 2.0 + * + * @return A pointer to the McharBuffer instance from the specified string, @n + * else @c null if an exception occurs + * @param[in] str The string to read + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c str is an empty string. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @endif + */ + static McharBuffer* StringToMbN(const String& str); + + /** + * Gets a new WcharBuffer from the specified string. @n + * The buffer's limit is the length of the string plus one and the starting position is @c 0. + * + * @since 2.0 + * + * @return A pointer to the WcharBuffer instance from the specified string, @n + * else @c null if an exception occurs + * @param[in] str The string to read + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c str is an empty string. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static WcharBuffer* StringToWcharBufferN(const String& str); + + /** + * @if OSPDEPREC + * Gets a new McharBuffer from a substring of the specified string. @n + * The buffer's limit is the length of the string plus one and the starting position is @c 0. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the StringToWcharBufferN(const String& str, int index, int length) method. + * @since 2.0 + * + * @return A pointer to the McharBuffer instance from the substring of the specified string, @n + * else @c null if an exception occurs + * @param[in] str The string to read + * @param[in] index The starting index for the substring in the string @n + * It must not be longer than the length of the string. + * @param[in] length The length of the substring @n + * It must not be longer than the length of the given string minus the specified @c index. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c str is an empty string. + * @exception E_OUT_OF_RANGE The @c index and @c length are outside the bounds of the data structure. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @endif + */ + static McharBuffer* StringToMbN(const String& str, int index, int length); + + /** + * Gets a new WcharBuffer from a substring of the specified string. @n + * The buffer's limit is the length of the string plus one and the starting position is @c 0. + * + * @since 2.0 + * + * @return A pointer to the WcharBuffer instance from the substring of the specified string, @n + * else @c null if an exception occurs + * @param[in] str The string to read + * @param[in] index The starting index for the substring in the string @n + * It must not be longer than the length of the string. + * @param[in] length The length of the substring @n + * It must not be longer than the length of the given string minus the specified @c index. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c str is an empty string. + * @exception E_OUT_OF_RANGE The @c index and @c length are outside the bounds of the data structure. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static WcharBuffer* StringToWcharBufferN(const String& str, int index, int length); + + /** + * @if OSPDEPREC + * Gets the string length in the McharBuffer. @n + * The string length is the length from the current position of the %McharBuffer to the @c null character. + * The position of the buffer is not changed. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as @c mchar type is changed to @c wchar_t type. + * Instead of using this method, use the GetStringLengthInWcharBuffer(const WcharBuffer& wb) method. + * + * @since 2.0 + * + * @return The length of the McharBuffer instance, @n + * else @c -1 if the %McharBuffer instance is not terminated with the @c null character + * @param[in] mb An instance of McharBuffer + * @remarks If @c null does not exist between the position and the limit of the buffer, the method returns @c -1. + * @endif + */ + static int GetStringLengthInMb(const McharBuffer& mb); + + /** + * Gets the string length in the WcharBuffer. @n + * The string length is the length from the current position of the %WcharBuffer to the @c null character. + * The position of the buffer is not changed. + * + * @since 2.0 + * + * @return The length of the WcharBuffer instance, @n + * else @c -1 if the %WcharBuffer instance is not terminated with the @c null character + * @param[in] wb An instance of WcharBuffer + * @remarks If @c null does not exist between the position and the limit of the buffer, the method returns @c -1. + */ + static int GetStringLengthInWcharBuffer(const WcharBuffer& wb); + + /** + * Gets a new ByteBuffer encoded from the specified string. @n + * The buffer's limit is the length of the string plus one and the starting position is @c 0. + * + * @since 2.0 + * + * @return A pointer to the ByteBuffer instance encoded from the specified string, @n + * else @c null if an exception occurs + * @param[in] unicodeString A string to encode + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Base::ByteBuffer + * @see Tizen::Base::String + */ + static ByteBuffer* StringToUtf8N(const String& unicodeString); + + /** + * Decodes a null-terminated UTF-8 string into a Unicode string. @n + * The position of the buffer is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] pUtf8String A pointer to a String instance containing UTF-8 codes + * @param[out] unicodeString A string containing Unicode characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c pUtf8String is a @c null reference. + * @exception E_INVALID_ENCODING_RANGE The indicated string contains UTF-8 code that is outside the bounds specified by the character encoding scheme. + * + * The following example demonstrates how to use the %Utf8ToString() method. + * + * @code + * + * const char* pUtf8String = "Utf8ToString"; + * + * String str; + * + * // Decodes a UTF-8 string into a Unicode string + * StringUtil::Utf8ToString(pUtf8String, str); + * + * @endcode + */ + static result Utf8ToString(const char* pUtf8String, String& unicodeString); + + /** + * Decodes a string consisting of base 64 digits to a ByteBuffer. @n + * The buffer's limit is the length of the string plus one and the starting position is @c 0. + * + * @since 2.0 + * + * @return A pointer to the ByteBuffer instance decoded from the specified string, @n + * else @c null if an exception occurs + * @param[in] base64String A string to decode + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. @n + * The specified @c base64String is not a valid Base64 string. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * The following example demonstrates how to use the %DecodeBase64StringN() method. + * + * @code + * + * const char* pChar = "abcdefg123456"; + * int size = strlen(pChar); + * + * String encodedStr; + * ByteBuffer buffer; + * buffer.Construct(size + 1); + * + * buffer.SetArray((byte*)pChar, 0, size); + * buffer.SetByte('\0'); + * buffer.Flip(); + * + * StringUtil::EncodeToBase64String(buffer, encodedStr); + * + * // Decodes a String consisting of base 64 digits to a ByteBuffer + * ByteBuffer* pDecodedBuffer = StringUtil::DecodeBase64StringN(encodedStr); + * + * @endcode + */ + static ByteBuffer* DecodeBase64StringN(const String& base64String); + + /** + * Encodes a ByteBuffer into a string consisting of base 64 characters. @n + * The position of the buffer is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] buffer An instance of ByteBuffer to encode + * @param[out] encodedString An instance of String consisting of base 64 characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the @c buffer is empty. + * + * The following example demonstrates how to use the %EncodeToBase64String() method. + * + * @code + * + * const char* pChar = "abcdefg123456"; + * int size = strlen(pChar); + * + * String encodedStr; + * ByteBuffer buffer; + * buffer.Construct(size + 1); + * + * buffer.SetArray((byte*)pChar, 0, size); + * buffer.SetByte('\0'); + * buffer.Flip(); + * + * // Encodes a ByteBuffer into a String consisting of base 64 characters + * StringUtil::EncodeToBase64String(buffer, encodedStr); + * + * @endcode + */ + static result EncodeToBase64String(const ByteBuffer& buffer, String& encodedString); + +private: + /** + * This default constructor is intentionally declared as private because this class cannot be constructed. + */ + StringUtil(void); + + /** + * This destructor is intentionally declared as private because this class cannot be constructed. + */ + ~StringUtil(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs The instance of the StringUtil + */ + StringUtil(const StringUtil& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %StringUtil + */ + StringUtil& operator =(const StringUtil& rhs); +}; // StringUtil + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_STRING_UTIL_H_ diff --git a/inc/FBaseUtilTypes.h b/inc/FBaseUtilTypes.h new file mode 100644 index 0000000..b4e4718 --- /dev/null +++ b/inc/FBaseUtilTypes.h @@ -0,0 +1,67 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilTypes.h + * @brief This is the header file for various utilities. + * + * This header file contains the descriptions of various utilities. + */ + +#ifndef _FBASE_UTIL_TYPES_H_ +#define _FBASE_UTIL_TYPES_H_ + +namespace Tizen { namespace Base { namespace Utility +{ + + +/** + * @enum CompressionLevel + * + * Defines the compression level. + * + * @since 2.0 + */ +enum CompressionLevel +{ + BEST_SPEED = 0, /**< For best speed */ + BEST_COMPRESSION, /**< For best compression */ + DEFAULT_COMPRESSION /**< For average speed and average compression */ +}; + + +/** + * @enum LinkType + * + * Defines the possible link types. + * + * @since 2.0 + */ +enum LinkType +{ + LINK_TYPE_NONE = 0x0000, /**< The no link type */ + LINK_TYPE_URL = 0x0001, /**< The URL link type */ + LINK_TYPE_EMAIL = 0x0002, /**< The email link type */ + LINK_TYPE_TEL_NUM = 0x0004, /**< The telephone number link type */ + LINK_TYPE_APPCONTROL = 0x0008, /**< The AppControl link type */ + LINK_TYPE_MIME = 0x0010, /**< The MIME link type */ + LINK_TYPE_MAX = 0x7FFF /*< Not Used. The placeholder */ +}; + +}}} // Tizen::Base::Utility + +#endif /* _FBASE_UTIL_TYPES_H_ */ diff --git a/inc/FBaseUtilUri.h b/inc/FBaseUtilUri.h new file mode 100644 index 0000000..f2d2248 --- /dev/null +++ b/inc/FBaseUtilUri.h @@ -0,0 +1,963 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilUri.h + * @brief This is the header file for the %Uri class. + * + * This header file contains the declarations of the %Uri class. + */ +#ifndef _FBASE_UTIL_URI_H_ +#define _FBASE_UTIL_URI_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +/** + * @class Uri + * @brief This class provides useful methods for URI. + * + * @since 2.0 + * + * The %Uri class represents a Uniform Resource Identifier (URI) as defined by RFC2396 and provides accessors + * which access the URI component. + * It also provides methods for creating, accessing, normalizing, resolving, and relativizing %Uri instances. + * + * For more information on the class features, see URI. + * + * The following example demonstrates how to use the %Uri class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::UriSample(void) + * { + * String base(L"http://www.samsung.com"); + * String against(L"/osp/framework/index.html"); + * String resolveString(L"http://www.samsung.com/osp/framework/index.html"); + * + * Uri baseUri; + * baseUri.SetUri(base); + * + * Uri againstUri; + * againstUri.SetUri(against); + * + * Uri resultUri; + * baseUri.Resolve(againstUri, resultUri); + * + * String resultString = resultUri.ToString(); + * if (resultString.Equals(resolveString)) + * { + * // ... + * } + * + * } + * @endcode + */ +class _OSP_EXPORT_ Uri + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Uri(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] uri An instance of %Uri to copy + */ + Uri(const Uri& uri); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Uri(void); + + /** + * Sets the current %Uri instance to the value of the specified instance of %Uri. + * + * @since 2.0 + * + * @param[in] uri An instance of %Uri + */ + void SetUri(const Uri& uri); + + /** + * Sets the current %Uri instance by parsing a given string. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string to parse into a URI + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c str is an empty string. + * @exception E_INVALID_FORMAT The specified @c str violates the URI syntax (RFC 2396). + */ + result SetUri(const Tizen::Base::String& str); + + /** + * Sets an absolute %Uri instance with given components. + * + * @since 2.0 + * + * @return An error code + * @param[in] scheme The scheme + * @param[in] ssp The scheme-specific-part + * @param[in] fragment The fragment + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT A component violates the URI syntax(RFC 2396). + */ + result SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& ssp, const Tizen::Base::String& fragment); + + /** + * Sets an absolute and hierarchical %Uri instance with the given components. + * + * @since 2.0 + * + * @return An error code + * @param[in] scheme The scheme + * @param[in] userInfo The user name and authorization + * @param[in] host The host name + * @param[in] port The port number + * @param[in] path The path + * @param[in] query The query + * @param[in] fragment The fragment + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT A component violates the URI syntax(RFC 2396). + */ + result SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& userInfo, const Tizen::Base::String& host, int port, const Tizen::Base::String& path, const Tizen::Base::String& query, const Tizen::Base::String& fragment); + + /** + * Sets an absolute and hierarchical %Uri instance with the given components. + * + * @since 2.0 + * + * @return An error code + * @param[in] scheme The scheme + * @param[in] host The host name + * @param[in] path The path + * @param[in] fragment The fragment + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT A component violates the URI syntax(RFC 2396). + * @remarks The authority and query component are left empty, and the port is set to @c -1. + */ + result SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& host, const Tizen::Base::String& path, const Tizen::Base::String& fragment); + + /** + * Sets an absolute and hierarchical %Uri instance with the given components. + * + * @since 2.0 + * + * @return An error code + * @param[in] scheme The scheme + * @param[in] authority The authority + * @param[in] path The path + * @param[in] query The query + * @param[in] fragment The fragment + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT A component violates the URI syntax(RFC 2396). + */ + result SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& authority, const Tizen::Base::String& path, const Tizen::Base::String& query, const Tizen::Base::String& fragment); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return A reference to the calling instance + * @param[in] rhs An instance of %Uri + */ + Uri& operator =(const Uri& rhs); + + /** + * Gets the value of the authority component. + * + * @since 2.0 + * + * @return The value of the authority component, @n + * else an empty string if the authority component is undefined + * @remarks The string returned by this method is equal to the string returned by GetEncodedAuthority(), + * except that all sequences of the escaped octets are decoded. + */ + Tizen::Base::String GetAuthority(void) const; + + /** + * Gets the value of the fragment component. + * + * @since 2.0 + * + * @return The value of the fragment component, @n + * else an empty string if the fragment component is undefined + * @remarks The string returned by this method is equal to the string returned by GetEncodedFragment(), + * except that all sequences of the escaped octets are decoded. + */ + Tizen::Base::String GetFragment(void) const; + + /** + * Gets the value of the host component. + * + * @since 2.0 + * + * @return The value of the host component, @n + * else an empty string if the host component is undefined + */ + Tizen::Base::String GetHost(void) const; + + /** + * Gets the value of the path component. + * + * @since 2.0 + * + * @return The value of the path component, @n + * else an empty string if the path component is undefined + * @remarks The string returned by this method is equal to the string returned by GetEncodedPath(), + * except that all sequences of the escaped octets are decoded. + */ + Tizen::Base::String GetPath(void) const; + + + /** + * Gets the value of the port component. + * + * @since 2.0 + * + * @return The value of the port component, @n + * else @c -1 if the port component is undefined + */ + int GetPort(void) const; + + + /** + * Gets the value of the query component. + * + * @since 2.0 + * + * @return The value of the query component, @n + * else an empty string if the query component is undefined + * @remarks The string returned by this method is equal to the string returned by GetEncodedQuery(), + * except that all sequences of the escaped octets are decoded. + */ + Tizen::Base::String GetQuery(void) const; + + + /** + * Gets the value of the scheme component. + * + * @since 2.0 + * + * @return The value of the query scheme, @n + * else an empty string if the query scheme is undefined + */ + Tizen::Base::String GetScheme(void) const; + + + /** + * Gets the value of the scheme-specific-part component. + * + * @since 2.0 + * + * @return The value of the scheme-specific-part component, @n + * else an empty string if the scheme-specific-part component is undefined + * @remarks The string returned by this method is equal to the string returned by GetEncodedSchemeSpecificPart(), + * except that all sequences of the escaped octets are decoded. + */ + Tizen::Base::String GetSchemeSpecificPart(void) const; + + + /** + * Gets the value of the user-info component. + * + * @since 2.0 + * + * @return The value of the user-info component, @n + * else an empty string if the user-info component is undefined + * @remarks The string returned by this method is equal to the string returned by GetEncodedUserInfo(), + * except that all sequences of the escaped octets are decoded. + */ + Tizen::Base::String GetUserInfo(void) const; + + + /** + * Gets the encoded value of the authority component. @n + * The non-US-ASCII characters in the authority component are encoded to escaped octets. + * + * @since 2.0 + * + * @return The encoded value of the authority component, @n + * else an empty string if the authority component is undefined + */ + Tizen::Base::String GetEncodedAuthority(void) const; + + + /** + * Gets the encoded value of the fragment component. @n + * The non-US-ASCII characters in the fragment component are encoded to escaped octets. + * + * @since 2.0 + * + * @return The encoded value of the fragment component, @n + * else an empty string if the fragment component is undefined + */ + Tizen::Base::String GetEncodedFragment(void) const; + + + /** + * Gets the encoded value of the path component. @n + * The non-US-ASCII characters in the path component are encoded to escaped octets. + * + * @since 2.0 + * + * @return The encoded value of the path component, @n + * else an empty string if the path component is undefined + */ + Tizen::Base::String GetEncodedPath(void) const; + + + /** + * Gets the encoded value of the query component. @n + * The non-US-ASCII characters in the query component are encoded to escaped octets. + * + * @since 2.0 + * + * @return The encoded value of the query component, @n + * else an empty string if the query component is undefined + */ + Tizen::Base::String GetEncodedQuery(void) const; + + + /** + * Gets the encoded value of the scheme-specific-part component. @n + * The non-US-ASCII characters in the scheme-specific-part component are encoded to escaped octets. + * + * @since 2.0 + * + * @return The encoded value of the scheme-specific-part component, @n + * else an empty string if the scheme-specific-part component is undefined + */ + Tizen::Base::String GetEncodedSchemeSpecificPart(void) const; + + /** + * Gets the encoded value of a user-info component, + * or returns an empty string if the user-info component is undefined. @n + * The non-US-ASCII characters in the user-info component are encoded to escaped octets. + * + * @since 2.0 + * + * @return The encoded value of user-info, @n + * else an empty string if the user-info component is undefined + */ + Tizen::Base::String GetEncodedUserInfo(void) const; + + + /** + * Checks whether the current %Uri instance is an absolute URI. + * + * @since 2.0 + * + * @return @c true if the current %Uri instance is an absolute URI, @n + * else @c false + */ + bool IsAbsolute(void) const; + + + /** + * Checks whether the calling %Uri instance is an opaque URI. + * + * @since 2.0 + * + * @return @c true if the current %Uri instance is an opaque URI, @n + * else @c false + */ + bool IsOpaque(void) const; + + + /** + * Gets the encoded US-ASCII string. + * + * @since 2.0 + * + * @return The encoded US-ASCII string + * @remarks If this URI does not contain any non US_ASCII characters, + * then the string returned by this method is equal to the string returned by ToString(). + * + * The following example demonstrates how to use the %GetEncodedString() method. + * + * @code + * String str(L"http://www.sec.com/osp?currency==\u20ac"); + * + * Uri uri; + * uri.SetUri(str); + * + * String encode = uri.GetEncodedString(); // encode == L"http://www.sec.com/osp?currency==%E2%82%AC" + * + * @endcode + */ + Tizen::Base::String GetEncodedString(void) const; + + /** + * Compares the calling URI instance to the specified %Uri instance. @n + * When comparing corresponding components of two URIs, if one component in the current instance is undefined + * but the other is defined, then the current instance is considered to be less than the given object. + * + * @since 2.0 + * + * @return The result of the comparison + * @code + * < 0 if the current instance is less than the given object + * = 0 if the current instance is equal to the given object + * > 0 if the current instance is greater than the given object + * @endcode + * @param[in] uri An instance of %Uri + * @remarks + * + * Ordering of URIs + * 1. Scheme + * Two URIs are ordered according to the ordering of schemes, without regard to case. + * 2. Hierarchical URI vs. Opaque URI + * A hierarchical URI is less than an opaque URI if they have an identical scheme. + * 3. Scheme-specific-part + * If two opaque URIs have an identical scheme, they are ordered according to + * the scheme-specific-part, without regard to %case. + * 4. Fragment + * If two opaque URIs have identical schemes and scheme-specific-parts, they are ordered according + * to the ordering of fragments, without regard to case. + * 5. Authority + * If two hierarchical URIs have identical schemes, they are ordered according to the authority, + * without regard to the case. + * 5-1. Server-based authority + * If two URIs are server-based, they are ordered according to their user-information, + * without regard to case. + * If the hosts are identical, then the URIs are ordered according to the ordering of ports. + * 6. Path + * If two hierarchical URIs have identical schemas and authority components, they are ordered according to the + * ordering of paths, without regard to the case. + * If their paths are identical, their queries are compared. And if the queries are the same, then their fragments + * are compared. + * + */ + int CompareTo(const Uri& uri) const; + + + /** + * Compares the specified instance to the current instance. + * + * @since 2.0 + * + * @return @c true if the two instances are equal, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks Two equal instances must return the same hash value. The default + * implementation of this method returns @c true if two instances + * have the same address. @n + * The method can be overridden to support value equality. Furthermore, the Equals() + * method must return the same results as the equality operator. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. + */ + virtual int GetHashCode(void) const; + + + /** + * Normalizes the current URI. + * + * @since 2.0 + * + * @return The normalized URI, @n + * else the current URI in case any error occurs + * @remarks Normalization is the process of removing unnecessary "." and ".." segments from the path component of the + * hierarchical URI. All "." segments are removed and If a ".." segment is preceded by a non-".." segment, + * both of these segments are removed. If a URI is opaque, the normalization has no effect. + * + * The following example demonstrates how to use the %Normalize() method. + * + * @code + * Uri uri1; + * uri1.SetUri(L"http://www.example.com/a/b/../c/./d.html"); + * + * Uri uriNormalized = uri1.Normalize(); + * String uriStr = uriNormalized.ToString(); // uriStr == L"http://www.example.com/a/c/d.html" + * + * @endcode + */ + Uri Normalize(void); + + + /** + * Parses the server-based authority component, if defined. + * + * @since 2.0 + * + * @return An error code + * @param[out] uri The parsed URI + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The authority component is defined but cannot be parsed as a server-based authority. + * @remarks This method is provided because the generic URI syntax cannot always distinguish a malformed server-based authority from a legitimate registry-based authority. + * For example, the authority component in the URI string "//foo:bar/" is not a legal + * server-based authority but it is legal as a registry-based authority. + */ + result ParseAuthority(Uri& uri); + + + /** + * Relativizes the specified %Uri instance against the calling %Uri instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] uri The %Uri to relativize against the calling %Uri + * @param[out] resultUri The relativized URI + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks Relativization is the opposite of Resolution. It is used + * to divide a URI into the base URI and the relative URI. + */ + result Relativize(const Uri& uri, Uri& resultUri); + + + /** + * Resolves the specified %Uri instance against the calling %Uri instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] uri The URI to resolve against this URI + * @param[out] resultUri The resolved URI + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks Resolution is the process of resolving a URI against another, base URI. For hierarchical URI, + * the path of the original is resolved against the path of the base URI and then normalized. @n + * + * For example, to resolve the URI "/osp/framework/index.html" against the base URI "http://www.samsung.com" , + * the resultant URI is "http://www.samsung.com/osp/framework/index.html". + * + */ + result Resolve(const Uri& uri, Uri& resultUri); + + + /** + * Sets the authority component to the specified String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] authority The authority + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is invalid. + */ + result SetAuthority(const Tizen::Base::String& authority); + + + /** + * Sets the fragment component to the specified String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] fragment The new fragment + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is invalid. + */ + result SetFragment(const Tizen::Base::String& fragment); + + + /** + * Sets the host component to the specified String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] host The new host + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is invalid. + */ + result SetHost(const Tizen::Base::String& host); + + + /** + * Sets the path component to the specified String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] path The new path component + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is invalid. + */ + result SetPath(const Tizen::Base::String& path); + + + /** + * Sets the port component to a given integer. + * + * @since 2.0 + * + * @return An error code + * @param[in] port The new port component + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c port is negative. + */ + result SetPort(int port); + + + /** + * Sets the query component to the specified String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] query The new query string + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is invalid. + */ + result SetQuery(const Tizen::Base::String& query); + + + /** + * Sets the scheme component to the specified String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] scheme The new scheme + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is invalid. + */ + result SetScheme(const Tizen::Base::String& scheme); + + + /** + * Sets the scheme-specific-part component to the specified String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] ssp The new scheme-specific-part component + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is invalid. + */ + result SetSchemeSpecificPart(const Tizen::Base::String& ssp); + + + /** + * Sets the user-info component to the specified String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] userInfo The new user-info string + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified string is invalid. + */ + result SetUserInfo(const Tizen::Base::String& userInfo); + + + /** + * Gets the content of the calling %Uri instance as a string containing escaped octets. + * + * @since 2.0 + * + * @return The content of this URI as a string containing escaped octets + */ + Tizen::Base::String ToString(void) const; + +private: + // + // Constructs an Uri instance with the given components. + // scheme, ssp(opaquePart), authority, user-info, host, port, path, query, fragment + // + result SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& opaque, + const Tizen::Base::String& authority, const Tizen::Base::String& userInfo, + const Tizen::Base::String& host, int port, const Tizen::Base::String& path, + const Tizen::Base::String& query, const Tizen::Base::String& fragment); + + // + // Appends a given scheme-specific-part to a String. + // + result AppendSchemeSpecificPart(Tizen::Base::String& strbuf, const Tizen::Base::String& opaque, + const Tizen::Base::String& authority, const Tizen::Base::String& userInfo, + const Tizen::Base::String& host, int port, const Tizen::Base::String& path, + const Tizen::Base::String& query) const; + + // + // Appends a given fragment to a String. + // + result AppendFragment(Tizen::Base::String& strbuf, const Tizen::Base::String& fragment) const; + + // + // Appends a given authority component to a String. + // + result AppendAuthority(Tizen::Base::String& strbuf, const Tizen::Base::String& authority, + const Tizen::Base::String& userInfo, const Tizen::Base::String& host, int port) const; + + // + // Parses a given URI string. + // + result ParseUri(const Tizen::Base::String& str); + + // + // Copies a given URI. + // + result CopyUri(const Uri& uri); + + // + // Encodes all components - authority, fragment, path, query, and ssp. + // + void EncodeAllComponent(void); + + // + // Parses a hierarchical URI string. + // @return The start index of the fragment. If the operation fails, @c -1 is returned. + // @param[in] startSsp The start index of scheme-specific-part + // @param[in] lengthOfUri The length of the URI string + // @param[out] authority A parsed authority component + // @param[out] path A parsed path component + // @param[out] query A parsed query component + // + result ParseHierarchicalUri(const Tizen::Base::String& str, int startSsp, Tizen::Base::String& authority, + Tizen::Base::String& path, Tizen::Base::String& query, int& index); + + + // + // Parses a server_based authority component. + // server_based authority: [user-info@][:port] + // + result ParseAuthority(const Tizen::Base::String& str, int curIndex, Tizen::Base::String& newAuth, + Tizen::Base::String& userInfo, Tizen::Base::String& host, int& port); + + void SetAndEncodeAuthority(const Tizen::Base::String& authority, + const Tizen::Base::String& path, const Tizen::Base::String& query); + + // + // Parses a server_based authority component. + // Assigns user-info, host and port to their member variable. + // + result ParseServerAuthority(const Tizen::Base::String& str, Tizen::Base::String& user, Tizen::Base::String& host, int& port); + + // + // Parses an IPv4 address. + // + result ParseIpv4(const Tizen::Base::String& str, int index, int& count); + + // + // Parses an IPv6 address. + // It will be implemented. + // + result ParseIpv6(const Tizen::Base::String& ip6, Tizen::Base::String& outIpv6); + + // + // Parses a host name and returns a host name as an out-param. + // + result ParseHostName(const Tizen::Base::String& str, int index, Tizen::Base::String& host); + + // + // These methods verify components. + // If a given component is valid, return @c true, else, @c false. + // @param[in] str A component + // + bool VerifyScheme(const Tizen::Base::String& str) const; + bool VerifyAuthority(const Tizen::Base::String& str) const; + bool VerifyHost(const Tizen::Base::String& str) const; + bool VerifyPath(const Tizen::Base::String& str) const; + bool VerifyUserInfo(const Tizen::Base::String& str) const; + bool VerifyUriChar(const Tizen::Base::String& str) const; + + // + // Checks that a given string only consists of server_based characters. + // @return @c true if a string consists of only server_based characters, @n + // else @c false + // + bool VerifyServerAuthority(const Tizen::Base::String& str) const; + + // + // Checks that a given string only consists of registry_based characters. + // @return @c true if a string consists of only registry_based characters, @n + // else @c false + // + bool VerifyRegistryAuthority(const Tizen::Base::String& str) const; + + // + // Checks whether a given char is a user-info character or not. + // user-info char: alphabet, digit, -_.!~*'(), ;:&=+$, + // + bool IsUserInfo(wchar_t mch) const; + + // + // Returns true if a given wchar_t is a mark character. + // mark char : -_.!~*'() + // + bool IsMark(wchar_t mch) const; + + // + // Returns true if two given wchar_ts are hexadecimals. + // + bool IsEscapedChar(wchar_t ch1, wchar_t ch2) const; + + // + // Returns true if a given string is already encoded. + // + bool IsEncoded(const Tizen::Base::String& str) const; + + // + // Returns true if a given wchar_t is an ISO control character. + // + bool IsControlChar(wchar_t ch) const; + + // + // Compares @c pStr1 with @c pStr2. @n + // If @c pStr1 is greater than @c pStr2, returns @c 1. + // If two strings are the same, return @c 0. + // If @c pStr1 is less than @c pStr2, returns @c -1. + // + int Compare(const Tizen::Base::String& pStr1, const Tizen::Base::String& pStr2) const; + + // + // Adds leading dots. + // If the normalized path is relative, and if the first segment could be parsed as a scheme name, + // then prepend a '.' segment + // + void AddLeadingDot(Tizen::Base::WcharBuffer& path, int* segments, int numSegments); + + // + // Finds the first character in stopString. + // If there is not a character in stopString, the last index is returned. + // + int Scan(const Tizen::Base::String& str, int start, const Tizen::Base::String& stopString); + + // + // Normalizes a given string and removes unnecessary dots. + // + Tizen::Base::String InternalNormalize(const Tizen::Base::String& path); + + // + // Returns the number of segments from a given path. + // + int GetNumberOfSegments(const Tizen::Base::String& path) const; + + // Join the segments in the given path according to the given segment-index array, + // ignoring those segments whose index entries have been set to @c -1, and inserting slashes as needed. + // Return the length of the resulting path. + // + // Preconditions: + // segs[i] == @c -1 implies segment i is to be ignored + // path computed by split, as above, with '\0' having replaced '/' + // + // Postconditions: + // path[0] .. path[return value] == Resulting path + // + int Join(Tizen::Base::WcharBuffer& path, int* segments, int segCount); + + // + // Removes unnecessary dots and segment pairs consisting of a non-".." segment + // followed by a ".." segment + // + void RemoveDots(const Tizen::Base::WcharBuffer& mb, int* segments, int segCount, int length); + + // + // Splits a path component into segments. + // + void SplitIntoSegments(Tizen::Base::WcharBuffer& mb, int* segments, int segCount); + + // + // Implements Uri resolution in RFC2396 5.2 + // + result Resolve(const Uri& baseUri, const Uri& childUri, Uri& resultUri); + + // + // Resolves the path of the base and child URI. + // + Tizen::Base::String ResolvePath(const Tizen::Base::String& path, const Tizen::Base::String& resolve, bool isAbsolute); + + bool EqualsComponent(const Tizen::Base::String& comp1, const Tizen::Base::String& comp2); + result Relativize(const Uri& baseUri, const Uri& childUri, Uri& resultUri); + + // + // Converts a component represented by UTF8 to a component represented by Unicode. + // + Tizen::Base::String Decode(const Tizen::Base::String& str); + + // + // Converts a component represented by Unicode to a component represented by UTF8. + // + Tizen::Base::String Encode(const Tizen::Base::String& str) const; + + static result AppendEscape(Tizen::Base::String& strbuf, byte b); + + // + // Clears the current instance. + // + void Clear(void); + + // Component + Tizen::Base::String __scheme; + Tizen::Base::String __ssp; + Tizen::Base::String __authority; + Tizen::Base::String __host; + Tizen::Base::String __fragment; + Tizen::Base::String __path; + Tizen::Base::String __userInfo; + Tizen::Base::String __query; + Tizen::Base::String __ipv4; + Tizen::Base::String __ipv6; + + // Encoded Component + Tizen::Base::String __encodedAuth; + Tizen::Base::String __encodedFragment; + Tizen::Base::String __encodedPath; + Tizen::Base::String __encodedQuery; + Tizen::Base::String __encodedSsp; + Tizen::Base::String __encodedUserInfo; + + int __port; + bool __hasScheme; + int __ipv6ByteCount; + + friend class _UriImpl; + class _UriImpl* __pUriImpl; + +}; // Uri + +}}} // Tizen::Base::Utility + +#endif //_FBASE_UTIL_URI_H_ diff --git a/inc/FBaseUtilUrlDecoder.h b/inc/FBaseUtilUrlDecoder.h new file mode 100644 index 0000000..09db2a3 --- /dev/null +++ b/inc/FBaseUtilUrlDecoder.h @@ -0,0 +1,116 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilUrlDecoder.h + * @brief This is the header file for the %UrlDecoder class. + * + * This header file contains the declarations of the %UrlDecoder class. + */ +#ifndef _FBASE_UTIL_URL_DECODER_H_ +#define _FBASE_UTIL_URL_DECODER_H_ + +// includes +#include + + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class UrlDecoder + * @brief This class provides a method for decoding strings using a specific encoding scheme. + * + * @since 2.0 + * + * The %UrlDecoder class provides a method for decoding strings using a specific encoding scheme. + * + * For more information on the class features, see UrlEncoder and UrlDecoder. + * + * The following example demonstrates how to use the %UrlDecoder class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::UrlDecoderSample(void) + * { + * result r = E_SUCCESS; + * String str1(L"url+encoding+test%3f"); + * String str2; + * + * // Decodes the input string + * r = UrlDecoder::Decode(str1, L"UTF-8", str2); + * } + * @endcode + */ + +class _OSP_EXPORT_ UrlDecoder +{ +public: + /** + * Decodes an encoded string using a specific encoding scheme. + * + * @since 2.0 + * + * @return An error code + * @param[in] str An instance of String to decode + * @param[in] encodingScheme The supported encoding scheme + * @param[out] decodedStr The decoded string + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @exception E_UNSUPPORTED_TYPE The specified encoding scheme is not supported. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method is used for decoding. It decodes an application/x-www-form-urlencoded string using a + * specific encoding scheme. The supplied encoding scheme is used to determine what characters are represented + * by any consecutive sequences of the form "%ab", where ab is the two-digit hexadecimal representation of a + * byte. + *@see UrlEncoder + */ + static result Decode(const Tizen::Base::String& str, const Tizen::Base::String& encodingScheme, Tizen::Base::String& decodedStr); + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + UrlDecoder(void); + + /* + * This destructor is intentionally declared as private so that only the platform can delete an instance. + */ + virtual ~UrlDecoder(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs The instance of the UrlDecoder + */ + UrlDecoder(const UrlDecoder& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %UrlDecoder + */ + UrlDecoder& operator =(const UrlDecoder& rhs); +}; // UrlDecoder + +}}} // Tizen::Base::Utility +#endif // _FBASE_UTIL_URL_DECODER_H_ \ No newline at end of file diff --git a/inc/FBaseUtilUrlEncoder.h b/inc/FBaseUtilUrlEncoder.h new file mode 100644 index 0000000..9d38497 --- /dev/null +++ b/inc/FBaseUtilUrlEncoder.h @@ -0,0 +1,118 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilUrlEncoder.h + * @brief This is the header file for the %UrlEncoder class. + * + * This header file contains the declarations of the %UrlEncoder class. + */ + +#ifndef _FBASE_UTIL_URL_ENCODER_H_ +#define _FBASE_UTIL_URL_ENCODER_H_ + +// includes +#include + + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class UrlEncoder + * @brief This class provides a method for encoding a string using a specific encoding scheme. + * + * @since 2.0 + * + * The %UrlEncoder class provides a method for encoding a string using a specific encoding scheme. + * + * For more information on the class features, see UrlEncoder and UrlDecoder. + * + * The following example demonstrates how to use the %UrlEncoder class. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::UrlEncoderSample(void) + * { + * result r = E_SUCCESS; + * String str1(L"url encoding test?"); + * String str2; + * + * // Encodes the input string + * r = UrlEncoder::Encode(str1, L"UTF-8", str2); + * } + * @endcode + */ + + +class _OSP_EXPORT_ UrlEncoder +{ +public: + /** + * Encodes an input string using a specific encoding scheme. @n + * It encodes all unsafe characters of a string. + * + * @since 2.0 + * + * @return An error code + * @param[in] str An instance of String to encode + * @param[in] encodingScheme The supported encoding scheme + * @param[out] encodedStr The encoded string + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @exception E_UNSUPPORTED_TYPE The specified encoding scheme is not supported. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method is used for encoding. It encodes input string into an + * application/x-www-form-urlencoded format using a specific encoding scheme. This method uses the specified + * encoding scheme to obtain the bytes for unsafe characters. + *@see UrlDecoder + */ + static result Encode(const Tizen::Base::String& str, const Tizen::Base::String& encodingScheme, Tizen::Base::String& encodedStr); + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + UrlEncoder(void); + + /* + * This destructor is intentionally declared as private so that only the platform can delete an instance. + */ + virtual ~UrlEncoder(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %UrlEncoder + */ + UrlEncoder(const UrlEncoder& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @param[in] rhs An instance of %UrlEncoder + */ + UrlEncoder& operator =(const UrlEncoder& rhs); +}; // UrlEncoder + +}}} // Tizen::Base::Utility +#endif // _FBASE_UTIL_URL_ENCODER_H_ diff --git a/inc/FBaseUtilZipEntry.h b/inc/FBaseUtilZipEntry.h new file mode 100644 index 0000000..6ef10e5 --- /dev/null +++ b/inc/FBaseUtilZipEntry.h @@ -0,0 +1,227 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilZipEntry.h + * @brief This is the header file for the %ZipEntry class. + * + * This header file contains the declarations of the %ZipEntry class. + */ + +#ifndef _FBASE_UTIL_ZIP_ENTRY_H_ +#define _FBASE_UTIL_ZIP_ENTRY_H_ + +#include +#include +#include + + + +namespace Tizen { namespace Base { namespace Utility +{ +/** + * @class ZipEntry + * @brief This class provides access to the entries of a zip-archive. + * + * @since 2.0 + * + * The %ZipEntry class is used for accessing the elements of a zip-archive. Each instance of + * %ZipEntry represents a single entry in the zip-archive. + * It also stores the information related to that entry, such as name, compressed size, + * uncompressed size, compression level, and archive name. + * + * For more information on the class features, see Utility. + * + * The following example demonstrates how to use the %ZipEntry class. + * + * @code + * #include + * + * using namespace Tizen::App; + * using namespace Tizen::Base; + * using namespace Tizen::Base::Utility; + * + * void + * MyClass::FileZipSample(void) + * { + * String str; + * int i = 0, count = 0; + * unsigned long size = 0; + * ZipEntry entry; + * + * FileUnzip unzip; + * String dataPath = App::GetInstance()->GetAppDataPath(); + * unzip.Construct(dataPath + L"sample.zip"); + * + * count = unzip.GetEntryCount(); + * + * for (i = 0; i < count; i++) + * { + * // Gets a ZipEntry from the zip-archive + * unzip.GetEntry(i, entry); + * + * // Gets an entry name associated with the ZipEntry + * str = entry.GetName(); + * + * // Gets the name of the zip file which ZipEntry belongs to + * str = entry.GetArchiveName(); + * + * // Gets the compressed size of ZipEntry + * size = entry.GetCompressedSize(); + * } + * + * } + * @endcode + */ +class _OSP_EXPORT_ ZipEntry + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + ZipEntry(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~ZipEntry(void); + + /** + * Gets an entry name associated with a zip entry. @n + * It can be a file or directory name. + * + * @since 2.0 + * + * @return An entry name + * + */ + String GetName(void) const; + + /** + * Gets the compression level associated with a zip entry. + * + * @since 2.0 + * + * @return The compression level associated with a zip entry + * + */ + CompressionLevel GetCompressionLevel(void) const; + + /** + * Checks whether a zip entry is a file or directory. + * + * @since 2.0 + * + * @return @c true if the entry is a directory, @n + * else @c false + */ + bool IsDirectory(void) const; + + /** + * Gets the compressed size of a zip entry. + * + * @since 2.0 + * + * @return The compressed size of a zip entry + */ + unsigned long GetCompressedSize(void) const; + + /** + * Gets the uncompressed size of a zip entry. + * + * @since 2.0 + * + * @return The uncompressed size of a zip entry + */ + unsigned long GetUncompressedSize(void) const; + + /** + * Gets the name of a zip file to which %ZipEntry belongs. + * + * @since 2.0 + * + * @return The name of a zip file + * @remarks This method returns the name of a zip file that is opened + * in the FileUnzipper::Construct() method. + */ + String GetArchiveName(void) const; + + /** + * Compares the specified instance to the calling instance. + * + * @since 2.0 + * + * @return @c true if the specified instance equals the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @remarks The method returns @c true if all the attributes in the instance are same. + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * + * @param[in] entry The instance of the %ZipEntry class to copy from + * @remarks This constructor is hidden. + */ + ZipEntry(const ZipEntry& entry); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * + * @param[in] entry An instance of %ZipEntry + * @remarks This operator is hidden. + */ + ZipEntry& operator =(const ZipEntry& entry); + + void Set(void* unzFile); + + + String __name; + void* __unzFile; + CompressionLevel __compressionLevel; + + friend class _FileUnzipperImpl; + + friend class _ZipEntryImpl; + class _ZipEntryImpl* __pZipEntryImpl; + +}; // ZipEntry + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_ZIP_ENTRY_H_ diff --git a/inc/FBaseUuId.h b/inc/FBaseUuId.h new file mode 100644 index 0000000..445525b --- /dev/null +++ b/inc/FBaseUuId.h @@ -0,0 +1,300 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUuId.h + * @brief This is the header file for the %UuId class. + * + * This header file contains the declarations of the %UuId class. + */ +#ifndef _FBASE_UU_ID_H_ +#define _FBASE_UU_ID_H_ + +#include +#include +#include + +#ifndef ClassId +#define ClassId UUID +#endif + +namespace Tizen { namespace Base +{ +/** + * @class UuId + * @brief This class is the base class of the wrapped UUID types and provides useful operators. + * + * @since 2.0 + * + * The %UuId class is the base class of the wrapped UUID types and provides useful operators. The UUID consists of 32 hexadecimal digits displayed in 5 groups separated by hyphens to form a total of 36 characters (32 digits and 4 hyphens '-'). + * + * It also provides operators for assignment and equality, and methods for parsing, comparing, and generalization. + * + * For more information on the class features, see Base Guide. + * + * The following example demonstrates how to use the %UuId class. + * + * @code + * + * #include + * + * using namespace Tizen::Base; + * + * void + * MyClass::UuIdSamples(void) + * { + * UuId uuid; + * String str(L"A02D0DA1-80A0-4E73-B61F-793263C029EE"); + * String uuidStr_upper + * UuId::Parse(str, uuid); // UuId = A02D0DA1-80A0-4E73-B61F-793263C029EE + * + * String uuidStr = uuid.ToString(); + * uuidStr.ToUpper(uuidStr_upper); + * + * if (str.Equals(uuidStr_upper)) + * { + * // ... + * } + * + * } + * @endcode + */ +class _OSP_EXPORT_ UuId + : public Object +{ +public: + /** + * This is the default constructor for this class. @n + * The %UuId is set to @c 0. + * + * @since 2.0 + */ + UuId(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] uuid An instance of %UuId + */ + UuId(const UuId& uuid); + + /** + * @if OSPDEPREC + * Initializes an instance of %UuId with the value of the specified UUID. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a UUID type is deprecated. + * Instead of using this method, use the UuId(const byte uuid[16]) method. + * @since 2.0 + * + * @param[in] uuid An instance of UUID + * @endif + */ + UuId(const UUID& uuid); + + /** + * Initializes an instance of %UuId with the uuid value. + * + * @since 2.0 + * + * @param[in] uuid A byte array of uuid value + */ + UuId(const byte uuid[16]); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~UuId(void); + + /** + * @if OSPDEPREC + * Checks whether the specified instance of %UuId is equal to the specified UUID. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a UUID type is deprecated. + * @since 2.0 + * + * @return @c true if the UUID and the %UuId instance are equal, @n + * else @c false + * @param[in] uuid1 An instance of UUID + * @param[in] uuid2 An instance of %UuId + * @endif + */ + _OSP_EXPORT_ friend bool operator ==(const UUID& uuid1, const UuId& uuid2); + + /** + * Checks whether the current instance of %UuId is equal to the specified instance of %UuId. + * + * @since 2.0 + * + * @return @c true if the two IDs are equal, @n + * else @c false + * @param[in] uuid An instance of %UuId + */ + bool operator ==(const UuId& uuid) const; + + /** + * @if OSPDEPREC + * Checks whether the specified instance of %UuId is not equal to the specified UUID. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a UUID type is deprecated. + * @since 2.0 + * + * @return @c true if the two IDs are not equal, @n + * else @c false + * @param[in] uuid1 An instance of UUID + * @param[in] uuid2 An instance of %UuId + * @endif + */ + _OSP_EXPORT_ friend bool operator !=(const UUID& uuid1, const UuId& uuid2); + + /** + * Checks whether the current instance of %UuId is not equal to the specified instance of %UuId. + * + * @since 2.0 + * + * @return @c true if the two IDs are not equal, @n + * else @c false + * @param[in] uuid An instance of %UuId + */ + bool operator !=(const UuId& uuid) const; + + /** + * Assigns the value of the specified instance to the current instance of %UuId. + * + * @since 2.0 + * + * @return A reference to the current instance + * @param[in] uuid An instance of %UuId + */ + UuId& operator =(const UuId& uuid); + + /** + * Checks whether the specified instance of Object is equal to the current instance of %UuId. + * + * @since 2.0 + * + * @return @c true if the specified instance of Object is equal to the current instance of %UuId, @n + * else @c false + * @param[in] obj An instance of Object to compare + * @remarks This method can be overridden to support value equality. Furthermore, the method must return the same result as the equality operator. + * @see Tizen::Base::Object::GetHashCode() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance of %UuId. + * + * @since 2.0 + * + * @return The integer value equivalent of the hash value of the current instance of %UuId + * @remarks Two equal instances must return the same hash value. For better performance, + * the used hash function must generate a random distribution for all inputs. @n + * The default implementation of this method returns the value of the current instance. + */ + virtual int GetHashCode(void) const; + + /** + * Gets the string representing the value of the current instance when implemented by a class. + * + * @since 2.0 + * + * @return An instance of the String class with the unicode representation of the value of the current instance @n + * If an error such as E_OUT_OF_MEMORY occurs, an empty string is returned. + */ + String ToString(void) const; + + /** + * @if OSPDEPREC + * Gets the UUID of the %UuId instance. + * + * @brief [Deprecated] + * @deprecated This method is deprecated as a UUID type is deprecated. + * @since 2.0 + * + * @return The UUID + * @endif + */ + UUID ToUUID(void) const; + + /** + * Parses the specified string representing a %UuId value. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string representing the %UuId value + * @param[out] uuid An instance of %UuId + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The string does not contain an %UuId that can be parsed. + * @remarks The format of a string representing a %UuId value is xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (For example, 130DF2EC-8233-4975-B03D-F0AD99E3449D). + */ + static result Parse(const String& str, UuId& uuid); + + /** + * Generates a new %UuId instance with a random value. + * + * @since 2.0 + * + * @return A new %UuId instance + */ + static UuId* GenerateN(void); + + /** + * Get a new invalid %UuId instance. + * + * @since 2.0 + * + * @return A new invalid %UuId instance + */ + static UuId GetInvalidUuId(void); + + /** + * @if OSPDEPREC + * This attribute is pre-defined. Its value is an invalid UUID. + * + * @brief [Deprecated] + * @deprecated This object is provided only for backward compatibility and will be deleted in the near future. + * Use GetInvalidUuId(void) instead of this object. + * @since 2.0 + * @endif + */ + static const UuId INVALID_UUID; + + /** + * A byte array of uuid value. + * + * @since 2.0 + */ + byte uuid[16]; + +private: + static void ConvertToUuId(byte uuid[16]); + + friend class _UuIdImpl; + class _UuIdImpl * __pUuIdImpl; + +}; // UuId + +}} // Tizen::Base + +#endif diff --git a/inc/FGrpBitmapCommon.h b/inc/FGrpBitmapCommon.h new file mode 100644 index 0000000..6076372 --- /dev/null +++ b/inc/FGrpBitmapCommon.h @@ -0,0 +1,85 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FGrpBitmapCommon.h + * @brief This is the header file for the %Bitmap class. + * + * This header file contains the definitions of the enumerations of the %Bitmap class. + */ + +#ifndef _FGRP_BITMAP_COMMON_H_ +#define _FGRP_BITMAP_COMMON_H_ + +namespace Tizen { namespace Graphics +{ + +/** + * @enum BitmapPixelFormat + * + * Defines the bitmap pixel format. + * + * @since 2.0 + */ +enum BitmapPixelFormat +{ + BITMAP_PIXEL_FORMAT_RGB565 = 1, /**< The RGB565 pixel format */ + BITMAP_PIXEL_FORMAT_ARGB8888, /**< The ARGB8888 pixel format */ + BITMAP_PIXEL_FORMAT_R8G8B8A8, /**< The R8G8B8A8 pixel format, the order of the color component is guaranteed by the byte unit */ + BITMAP_PIXEL_FORMAT_MAX, // This enum value is for internal use only. Using this enum value can cause behavioral, security-related, and consistency-related issues in the application. + BITMAP_PIXEL_FORMAT_MIN = 0 // This enum value is for internal use only. Using this enum value can cause behavioral, security-related, and consistency-related issues in the application. +}; + +/** + * @enum BufferScaling + * + * Defines the bitmap buffer scaling type. + * + * @since 2.0 + * + */ +enum BufferScaling +{ + BUFFER_SCALING_NONE = 1, /**< The bitmap buffer is created without scaling */ + BUFFER_SCALING_AUTO, /**< The bitmap buffer is created according to the auto scaling rule */ + BUFFER_SCALING_MAX, // This enum value is for internal use only. Using this enum value can cause behavioral, security-related, and consistency-related issues in the application. + BUFFER_SCALING_MIN = 0 // This enum value is for internal use only. Using this enum value can cause behavioral, security-related, and consistency-related issues in the application. +}; + +/** + * @enum BitmapScalingQuality + * + * Defines the bitmap scaling quality. + * + * @since 2.0 + * + * @remarks Bitmap::Scale() function performs the operation according to the given BitmapScalingQuality value. \n + * Bitmap scaling with BITMAP_SCALING_QUALITY_HIGH provides better results than others, but it takes longer. + * On the other hand, bitmap scaling with BITMAP_SCALING_QUALITY_LOW runs faster than others, but the results are poorer. + * When you scale bitmaps with a masking color then you have to select BITMAP_SCALING_QUALITY_LOW, + * because that algorithm does not harm the masking color (by sampling the pixels instead of interpolating). + */ +enum BitmapScalingQuality +{ + BITMAP_SCALING_QUALITY_LOW, /**< Low-quality but high-performance */ + BITMAP_SCALING_QUALITY_MID, /**< Mid-quality */ + BITMAP_SCALING_QUALITY_HIGH /**< High-quality but low-performance */ +}; + +} } // Tizen::Graphics + +#endif diff --git a/inc/FIo.h b/inc/FIo.h new file mode 100644 index 0000000..10dcef2 --- /dev/null +++ b/inc/FIo.h @@ -0,0 +1,74 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo.h + * @brief This is the header file for the Tizen::Io namespace. + * + * This header file contains the declarations of the Tizen::Io namespace. + */ + +#ifndef _FIO_H_ +#define _FIO_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * @namespace Tizen::Io + * @brief This namespace contains classes and interfaces for performing basic I/O operations. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %Io namespace allows applications to input/output data to/from file systems and other programs and process it. + * Thus, the %Io namespace is an interface between the system and the application. + * The %Io namespace provides classes and methods for managing files, directories, registries, databases, channels, and serial port communication. + * @n + * For more information on the %Io namespace features, see Io Guide. + * + * The following diagram illustrates the relationships between the classes belonging to the %Io namespace. + * @image html io_namespace_classdiagram.png + */ + +namespace Tizen +{ +namespace Io +{ + +} +} + +#endif // _FIO_H_ + diff --git a/inc/FIoChannel.h b/inc/FIoChannel.h new file mode 100644 index 0000000..e5d572a --- /dev/null +++ b/inc/FIoChannel.h @@ -0,0 +1,38 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoChannel.h + * @brief This is the header file for the %Channel class. + * + * This header file contains the declarations of the %Channel class. + */ +#ifndef _FIO_CHANNEL_H_ +#define _FIO_CHANNEL_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + + +} } // Tizen::Io + +#endif //_FIO_CHANNEL_H_ diff --git a/inc/FIoChannelTypes.h b/inc/FIoChannelTypes.h new file mode 100644 index 0000000..2fe5bac --- /dev/null +++ b/inc/FIoChannelTypes.h @@ -0,0 +1,45 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoChannelTypes.h + * @brief This is the header file for the %ChannelType class. + * + * This header file contains the enumerator declarations of the %ChannelType class. + */ +#ifndef _FIO_CHANNEL_TYPES_H_ +#define _FIO_CHANNEL_TYPES_H_ + +namespace Tizen { namespace Io +{ + +/** + * @enum ChannelType + * + * Defines the type of the channel. + * + * @since 2.0 + * + */ +enum ChannelType +{ + CHANNEL_TYPE_CLIENT = 0, /**< The client channel */ + CHANNEL_TYPE_SERVER /**< The server channel */ +}; + +} } // Tizen::Io + +#endif //_FIO_CHANNEL_TYPES_H_ diff --git a/inc/FIoClientChannel.h b/inc/FIoClientChannel.h new file mode 100644 index 0000000..5f00e5a --- /dev/null +++ b/inc/FIoClientChannel.h @@ -0,0 +1,213 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoClientChannel.h + * @brief This is the header file for the %ClientChannel class. + * + * This header file contains the declarations of the %ClientChannel class. + */ +#ifndef _FIO_CLIENT_CHANNEL_H_ +#define _FIO_CLIENT_CHANNEL_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** +* @if OSPDEPREC +* @class ClientChannel +* @brief [Deprecated] This class provides methods for sending a request to another application. +* +* @deprecated This class is deprecated. Instead of using this class, use LocalMessagePort, RemoteMessagePort, and MessagePortManager classes. +* @since 2.0 +* +* @final This class is not intended for extension. +* +* The %ClientChannel class provides methods for sending a request to another application's ServerChannel. To receive a response +* for the request, set the ChannelResponseEventListener interface. The instance of %ClientChannel can be retrieved +* using ClientChannel::GetInstance(). +* @n +* For more information on the class features, see Channel Communication. +* +* The following example demonstrates how to use the %ClientChannel class. +* +* @code +* +* #include +* #include +* +* using namespace Tizen::Base; +* using namespace Tizen::Base::Collection; +* using namespace Tizen::Io; +* using namespace Tizen::App; +* +* class MyAppClass +* : public Tizen::Io::IChannelResponseEventListener +* { +* public: +* result Initialize(void); +* void virtual OnChannelResponseReceivedN(RequestId reqId, Tizen::Io::ClientChannel& clientChannel +* , const Tizen::Base::String& serverChannelId +* , Tizen::Base::Collection::IList* pArgs); +* void GetOnlineFriends(void); +* }; +* +* void +* MyAppClass::Initialize(void) +* { +* // Sets the channel response event listener. +* ClientChannel::GetInstance()->SetChannelResponseEventListener(this); +* } +* +* void +* MyAppClass::OnChannelResponseReceivedN(RequestId reqId, ClientChannel& clientChannel +* , const String& serverChannelId +* , IList* pArgs) +* { +* // Handles the channel response. +* for(int i = 0; i < pArgs->GetCount(); i++) +* { +* AppLog("pData[%d]=%S", i, ((String*)(pArgs->GetAt(i)))->GetPointer()); +* } +* +* // Cleans up the arguments. +* pArgs->RemoveAll(true); +* delete pArgs; +* } +* +* void +* MyAppClass::GetOnlineFriends(void) +* { +* RequestId reqId = 0; +* +* ArrayList* pDataList = new ArrayList(); +* pDataList->Construct(); +* +* String* pData = new String(L"GetList"); +* String* pData2 = new String(L"Friend"); +* +* pDataList->Add(*pData); +* pDataList->Add(*pData2); +* +* ClientChannel::GetInstance()->SendRequest(L"1234567890.ContactSvc", pDataList, reqId); +* +* pDataList->RemoveAll(true); +* delete pDataList; +* } +* +* @endcode +* @endif +*/ + +class _OSP_EXPORT_ ClientChannel + : public Tizen::Base::Object +{ +public: + /** + * Gets the default client channel of the application. + * + * @since 2.0 + * + * @return A pointer to the %ClientChannel instance, @n + * else @c null if it fails + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static ClientChannel* GetInstance(void); + + /** + * Gets the specific client channel of the application. + * + * @since 2.0 + * + * @return A pointer to the %ClientChannel instance, @n + * else @c null if it fails + * @param[in] channelName The channel name + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static ClientChannel* GetInstance(const Tizen::Base::String& channelName); + + /** + * Sets the response event listener. @n + * The listener is called when a response is received. To reset the event listener, @c null must be passed. + * + * @since 2.0 + * + * @param[in] pResponseListener The response event listener + */ + void SetChannelResponseEventListener(IChannelResponseEventListener* pResponseListener); + + /** + * Sends a request to the specific server channel of an application specified by the serverChannelId. + * + * @since 2.0 + * + * @return An error code + * @param[in] serverChannelId The server channel ID which can be either application ID or appicationID.ChannelName + * @param[in] pArgs A pointer to an argument list of type String + * @param[out] reqId The request ID + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The server channel is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result SendRequest(const Tizen::Base::String& serverChannelId, const Tizen::Base::Collection::IList* pArgs, RequestId& reqId); + + +private: + /** + * This default constructor is intentionally declared as private to implement the Singleton semantic. + */ + ClientChannel(void); + + /** + * This destructor is intentionally declared as private to implement the Singleton semantic. + */ + virtual ~ClientChannel(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + ClientChannel(const ClientChannel& clientChannel); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + ClientChannel& operator =(const ClientChannel& clientChannel); + + static void InitSingleton(void); + + static void DestroySingleton(void); + + static ClientChannel* __pClientChannelInstance; + + friend class _ClientChannelImpl; + + class _ClientChannelImpl* __pClientChannelImpl; + +}; // ClientChannel + +} } // Tizen::Io + +#endif //_FIO_CLIENT_CHANNEL_H_ diff --git a/inc/FIoDatabase.h b/inc/FIoDatabase.h new file mode 100644 index 0000000..32670d2 --- /dev/null +++ b/inc/FIoDatabase.h @@ -0,0 +1,845 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDatabase.h + * @brief This is the header file for the %Database class. + * + * This header file contains the declarations of the %Database class. + */ + +#ifndef _FIO_DATABASE_H_ +#define _FIO_DATABASE_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ +class ByteBuffer; +}} + +namespace Tizen { namespace Io +{ + +class DbStatement; +class DbEnumerator; + +/** + * @class Database + * @brief This class provides the basic database and database entry management methods. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Database class provides the basic database and database entry management methods. + * All members of this class are guaranteed to be thread-safe. + * + * For more information on the class features, + * see Database Operations. + * + * @see Tizen::Io::DbStatement + * @see Tizen::Io::DbEnumerator + * + * The following example demonstrates how to use the %Database class. + * + * @code +#include +#include + +using namespace Tizen::Io; +using namespace Tizen::App; + +result +MyTest::UsingDatabase(void) +{ + Database* pDatabase; + DbStatement* pStmt; + DbEnumerator* pEnum; + String dbName; + String sql, sql2, sql3; + String statement; + String stringItem; + result r = E_SUCCESS; + + dbName = App::GetInstance()->GetAppDataPath() + L"sample.db"); + + pDatabase = new Database(); + if (!pDatabase) + { + goto CATCH; + } + + r = pDatabase->Construct(dbName, "a+"); + if (IsFailed(r)) + { + goto CATCH; + } + + AppLog("Create database table:"); + sql.Append(L"CREATE TABLE IF NOT EXISTS myTable1 ( column0 INTEGER PRIMARY KEY, column1 DOUBLE, column2 TEXT )"); + + r = pDatabase->ExecuteSql(sql, true); + if (IsFailed(r)) + { + goto CATCH; + } + + AppLog("Insert rows:"); + pDatabase->BeginTransaction(); + + statement.Append(L"INSERT INTO myTable1 (column0, column1, column2) VALUES (?, ?, ?)"); + pStmt = pDatabase->CreateStatementN(statement); + + stringItem.Append(L"Initial Data"); + for (int i = 0; i < 10; i++) + { + pStmt->BindInt(0, i); + pStmt->BindDouble(1, i * 0.1); + pStmt->BindString(2, stringItem); + + pEnum = pDatabase->ExecuteStatementN(*pStmt); + AppAssert(!pEnum); + } + + pDatabase->CommitTransaction(); + + delete pStmt; + + AppLog("Select query using Database::QueryN() wrapper API:"); + pEnum = pDatabase->QueryN(L"SELECT * FROM myTable1 WHERE column0 < 5"); + if (pEnum) + { + int nRows = 0; + int iVal; + double fVal; + String strVal; + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetIntAt(0, iVal); + if (IsFailed(r)) + { + goto CATCH; + } + + r = pEnum->GetDoubleAt(1, fVal); + if (IsFailed(r)) + { + goto CATCH; + } + + r = pEnum->GetStringAt(2, strVal); + if (IsFailed(r)) + { + goto CATCH; + } + + AppLog("[%d] column0=%d, column1=%f, column2=%ls", nRows++, iVal, fVal, strVal.GetPointer()); + } + delete pEnum; + } + + AppLog("Select query using statement:"); + pStmt = pDatabase->CreateStatementN(L"SELECT * FROM myTable1 WHERE column0 > ? AND column0 < ?"); + r = GetLastResult(); + if (IsFailed(r)) + { + goto CATCH; + } + AppAssert(pStmt); + + r = pStmt->BindInt(0, 3); + if (IsFailed(r)) + { + goto CATCH; + } + + r = pStmt->BindInt(1, 8); + if (IsFailed(r)) + { + goto CATCH; + } + + pEnum = pDatabase->ExecuteStatementN(*pStmt); + r = GetLastResult(); + if (IsFailed(r)) + { + goto CATCH; + } + + if (pEnum) + { + int nRows = 0; + int iVal; + double fVal; + String strVal; + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetIntAt(0, iVal); + if (IsFailed(r)) + { + goto CATCH; + } + + r = pEnum->GetDoubleAt(1, fVal); + if (IsFailed(r)) + { + goto CATCH; + } + + r = pEnum->GetStringAt(2, strVal); + if (IsFailed(r)) + { + goto CATCH; + } + + AppLog("[%d] column0=%d, column1=%f, column2=%ls", nRows++, iVal, fVal, strVal.GetPointer()); + } + delete pEnum; + } + + AppLog("Delete rows:"); + pDatabase->BeginTransaction(); + + sql2.Append(L"DELETE FROM myTable1 WHERE column0 = 1"); + r = pDatabase->ExecuteSql(sql2, true); + + if (r != E_SUCCESS) + { + goto CATCH; + } + + pDatabase->CommitTransaction(); + + AppLog("Update rows:"); + pDatabase->BeginTransaction(); + + sql3.Append(L"UPDATE myTable1 SET column2 = 'Converted Data' WHERE column2 = 'Initial Data'"); + r = pDatabase->ExecuteSql(sql3, true); + + if (r != E_SUCCESS) + { + goto CATCH; + } + + pDatabase->CommitTransaction(); + + // Resource cleanup + delete pDatabase; + pDatabase = null; + + r = Database::Delete(dbName); + if (IsFailed(r)) + { + goto CATCH; + } + + AppLog("Finished successfully..."); + return E_SUCCESS; + +CATCH: + if (pDatabase) + { + delete pDatabase; + pDatabase = null; + } + + if (Database::Exists(dbName)) + { + Database::Delete(dbName); + } + + return r; +} + * @endcode + */ + +class _OSP_EXPORT_ Database + : public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + Database(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Database(void); + + /** + * @if OSPDEPREC + * @{ + * Initializes this instance of %Database with the specified parameters. @n + * This method creates a new database file or opens an existing database file in the read-write mode. + * + * @if OSPCOMPAT + * @brief [Deprecated] [Compatibility] + * @endif + * @deprecated This method is deprecated. Instead of using this method, use Directory::Create(const Tizen::Base::String &dirPath, + * bool createParentDirectories=false) and Database::Construct(const Tizen::Base::String& dbPath, const Tizen::Base::String& openMode). + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] dbPath The path of the database file to open + * @param[in] createIfNotExist Set to @c true to create a database file, @n + * else @c false to open an existing database file + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified @c dbPath is invalid. @n + * - The specified @c dbPath is invalid or the path ends with '/'. @n + * - The directory name path is missing. @n + * - The parent directory does not exist. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_ALREADY_EXIST The specified database file already exists. @n + * Creation of database file has failed because the destination file already exists. @n + * Creation of the database file is attempted if the file does not exist and + * the specified @c createIfNotExist is @c true. + * However, at this moment another thread has been already created the database file + * with the same file path. + * This is a rare case, however, it is possible if a race condition is present between several threads. + * @exception E_FILE_NOT_FOUND The specified database file cannot be found or accessed. + * @exception E_DATABASE Either of the following conditions has occurred: @n + * - The method has failed to open or create a file. @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks To open the database file in the read-only mode, + * use the Database::Construct(const Tizen::Base::String& dbPath, const char* pOpenMode) method + * with "r" as the value for the open mode flag. + * @} + * @endif + */ + result Construct(const Tizen::Base::String& dbPath, bool createIfNotExist); + + /** + * @if OSPDEPREC + * @{ + * Initializes this instance of %Database with the specified parameters. @n + * This method creates a new database file or opens an existing database file in the read-only or the read-write mode. + * + * @if OSPCOMPAT + * @brief [Deprecated] [Compatibility] + * @endif + * @deprecated This method is deprecated. Instead of using this method, use Directory::Create(const Tizen::Base::String &dirPath, + * bool createParentDirectories=false) and Database::Construct(const Tizen::Base::String& dbPath, const Tizen::Base::String& openMode). + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] dbPath The path of the database file to open + * @param[in] openMode An open mode flag @n + * Currently, the following flags can be used in combination with the logical OR operator: @n + * (1) DB_OPEN_READ_ONLY @n + * (2) DB_OPEN_READ_WRITE @n + * (3) DB_OPEN_READ_WRITE | DB_OPEN_CREATE + * @param[in] option This argument is reserved for further use + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified @c dbPath is invalid. @n + * - The specified @c openMode is invalid. @n + * - The specified @c dbPath is invalid or the path ends with '/'. @n + * - The directory name path is missing. @n + * - The parent directory does not exist. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_ALREADY_EXIST The specified database file already exists. + * @exception E_FILE_NOT_FOUND The specified database file cannot be found or accessed. + * @exception E_DATABASE Either of the following conditions has occurred: @n + * - The method has failed to open or create a file. @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @} + * @endif + */ + result Construct(const Tizen::Base::String& dbPath, long openMode, long option); + + /** + * Initializes this instance of %Database with the specified parameters. @n + * This method opens an existing database file or creates a new database file according to the specified file opening mode. + * + * @since 2.0 + * + * @return An error code + * @param[in] dbPath The path of the database file to open or create + * @param[in] pOpenMode The file opening mode @n + * It can be one of the following: + * - r : Open for reading. + * - r+: Open for reading and writing. + * - a+: Open for appending and reading. The database file is created if it does not exist. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified @c dbPath is equal to @c 0 or + * exceeds system limitations. @n + * - The specified @c dbPath ends with '/'. @n + * - The combination of the specified @c pOpenMode is not allowed. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The specified @c dbPath cannot be found. + * @exception E_INVALID_FORMAT The specified @c dbPath is not a database. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. @n + */ + result Construct(const Tizen::Base::String& dbPath, const char* pOpenMode); + + /** + * Initializes this instance of %Database with the specified parameters. @n + * This method opens an existing secure database file or creates a new one according to the specified file opening mode. + * The contents written to the secure database file is automatically encrypted and the contents read from the secure database + * file is automatically decrypted by the platform. @n + * Applications using this method can access the same secure database files that are created by other applications with the + * identical key value in same device. However, the secure files created by this method cannot be accessed in other devices. + * + * @since 2.0 + * + * @return An error code + * @param[in] dbPath The path of the database file to open or create + * @param[in] pOpenMode The file opening mode @n + * It can be one of the following: @n + * - r : Open for reading @n + * - r+: Open for reading and writing @n + * - a+: Open for appending and reading. The database file is created if it does not exist. @n + * @param[in] secretKey A key used to encrypt data of a database file or decrypt a secure database file @n + * If a secure database file is created with a specific key value, + * other applications can access the same secure database file with the identical key value. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified @c dbPath is equal to @c 0 or + * exceeds system limitations. @n + * - The specified @c dbPath ends with '/'. @n + * - The combination of the specified @c pOpenMode is not allowed. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The specified @c dbPath cannot be found. + * @exception E_INVALID_FORMAT The specified @c dbPath is not a database. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. @n + * @exception E_UNSUPPORTED_OPERATION This operation is not supported. + */ + result Construct(const Tizen::Base::String& dbPath, const char* pOpenMode, const Tizen::Base::ByteBuffer& secretKey); + + /** + * Creates a SQL statement for the current database. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return A pointer to the DbStatement instance, @n + * else @c null if an exception occurs + * @param[in] sqlStatement The SQL statement to compile + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c sqlStatement is invalid SQL. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see ExecuteStatementN() + */ + DbStatement* CreateStatementN(const Tizen::Base::String& sqlStatement); + + /** + * Executes a statement in the calling %Database instance. @n + * If an application opens a database file using Database::Construct(const Tizen::Base::String& dbPath, + * const char* pOpenMode, const Tizen::Base::ByteBuffer& secretKey), + * the data set written by INSERT/UPDATE is automatically encrypted by the Tizen platform and + * the data set read by SELECT is also decrypted by itself. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return A pointer to the DbEnumerator instance, @n + * else @c null if an exception occurs, if no result set is generated after the successful execution of the + * SELECT query, or if one of INSERT, UPDATE, and DELETE queries is executed. + * @param[in] dbStatement The DbStatement instance to execute + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c dbStatement includes invalid SQL. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_STORAGE_FULL The disk space or database image is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks If @c dbStatement contains the SELECT query, the Reset() method of the DbEnumerator instance returned + * from this method should be called. The Reset() method should be called before re-binding the dbStatement + * with the bind methods of the DbStatement class. + * This method returns an enumerator if the result set is generated by the SELECT query. + * @c null is returned if no result set is available after the successful execution of the SELECT query. + * Note that, a return value of @c null does not mean that the statement execution has failed. + * The enumerator returned by the SELECT query does not indicate any row before it calls DbEnumerator::MoveNext(). + * The specific error code can be accessed using the GetLastResult() method. + */ + DbEnumerator* ExecuteStatementN(const DbStatement& dbStatement); + + /** + * Executes SQL statement in this %Database instance. @n + * Any SQL statement that does not give a result set can be run using this method; for example, CREATE, INSERT, UPDATE, DELETE. + * The SELECT query cannot be executed using this method. @n + * If an application opens a database file using Database::Construct(const Tizen::Base::String& dbPath, + * const char* pOpenMode, const Tizen::Base::ByteBuffer& key), + * the data set written by INSERT/UPDATE is automatically encrypted by the Tizen platform. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] sqlStatement The SQL statement to execute + * @param[in] option This argument is reserved for further use. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c sqlStatement is invalid SQL. + * @exception E_INVALID_OPERATION The specified @c sqlStatement is a SELECT query. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_STORAGE_FULL The disk space or database image is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks Use QueryN() to execute SELECT query. + * @see QueryN() + */ + result ExecuteSql(const Tizen::Base::String& sqlStatement, bool option); + + /** + * Executes a SELECT query in the calling %Database instance. @n + * If an application opens a database file using Database::Construct(const Tizen::Base::String& dbPath, + * const char* pOpenMode, const Tizen::Base::ByteBuffer& key), + * the data set read by SELECT is automatically decrypted by the Tizen platform. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return A pointer to the %DbEnumerator instance, @n + * else @c null if an exception occurs or if no result set is generated after the successful execution of the SELECT query + * @param[in] sqlStatement The SQL statement to execute + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c sqlStatement is invalid SQL. + * @exception E_INVALID_OPERATION The specified @c sqlStatement is not a SELECT query. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks This method returns an enumerator if the result set is generated by the SELECT query. + * @c null is returned if no result set is available after the successful execution of the SELECT query. + * Note that, a return value of @c null does not mean that the statement execution has failed. + * The enumerator returned by the SELECT query does not indicate any row before it calls + * DbEnumerator::MoveNext(). + * The specific error code can be accessed using the GetLastResult() method. + * @see ExecuteSql() + */ + DbEnumerator* QueryN(const Tizen::Base::String& sqlStatement); + + /** + * Begins a transaction within this %Database instance. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The transaction has already begun. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see CommitTransaction() + * @see RollbackTransaction() + */ + result BeginTransaction(void); + + /** + * Commits a transaction within this %Database instance. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The transaction mode is not activated. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_STORAGE_FULL The disk space or database image is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks Database::CommitTransaction() automatically resets not only all the DbStatement instances + * but also all the DbEnumerator instances obtained from the current %Database instance. + * As a result, the prepared statement of the %DbStatement instances are reset to its initial state, ready to be re-executed, + * and enumerator of the %DbEnumerator instances are reset to the first position. + * Therefore, the user should be careful when the same instance of the %Database class is shared across multiple threads. + * Further, access to the %DbStatement or %DbEnumerator instances resets due to commit operation. This will eventually lead to crash. + * To avoid a crash, the user can use multiple database instances for each thread. + * Sharing of the same database instance across multiple threads is not recommended. + * @see BeginTransaction() + * @see RollbackTransaction() + */ + result CommitTransaction(void); + + /** + * Aborts a running transaction within this %Database instance. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The transaction mode is not activated. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_STORAGE_FULL The disk space or database image is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see BeginTransaction() + * @see CommitTransaction() + */ + result RollbackTransaction(void); + + /** + * Gets the database's filename. + * + * @since 2.0 + * + * @return The filename of this %Database instance + */ + Tizen::Base::String GetName(void) const; + + /** + * Deletes the database file with the specified file name. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] databasePath The path of the database file to delete + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified @c databasePath is invalid. @n + * - The specified @c databasePath parameter contains an invalid path or + * the path ends with '/'. @n + * - The directory name path is missing. @n + * - The parent directory does not exist. @n + * - An I/O security issue. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The specified database file cannot be found. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. @n + * - A system error has occurred. + */ + static result Delete(const Tizen::Base::String& databasePath); + + /** + * Checks whether the database file exists. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return @c true if the database file exists, @n + * else @c false + * @param[in] databasePath The path of the database file to check + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified @c databasePath is invalid. @n + * - The specified @c databasePath parameter contains an invalid path or + * the path ends with '/'. @n + * - The directory name path is missing. @n + * - The parent directory does not exist. @n + * - An I/O security issue. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static bool Exists(const Tizen::Base::String& databasePath); + + /** + * Converts a normal database file to a secure database file. @n + * A secure database file, that is converted by this method, can be shared among applications with the same key value. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For path compatibility, see @ref CompIoPathPage "here". + * For exception compatibility, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] normalDbPath The normal (non-encrypted) database file path + * @param[in] secureDbPath The secure (encrypted) database file path to create + * @param[in] secretKey A key to encrypt normal database file @n + * If the normal database file is converted with a specific key value, + * applications can access the same secure database file with the identical key value. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path is invalid. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The specified @c normalDbPath does not exist. + * @exception E_FILE_ALREADY_EXIST The specified @c secureDbPath already exists. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAlT The database file is malformed. + * @exception E_STORAGE_FULL The disk space or database image is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_UNSUPPORTED_OPERATION This operation is not supported. + */ + static result ConvertToSecureDatabase(const Tizen::Base::String& normalDbPath, const Tizen::Base::String& secureDbPath, + const Tizen::Base::ByteBuffer& secretKey); + + /** + * Gets the last inserted row ID. + * + * @since 2.0 + * + * @return Row ID of the most recent successful insert, @n + * else @c -1 if no successful INSERT operations have ever occurred on + * the current opened database. + * @remarks The row ID is always available as an undeclared column named ROWID, OID, or _ROWID_ + * as long as those names are not also used by explicitly declared columns. + * If the table has a column of type INTEGER PRIMARY KEY then that column is another alias + * for the row ID. @n + * This method returns the row ID of the most recent successful INSERT operation + * for current %Database. + */ + long long GetLastInsertRowId(void) const; + + /** + * @if OSPCOMPAT + * @page CompDatabaseExceptionPage Compatibility for E_DATABASE exception + * @section CompDatabaseExceptionPageIssueSection Issues + * Implementing this method in OSP compatible applications has the following issues: @n + * + * -# E_DATABASE exception includes many errors from underlying database engine. + * -# If database is locked, E_SERVICE_BUSY is returned. + * + * @section CompDatabaseExceptionPageSolutionSection Resolutions + * The issue mentioned above is resolved in Tizen. @n + * + * @par When working in Tizen: + * -# E_DATABASE exception is divided into several exceptions. Refer to exception description of API reference. + * -# E_SERVICE_BUSY is changed to E_OBJECT_LOCKED. + * + * @endif + */ + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + Database(const Database& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * @since 2.0 + */ + Database& operator =(const Database& rhs); + + /** + * The implementation of this method is intentionally blank and declared as private to prohibit implicit conversion. + * + * @since 2.0 + */ + result Construct(const Tizen::Base::String& dbPath, const wchar_t* pOpenMode); + + class _DatabaseImpl* __pDatabaseImpl; + + friend class _DatabaseImpl; + +}; // Database + +}} // Tizen::Io + +#endif //_FIO_DATABASE_H_ + diff --git a/inc/FIoDbEnumerator.h b/inc/FIoDbEnumerator.h new file mode 100644 index 0000000..8cab8cb --- /dev/null +++ b/inc/FIoDbEnumerator.h @@ -0,0 +1,469 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDbEnumerator.h + * @brief This is the header file for the %DbEnumerator class. + * + * This header file contains the declarations of the %DbEnumerator class. + */ + +#ifndef _FIO_DB_ENUMERATOR_H_ +#define _FIO_DB_ENUMERATOR_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +class DateTime; +}} + +namespace Tizen { namespace Io +{ + +/** + * @class DbEnumerator + * @brief This class provides methods for navigating the result set from the SELECT query. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %DbEnumerator class provides methods for navigating the result set from the SELECT query. + * All the members of this class are guaranteed to be thread-safe. + * + * For more information on the class features, see Database Operations. + * + * @see Tizen::Io::Database + */ +class _OSP_EXPORT_ DbEnumerator + : public Tizen::Base::Object + , public Tizen::Io::IDbEnumerator +{ + +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DbEnumerator(void); + + /** + * Moves the enumerator to the next position. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_OUT_OF_RANGE The enumerator has reached out of the result set returned by the SELECT query. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::Io::Database::ExecuteStatementN() + * @see Tizen::Io::Database::QueryN() + * @see Tizen::Io::DbEnumerator::MovePrevious() + * @see Tizen::Io::DbEnumerator::MoveFirst() + * @see Tizen::Io::DbEnumerator::MoveLast() + */ + virtual result MoveNext(void); + + /** + * Moves the enumerator to the previous position. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_OUT_OF_RANGE The enumerator has reached out of the result set returned by the SELECT query. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::Io::Database::ExecuteStatementN() + * @see Tizen::Io::Database::QueryN() + * @see Tizen::Io::DbEnumerator::MoveNext() + * @see Tizen::Io::DbEnumerator::MoveFirst() + * @see Tizen::Io::DbEnumerator::MoveLast() + */ + virtual result MovePrevious(void); + + /** + * Moves the enumerator to the first position. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::Io::Database::ExecuteStatementN() + * @see Tizen::Io::Database::QueryN() + * @see Tizen::Io::DbEnumerator::MoveNext() + * @see Tizen::Io::DbEnumerator::MovePrevious() + * @see Tizen::Io::DbEnumerator::MoveLast() + */ + virtual result MoveFirst(void); + + /** + * Moves the enumerator to the last position. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see Tizen::Io::Database::ExecuteStatementN() + * @see Tizen::Io::Database::QueryN() + * @see Tizen::Io::DbEnumerator::MoveNext() + * @see Tizen::Io::DbEnumerator::MovePrevious() + * @see Tizen::Io::DbEnumerator::MoveFirst() + */ + virtual result MoveLast(void); + + /** + * Resets the calling %DbEnumerator instance back to its initial state. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to reset the enumerator of the result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks After this method is called, if MoveNext() is called the cursor goes to the first position. + */ + virtual result Reset(void); + + /** + * Gets an @c int value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The integer value obtained from the column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetIntAt(int columnIndex, int& value) const; + + /** + * Gets a @c long @c long value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The 64-bit integer value obtained from the column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetInt64At(int columnIndex, long long& value) const; + + /** + * Gets a @c double value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a double + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetDoubleAt(int columnIndex, double& value) const; + + /** + * Gets a @c String value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a String + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_INVALID_ENCODING_RANGE The string conversion has failed due to invalid encoding range, or + * it is possible if the database file is corrupted. + */ + virtual result GetStringAt(int columnIndex, Tizen::Base::String& value) const; + + /** + * Gets a byte array value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The user-provided buffer used to receive the blob data as a stream of type ByteBuffer @n + * The buffer will be filled from the current position and data copy will be continued + * until buffer limitation is reached or no more blob data remains. @n + * The maximum size available is limited to 100 MByte. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_OUT_OF_RANGE The byte buffer operation has failed. + * @exception E_OVERFLOW The specified @c value of the byte buffer is insufficient to save the data. + */ + virtual result GetBlobAt(int columnIndex, Tizen::Base::ByteBuffer& value) const; + + /** + * Gets a blob data from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] buffer The user-provided buffer used to receive the blob data @n + * The maximum size available is limited to 100 MByte. + * @param[out] size The maximum buffer length in bytes + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range, or the specified @c size is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_OVERFLOW The specified @c buffer is insufficient to save the data. + */ + virtual result GetBlobAt(int columnIndex, void* buffer, int size) const; + + /** + * Gets a @c DateTime value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a DateTime instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_INVALID_FORMAT The date is not correctly formatted, or the method is trying to access column of type String. @n + * The date format should be 'mm/dd/yyyy hh:mm:ss'. + * @exception E_OUT_OF_RANGE Either the year(%d), month(%d), day(%d), hour(%d), minute(%d), or second(%d) value is out of range, + * or the method is trying to access a column of type String. + * @remarks Note that the DateTime is constructed inside the method. + */ + virtual result GetDateTimeAt(int columnIndex, Tizen::Base::DateTime& value) const; + + /** + * Gets the number of columns for this enumerator. + * + * @since 2.0 + * + * @return The number of columns in the calling enumerator, @n + * else @c -1 if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @remarks The method must be called after MoveNext(), MoveFirst(), or MoveLast(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetColumnCount(void) const; + + /** + * Gets the type of the column indicated by the specified index. + * + * @since 2.0 + * + * @return The type of column, @n + * else DB_COLUMNTYPE_UNDEFINED if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @remarks The method must be called after MoveNext(), MoveFirst(), or MoveLast(). @n + * Currently, DB_COLUMNTYPE_INT is returned for a 64-bit integer. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual DbColumnType GetColumnType(int columnIndex) const; + + /** + * Gets the name of the column indicated by the specified index. + * + * @since 2.0 + * + * @return The name of the column, @n + * else an empty string if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_INVALID_ENCODING_RANGE The string conversion has failed due to invalid encoding range, or + * it is possible if the database file is corrupted. + * @remarks The method must be called after MoveNext(), MoveFirst(), or MoveLast(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetColumnName(int columnIndex) const; + + /** + * Gets the size of data in bytes. + * + * @since 2.0 + * + * @return The size of the data in bytes, @n + * else @c -1 if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * - The Database or DbStatement instance associated with this instance is deleted. + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @remarks The method must be called after MoveNext(), MoveFirst(), or MoveLast(). @n + * If the destination column is of type String, this method returns the @c byte length excluding the @c null terminator character. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetColumnSize(int columnIndex) const; + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + DbEnumerator(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + DbEnumerator(const DbEnumerator& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * @since 2.0 + */ + DbEnumerator& operator =(const DbEnumerator& rhs); + + class _DbEnumeratorImpl* __pDbEnumeratorImpl; + + friend class _DbEnumeratorImpl; + +}; // DbEnumerator + +}} // Tizen::Io + +#endif // _FIO_DB_ENUMERATOR_H_ + diff --git a/inc/FIoDbStatement.h b/inc/FIoDbStatement.h new file mode 100644 index 0000000..2d0fee6 --- /dev/null +++ b/inc/FIoDbStatement.h @@ -0,0 +1,303 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoDbStatement.h + * @brief This is the header file for the %DbStatement class. + * + * This header file contains the declarations of the %DbStatement class. + */ + +#ifndef _FIO_DB_STATEMENT_H_ +#define _FIO_DB_STATEMENT_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** + * @class DbStatement + * @brief This class provides a method for evaluating pre-compiled statements. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %DbStatement class provides a method for evaluating pre-compiled statements. + * All members of this class are guaranteed to be thread-safe. + * + * For more information on the class features, see Database Operations. + */ +class _OSP_EXPORT_ DbStatement + : public Tizen::Base::Object +{ + +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DbStatement(void); + + /** + * Binds an integer value to the statement parameter. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is bound + * @param[out] value The integer value to bind + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The instance has not been properly constructed, + * or the instance is finalized. + * @exception E_INVALID_ARG The specified @c columnIndex is invalid. + * @exception E_INVALID_OPERATION This method has failed to bind the parameter because the database state has not been reset + * after executing the SELECT query by using Database::ExecuteStatementN() or DbEnumerator::MoveNext(). + * In this case DbEnumerator::Reset() should be invoked before calling this method. + */ + result BindInt(int columnIndex, int value); + + /** + * Binds a @c long @c long value to the statement parameter. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is bound + * @param[out] value The 64-bit integer value to bind + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The instance has not been properly constructed, + * or the instance is finalized. + * @exception E_INVALID_ARG The specified @c columnIndex is invalid. + * @exception E_INVALID_OPERATION This method has failed to bind the parameter because the database state has not been reset + * after executing the SELECT query by using Database::ExecuteStatementN() or DbEnumerator::MoveNext(). + * In this case DbEnumerator::Reset() should be invoked before calling this method. + */ + result BindInt64(int columnIndex, long long value); + + /** + * Binds a @c double value to the statement parameter. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is bound + * @param[out] value The @c double value to bind + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The instance has not been properly constructed, + * or the instance is finalized. + * @exception E_INVALID_ARG The specified @c columnIndex is invalid. + * @exception E_INVALID_OPERATION This method has failed to bind the parameter because the database state has not been reset + * after executing the SELECT query by using Database::ExecuteStatementN() or DbEnumerator::MoveNext(). + * In this case DbEnumerator::Reset() should be invoked before calling this method. + */ + result BindDouble(int columnIndex, double value); + + /** + * Binds a String value to the statement parameter. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is bound + * @param[out] value The string value to bind + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The instance has not been properly constructed, + * or the instance is finalized. + * @exception E_INVALID_ARG The specified @c value exceeds size limit. + * @exception E_INVALID_OPERATION This method has failed to bind the parameter because the database state has not been reset + * after executing the SELECT query by using Database::ExecuteStatementN() or DbEnumerator::MoveNext(). + * In this case DbEnumerator::Reset() should be invoked before calling this method. + */ + result BindString(int columnIndex, const Tizen::Base::String& value); + + /** + * Binds a value of type ByteBuffer to the statement parameter. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is bound + * @param[out] value The blob value to bind @n + * The maximum available size is limited to 100 MBytes. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The instance has not been properly constructed, + * or the instance is finalized. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c columnIndex is invalid. @n + * - The size of byte buffer is less than @c 0 or has @c null data. @n + * - The specified @c value exceeds size limit. + * @exception E_INVALID_OPERATION This method has failed to bind the parameter because the database state has not been reset + * after executing the SELECT query by using Database::ExecuteStatementN() or DbEnumerator::MoveNext(). + * In this case DbEnumerator::Reset() should be invoked before calling this method. + * @remarks The bound @c byte array size is from the current position of byte buffer to the limit. + */ + result BindBlob(int columnIndex, const Tizen::Base::ByteBuffer& value); + + /** + * Binds the raw blob data to the statement parameter. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is bound + * @param[in] buffer A pointer to the buffer where blob data is located @n + * The maximum available size is limited to 100 MBytes. + * @param[in] size The blob data length in bytes + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The instance has not been properly constructed, + * or the instance is finalized. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c columnIndex is invalid. @n + * - The specified @c size is less than @c 0. @n + * - The pointer to the buffer is @c null. @n + * - The specified @c buffer exceeds size limit. + * @exception E_INVALID_OPERATION This method has failed to bind the parameter because the database state has not been reset + * after executing the SELECT query by using Database::ExecuteStatementN() or DbEnumerator::MoveNext(). + * In this case DbEnumerator::Reset() should be invoked before calling this method. + */ + result BindBlob(int columnIndex, const void* buffer, int size); + + /** + * Binds a DateTime value to the statement parameter. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is bound + * @param[out] value The date value to bind + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The instance has not been properly constructed, + * or the instance is finalized. + * @exception E_INVALID_ARG The specified @c columnIndex is invalid, or + * the value is less than @c or a @c null pointer. + * @exception E_INVALID_OPERATION This method has failed to bind the parameter because the database state has not been reset + * after executing the SELECT query by using Database::ExecuteStatementN() or DbEnumerator::MoveNext(). + * In this case DbEnumerator::Reset() should be invoked before calling this method. + */ + result BindDateTime(int columnIndex, const Tizen::Base::DateTime& value); + + /** + * Binds a @c null value to the statement parameter. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompDatabaseExceptionPage "here". + * @endif + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is bound + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The instance has not been properly constructed, + * or the instance is finalized. + * @exception E_INVALID_ARG The specified @c columnIndex is invalid. + * @exception E_INVALID_OPERATION This method has failed to bind the parameter because the database state has not been reset + * after executing the SELECT query by using Database::ExecuteStatementN() or DbEnumerator::MoveNext(). + * In this case DbEnumerator::Reset() should be invoked before calling this method. + */ + result BindNull(int columnIndex); + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + DbStatement(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + DbStatement(const DbStatement& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + DbStatement& operator =(const DbStatement& rhs); + + class _DbStatementImpl* __pDbStatementImpl; + + friend class _DbStatementImpl; + +}; // DbStatement + +}} // Tizen::Io + +#endif //_FIO_DB_STATEMENT_H_ + diff --git a/inc/FIoDbTypes.h b/inc/FIoDbTypes.h new file mode 100644 index 0000000..b601764 --- /dev/null +++ b/inc/FIoDbTypes.h @@ -0,0 +1,56 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDbTypes.h + * @brief This is the header file for the %DbTypes class. + * + * This header file contains enum declarations of the @e %DbTypes class. + */ + +#ifndef _FIO_DB_TYPES_H_ +#define _FIO_DB_TYPES_H_ + +namespace Tizen { namespace Io +{ + +#define DB_OPEN_READ_ONLY (0x00000001L) +#define DB_OPEN_READ_WRITE (0x00000002L) +#define DB_OPEN_CREATE (0x00000004L) + +/** + * @enum DbColumnType + * + * Defines types of column. + * + * @since 2.0 + */ +enum DbColumnType +{ + DB_COLUMNTYPE_INT = 0, /**< The column type is 4bytes integer */ + DB_COLUMNTYPE_INT64, /**< The column type is 8bytes integer */ + DB_COLUMNTYPE_DOUBLE, /**< The column type is double */ + DB_COLUMNTYPE_TEXT, /**< The column type is text */ + DB_COLUMNTYPE_BLOB, /**< The column type is blob */ + DB_COLUMNTYPE_NULL, /**< The column type is null */ + DB_COLUMNTYPE_UNDEFINED +}; + +}} // Tizen::Io + +#endif //_FIO_DB_TYPES_H_ + diff --git a/inc/FIoDirEntry.h b/inc/FIoDirEntry.h new file mode 100644 index 0000000..29d8d61 --- /dev/null +++ b/inc/FIoDirEntry.h @@ -0,0 +1,278 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDirEntry.h + * @brief This is the header file for the %DirEntry class. + * + * This header file contains the declarations of the %DirEntry class. + */ + +#ifndef _FIO_DIR_ENTRY_H_ +#define _FIO_DIR_ENTRY_H_ + +#include + +namespace Tizen { namespace Base +{ +class String; +class DateTime; +}} + +namespace Tizen { namespace Io +{ + +/** + * @class DirEntry + * @brief This class stores the information about each directory entry. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %DirEntry class stores the information about each directory entry. + * + * For more information on the class features, + * see Io Guide. + * + * @see Tizen::Io::Directory + * @see Tizen::Io::File + * + * The following example demonstrates how to use the %DirEntry class. + * + * @code + +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Io; + +int main(void) +{ + String dirName(L"test"); + Directory dir; + DirEnumerator *pDirEnum = null; + String name; + Tizen::Base::DateTime dt; + result r = E_SUCCESS; + + // Open the directory + r = dir.Construct(App::GetInstance()->GetAppDataPath() + dirName); + if (IsFailed(r)) + { + goto CATCH; + } + + // Read all the directory entries + pDirEnum = dir.ReadN(); + if (!pDirEnum) + { + goto CATCH; + } + + // Loop through all the directory entries + while (pDirEnum->MoveNext() == E_SUCCESS) + { + DirEntry dirEntry = pDirEnum->GetCurrentDirEntry(); + + // Get several properties of each directory entry. + name = dirEntry.GetName(); + + name += L": size="; + name += Long((long) dirEntry.GetFileSize()).ToString(); + + if (dirEntry.IsDirectory()) + { + name += L", [directory]"; + } + if (dirEntry.IsReadOnly()) + { + name += L", [read-only]"; + } + if (dirEntry.IsHidden()) + { + name += L", [hidden]"; + } + + dt = dirEntry.GetDateTime(); + + name += L", year="; + name += dt.GetYear(); + + name += L", month="; + name += dt.GetMonth(); + + name += L", day="; + name += dt.GetDay(); + + name += L", hour="; + name += dt.GetHour(); + + name += L", min="; + name += dt.GetMinute(); + + name += L", second="; + name += dt.GetSecond(); + + // Print out message... + } + + // Delete the enumerator + delete pDirEnum; + + AppLog("Succeeded"); + + // The opened directory is closed automatically when the destructor of Directory class is invoked + return 0; + +CATCH: + if (pDirEnum) + { + delete pDirEnum; + } + AppLog("Failed..."); + return -1; +} + * @endcode + */ +class _OSP_EXPORT_ DirEntry + : public Tizen::Base::Object +{ + +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DirEntry(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %DirEntry + */ + DirEntry(const DirEntry& rhs); + + /** + * Assigns the value of the specified instance to the current instance of %DirEntry. + * + * @since 2.0 + * + * @return A reference to the calling instance + * @param[in] rhs An instance of %DirEntry + */ + DirEntry& operator =(const DirEntry& rhs); + + /** + * Compares the specified instance of Object to the calling instance of %DirEntry. + * + * @since 2.0 + * + * @return @c true if the values of the specified instance equals the values of the current instance, @n + * else @c false + * @param[in] object The object to compare with the current instance + */ + virtual bool Equals(const Object& object) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Gets the name of this directory entry. + * + * @since 2.0 + * + * @return The name of this directory entry + */ + const Tizen::Base::String GetName(void) const; + + /** + * Gets the file size of this directory entry. + * + * @since 2.0 + * + * @return The file size of this directory entry + */ + unsigned long GetFileSize(void) const; + + /** + * Checks whether the current %DirEntry instance is a directory. + * + * @since 2.0 + * + * @return @c true if it is a directory, @n + * else @c false + */ + bool IsDirectory(void) const; + + /** + * Checks whether a file has a hidden attribute. + * + * @since 2.0 + * + * @return @c true if the file has a hidden attribute, @n + * else @c false + */ + bool IsHidden(void) const; + + /** + * Checks whether a file has a read-only attribute. + * + * @since 2.0 + * + * @return @c true if the file has a read-only attribute, @n + * else @c false + */ + bool IsReadOnly(void) const; + + /** + * Gets the date and time of creation of the directory entry. + * + * @since 2.0 + * + * @return The date and time of creation + */ + Tizen::Base::DateTime GetDateTime(void) const; + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + DirEntry(void); + + class _DirEntryImpl* __pDirEntryImpl; + + friend class _DirEntryImpl; + +}; // DirEntry + +}} // Tizen::Io + +#endif // _FIO_DIR_ENTRY_H_ + diff --git a/inc/FIoDirEnumerator.h b/inc/FIoDirEnumerator.h new file mode 100644 index 0000000..2121387 --- /dev/null +++ b/inc/FIoDirEnumerator.h @@ -0,0 +1,226 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDirEnumerator.h + * @brief This is the header file for the %DirEnumerator class. + * + * This header file contains the declarations of the %DirEnumerator class. + */ + +#ifndef _FIO_DIR_ENUMERATOR_H_ +#define _FIO_DIR_ENUMERATOR_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +class DirEntry; + +/** + * @class DirEnumerator + * @brief This class provides methods to access the collection of a specific directory entry list. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %DirEnumerator class provides methods to access the collection of a specific directory entry list. + * Generally, %DirEnumerator is instantiated by the Directory::ReadN() method, + * and used to get the %DirEntry instances that have information pertaining to the directory. + * + * For more information on the class features, + * see Io Guide. + * + * @see Tizen::Io::Directory + * @see Tizen::Io::DirEntry + * @see Tizen::Io::File + * + * The following example demonstrates how to use the %DirEnumerator class. + * + * @code +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Io; + +int main(void) +{ + String dirName(L"data/test"); + Directory dir; + DirEnumerator *pDirEnum = null; + result r = E_SUCCESS; + + // Open the directory + r = dir.Construct(Tizen::App::App::GetInstance()->GetAppRootPath() + dirName); + if (IsFailed(r)) + { + goto CATCH; + } + + // Read all the directory entries + pDirEnum = dir.ReadN(); + if (!pDirEnum) + { + goto CATCH; + } + + // Loop through all the directory entries + while (pDirEnum->MoveNext() == E_SUCCESS) + { + DirEntry dirEntry = pDirEnum->GetCurrentDirEntry(); + + // Do something... + } + + // Delete the enumerator + delete pDirEnum; + + AppLog("Succeeded"); + + // The opened directory is closed automatically when the destructor of the Directory class is invoked. + return 0; + +CATCH: + if (pDirEnum) + { + delete pDirEnum; + } + AppLog("Failed..."); + return -1; +} + * @endcode + * + */ +class _OSP_EXPORT_ DirEnumerator + : public Tizen::Base::Object + , public Tizen::Base::Collection::IEnumerator +{ + +public: + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DirEnumerator(void); + + /** + * Gets the value of the DirEntry instance in the currently accessed directory. + * + * @since 2.0 + * + * @return A reference to the DirEntry instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The current position of the collection is not valid. + * @remarks Use the MoveNext() method to get information from another file or directory to the currently accessed directory. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + DirEntry GetCurrentDirEntry(void) const; + + /** + * Gets the pointer to the object at the current position of a directory entry collection. + * + * @since 2.0 + * + * @return A pointer to the DirEntry instance, @n + * else @c null if the current position of the collection is invalid + * @remarks Use the MoveNext() method to get information of another file or directory in the currently accessed directory. + */ + virtual Tizen::Base::Object* GetCurrent(void) const; + + /** + * Moves the current position of the collection to the next position in the currently accessed directory. @n + * When %DirEnumerator is instantiated, its initial position is set to @c -1. @n + * Therefore, calling the GetCurrentDirEntry() method without a call to MoveNext() throws an E_INVALID_STATE exception, + * and returns a reference to an empty DirEntry instance. @n + * Similarly, calling the GetCurrent() method without a call to MoveNext() returns a @c null pointer to indicate an error condition. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds + * system limitations. @n + * - The specified path is invalid.@n + * - The file handle is invalid (either the file is closed by + * another method, or the memory is corrupted). + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_END_OF_FILE There are no more directory entries to read. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + virtual result MoveNext(void); + + /** + * Resets the current position of the collection to @c -1. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The file handle is invalid (either the file is closed by another method, or the memory is corrupted). + */ + virtual result Reset(void); + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + * + * @since 2.0 + */ + DirEnumerator(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + DirEnumerator(const DirEnumerator& source); + + /** + * This is the copy constructor for this class. + * + * @since 2.0 + */ + DirEnumerator(const Tizen::Base::String& dirPath); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + DirEnumerator& operator =(const DirEnumerator& source); + + DirEntry* __pCurDirEntry; + class _DirEnumeratorImpl* __pDirEnumeratorImpl; + + friend class _DirEnumeratorImpl; + +}; // DirEnumerator + +}} // Tizen::Io + +#endif // _FIO_DIR_ENUMERATOR_H_ + diff --git a/inc/FIoDirectory.h b/inc/FIoDirectory.h new file mode 100644 index 0000000..cfafe1a --- /dev/null +++ b/inc/FIoDirectory.h @@ -0,0 +1,321 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDirectory.h + * @brief This is the header file for the %Directory class. + * + * This header file contains the declarations of the %Directory class. + */ + +#ifndef _FIO_DIRECTORY_H_ +#define _FIO_DIRECTORY_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** + * @class Directory + * @brief This class provides methods to operate on directories. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Directory class provides methods to operate on directories. + * + * For more information on the class features, + * see Io Guide. + * + * @see Tizen::Io::DirEntry + * @see Tizen::Io::File + * + * The following example demonstrates how to use the %Directory class. + * + * @code +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Io; +using namespace Tizen::App; + +int main(void) +{ + String dirName; + String modifyName; + Directory* pDir; + DirEnumerator* pDirEnum; + result r = E_SUCCESS; + + dirName = App::GetInstance()->GetAppDataPath() + L"test"; + modifyName = App::GetInstance()->GetAppDataPath() + L"test2"; + + //------------------------------------------------ + // Directory entry traversal example + //------------------------------------------------ + pDir = new Directory; // Allocates the %Directory instance + + // Open the directory + r = pDir->Construct(dirName); + if (IsFailed(r)) + { + goto CATCH; + } + + // Reads all the directory entries + pDirEnum = pDir->ReadN(); + if (!pDirEnum) + { + goto CATCH; + } + + // Loops through all the directory entries + while (pDirEnum->MoveNext() == E_SUCCESS) + { + DirEntry entry = pDirEnum->GetCurrentDirEntry(); + + // Do something... + } + + // Releases the %Directory instance. + // The opened directory is closed automatically when the destructor of the %Directory class is invoked. + delete pDir; + pDir = null; + + //------------------------------------------------ + // Renames the directory example + //------------------------------------------------ + r = Directory::Rename(dirName, modifyName); + if (IsFailed(r)) + { + goto CATCH; + } + AppLog("Succeeded!"); + return 0; + +CATCH: + if (pDir) + { + delete pDir; + } + AppLog("Failed..."); + return -1; +} + * @endcode + * + */ + +class _OSP_EXPORT_ Directory + : public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @remarks After creating an instance of this class, the Construct() method must be called explicitly to initialize this instance. + */ + Directory(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Directory(void); + + /** + * Initializes this instance of %Directory with the specified parameter. @n + * The Construct() method safely opens an existing directory using the specified directory name. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] dirPath The path to the directory to open + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path contains prohibited character(s). @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + result Construct(const Tizen::Base::String& dirPath); + + /** + * Reads all the directory entries from the current directory and then returns a DirEnumerator instance that is used to traverse each directory entry. + * + * @since 2.0 + * + * @return A pointer to the DirEnumerator object that provides a way to access the collection of a directory entry list, @n + * else @c null if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks The returned enumeration objects should be released by the caller. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + DirEnumerator* ReadN(void); + + /** + * Creates a new directory. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] dirPath The path at which the directory is created + * @param[in] createParentDirectories Set to @c true if the non-existing parent directories are created automatically + * up to the destination, @n + * else @c false if an absent parent directory causes an exception + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_ALREADY_EXIST The specified file already exists. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + static result Create(const Tizen::Base::String& dirPath, bool createParentDirectories = false); + + /** + * Deletes the directory specified by the path. @n + * When @c recursive is set to be @c true, it removes all the subdirectories and their contents. @n + * When @c false, this method removes the directory only if it is empty. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] dirPath The path of the directory to remove + * @param[in] recursive Set to @c true to remove the sub-directories recursively, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds + * system limitations. @n + * - The specified @c dirPath is not directory path. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The specified @c dirPath cannot be found. + * @exception E_FILE_ALREADY_EXIST The specified directory already exists. + * @exception E_MAX_EXCEEDED The number of opened directories has exceeded the maximum limit. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + static result Remove(const Tizen::Base::String& dirPath, bool recursive = false); + + /** + * Renames the specified directory to the specified name. @n + * This method is static. @n + * This method does not create parent directories automatically. For example, @b "/CurrentDir" cannot be moved to + * @b "/NewDir/SubDir" if @b "/NewDir" does not already exist. An E_FILE_NOT_FOUND exception is thrown. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] orgDirPath The original directory path + * @param[in] newDirPath The new directory path + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified path is @c 0 or exceeds system limitations. @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_FILE_ALREADY_EXIST The specified file already exists. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + static result Rename(const Tizen::Base::String& orgDirPath, const Tizen::Base::String& newDirPath); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + Directory(const Directory& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + Directory& operator =(const Directory& rhs); + + class _DirectoryImpl* __pDirectoryImpl; + + friend class _DirectoryImpl; + +}; // Directory + +}} // Tizen::Io + +#endif // _FIO_DIRECTORY_H_ + diff --git a/inc/FIoFile.h b/inc/FIoFile.h new file mode 100644 index 0000000..d4297b0 --- /dev/null +++ b/inc/FIoFile.h @@ -0,0 +1,908 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoFile.h + * @brief This is the header file for the %File class. + * + * This header file contains the declarations of the %File class. + */ + +#ifndef _FIO_FILE_H_ +#define _FIO_FILE_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** + * @enum FileSeekPosition + * + * Defines the file seek position. + * + * @since 2.0 + */ +enum FileSeekPosition +{ + FILESEEKPOSITION_BEGIN, /**GetAppRootPath() + L"data" + * or Tizen::App::App::GetInstance()->GetAppDataPath(). + * - res - Used to read resource files that are delivered with the application package (read-only permission) @n + * To access this directory, use Tizen::App::App::GetInstance()->GetAppRootPath() + L"res" + * or Tizen::App::App::GetInstance()->GetAppResourcePath(). + * - shared - Used to share data and resource files with other applications @n + * There are data and res directories under the shared directory. + * Use Tizen::App::App::GetInstance()->GetAppRootPath() + L"shared" to access its own shared directory and + * use Tizen::App::AppManager::GetAppSharedPath() to access other application's shared directory. @n + * + * For more information on the path, + * see I/O Overview. + * + * For more information on class features, + * see Io Guide. + * + * The following example demonstrates how to use the %File class. + * + * @code + +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Io; +using namespace Tizen::App; + +int main(void) +{ + String fileName(L"test.txt"); + File file; + char buffer[10]; + char buffer2[5]; + int i; + int readCnt; + result r = E_SUCCESS; + + // Creates file + r = file.Construct(App::GetInstance()->GetAppDataPath() + fileName, "w+"); + if (IsFailed(r)) + { + goto CATCH; + } + + for (i = 0; i < 10; i++) + { + buffer[i] = (char) i; + } + + // Writes to the file + r = file.Write(buffer, 10); + if (IsFailed(r)) + { + goto CATCH; + } + + // Repositions the file pointer + r = file.Seek(FILESEEKPOSITION_CURRENT, -5); + if (IsFailed(r)) + { + goto CATCH; + } + + // Reads + readCnt = file.Read(buffer2, 5); + r = GetLastResult(); + if (IsFailed(r)) + { + goto CATCH; + } + if (readCnt != 5) + { + goto CATCH; + } + + // Checks the correctness of the read data + for (i = 0; i < readCnt; i++) + { + char m, n; + m = buffer2[i]; + n = buffer[i + 5]; + if (m != n) + { + goto CATCH; + } + } + AppLog("Succeeded!"); + return 0; + +CATCH: + AppLog("Failed..."); + return -1; +} + + * @endcode + */ + +/** + * @if OSPCOMPAT + * @page CompIoPathPage Compatibility for path + * @section CompIoPathPageIssueSection Issues + * The path argument of this method in OSP compatible applications has the following issue: @n + * + * -# The path should begin with an allowed path prefix such as '/Home', '/Home/Share', '/Res', '/Share/[@e appid]', + * '/Media', and '/Storagecard/Media'. + * + * @section CompIoPathPageSolutionSection Resolutions + * + * - There are no specific allowed path prefixes in Tizen. + * + * @par When working in Tizen: + * - For accessing its own data directory, use Tizen::App::App::GetInstance()->GetAppRootPath() + L"data" @n + * or Tizen::App::App::GetInstance()->GetAppDataPath(). + * - For accessing its own resource directory, use Tizen::App::App::GetInstance()->GetAppRootPath() + L"res" @n + * or Tizen::App::App::GetInstance()->GetAppResourcePath(). + * - For accessing its own shared directory, use Tizen::App::App::GetInstance()->GetAppRootPath() + L"shared/data". + * - For accessing the media directory, use Tizen::System::Environment::GetMediaPath(). + * - For accessing the external storage, use Tizen::System::Environment::GetExternalStoragePath(). + * + * For more information on the path, + * see I/O Overview. + * @endif + */ + +class _OSP_EXPORT_ File + : public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + File(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~File(void); + + /** + * @if OSPDEPREC + * @{ + * Initializes this instance of %File with the specified parameters. @n + * This method opens an existing file or creates a new one according to the specified file opening mode. + * + * @if OSPCOMPAT + * @brief [Deprecated] [Compatibility] + * @endif + * @deprecated This method is deprecated. Instead of using this method, use Directory::Create(const Tizen::Base::String &dirPath, + * bool createParentDirectories=false) and File::Construct(const Tizen::Base::String& filePath, const Tizen::Base::String& openMode). + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] filePath The path of the file to open or create + * @param[in] openMode The file opening mode @n + * It can be one of the following: + * - r : Open for reading. + * - r+: Open for reading and writing. + * - w : Open for writing. The file is created if it does not exist, + * otherwise it is truncated to zero length. + * - w+: Open for writing and reading. The file is created if it does not exist, + * otherwise it is truncated to zero length. + * - a : Open for appending. The file is created if it does not exist. + * - a+: Open for appending and reading. The file is created if it does not exist. + * @param[in] createParentDirectories Set to @c true to automatically create non-existent parent directories up to destination, @n + * else @c false @n + * This parameter is useful only if the specified @c openMode allows creation of an absent + * file. For example, the following modes: "w", "w+", "a" and "a+". @n + * If the value of @c openMode is not any one of these, E_INVALID_ARG exception is thrown. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The combination of the specified @c openMode is not allowed. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. @n + * For example, opening a read-only file in the write mode such as "w" or "a". + * @exception E_FILE_NOT_FOUND The specified @c filePath cannot be found. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks The following file opening mode strings are recognized by this method: "w+", "wb+", "w+b", "w", "wb", "a+", + * "ab+", "a+b", "a", "ab", "r+", "rb+", "r+b", "r", "rb". @n + * Other strings lead to E_INVALID_ARG. However, "b"(binary) open mode is ignored internally. + * @} + * @endif + */ + result Construct(const Tizen::Base::String& filePath, const Tizen::Base::String& openMode, bool createParentDirectories); + + /** + * Initializes this instance of %File with the specified parameters. @n + * This method opens an existing file or creates a new one according to the specified file opening mode. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] filePath The path of the file to open or create + * @param[in] openMode The file opening mode @n + * It can be one of the following: + * - r : Open for reading. + * - r+: Open for reading and writing. + * - w : Open for writing. The file is created if it does not exist, + * otherwise it is truncated to zero length. + * - w+: Open for writing and reading. The file is created if it does not exist, + * otherwise it is truncated to zero length. + * - a : Open for appending. The file is created if it does not exist. + * - a+: Open for appending and reading. The file is created if it does not exist. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The combination of the specified @c openMode is not allowed. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. @n + * For example, opening a read-only file in the write mode such as "w" or "a". + * @exception E_FILE_NOT_FOUND The specified @c filePath cannot be found. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The following file opening mode strings are recognized by this method: "w+", "wb+", "w+b", "w", "wb", "a+", + * "ab+", "a+b", "a", "ab", "r+", "rb+", "r+b", "r", "rb". @n + * Other strings lead to E_INVALID_ARG. However, "b"(binary) open mode is ignored internally. + */ + result Construct(const Tizen::Base::String& filePath, const Tizen::Base::String& openMode); + + /** + * Initializes this instance of %File with the specified parameters. @n + * This method opens an existing file or creates a new one according to the specified file opening mode. + * + * @since 2.0 + * + * @return An error code + * @param[in] filePath The path of the file to open or create + * @param[in] pOpenMode The file opening mode @n + * It can be one of the following: + * - r : Open for reading. + * - r+: Open for reading and writing. + * - w : Open for writing. The file is created if it does not exist, + * otherwise it is truncated to zero length. + * - w+: Open for writing and reading. The file is created if it does not exist, + * otherwise it is truncated to zero length. + * - a : Open for appending. The file is created if it does not exist. + * - a+: Open for appending and reading. The file is created if it does not exist. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The combination of the specified @c pOpenMode is not allowed. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. @n + * For example, opening a read-only file in the write mode such as "w" or "a". + * @exception E_FILE_NOT_FOUND The specified @c filePath cannot be found. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The following file opening mode strings are recognized by this method: "w+", "wb+", "w+b", "w", "wb", "a+", + * "ab+", "a+b", "a", "ab", "r+", "rb+", "r+b", "r", "rb". @n + * Other strings lead to E_INVALID_ARG. However, "b"(binary) open mode is ignored internally. + */ + result Construct(const Tizen::Base::String& filePath, const char* pOpenMode); + + /** + * Initializes this instance of %File with the specified parameters. @n + * This method opens an existing secure file or creates a new one according to the specified file opening mode. @n + * The contents written to the secure file is automatically encrypted and the contents read from the secure file is automatically + * decrypted by the platform. @n + * Applications using this method can access the secure files that are created by other applications with the identical key value + * in same device. However, the secure files created by this method cannot be accessed in other devices. + * + * @since 2.0 + * + * @return An error code + * @param[in] filePath The path of the file to open or create + * @param[in] pOpenMode The file opening mode @n + * It can be one of the following: + * - r : Open for reading. + * - r+: Open for reading and writing. + * - w : Open for writing. The file is created if it does not exist, + * otherwise it is truncated to zero length. + * - w+: Open for writing and reading. The file is created if it does not exist, + * otherwise it is truncated to zero length. + * - a : Open for appending. The file is created if it does not exist. + * - a+: Open for appending and reading. The file is created if it does not exist. + * @param[in] secretKey A key used to encrypt data of a file or decrypt a secure file @n + * If a secure file is created with a specific key value, + * other applications can access the same secure file with the identical key value. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. + * - The combination of the specified @c pOpenMode is not allowed. @n + * - The specified @c secretKey is incorrect or the secure file is corrupted. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. @n + * For example, opening a read-only file in the write mode such as "w" or "a". + * @exception E_FILE_NOT_FOUND The specified @c filePath cannot be found. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. @n + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The following file opening mode strings are recognized by this method: "w+", "wb+", "w+b", "w", "wb", "a+", + * "ab+", "a+b", "a", "ab", "r+", "rb+", "r+b", "r", "rb". @n + * Other strings lead to E_INVALID_ARG. However, "b"(binary) open mode is ignored internally. + */ + result Construct(const Tizen::Base::String& filePath, const char* pOpenMode, const Tizen::Base::ByteBuffer& secretKey); + + /** + * Reads the byte data from the current file pointer. @n + * The user-specified ByteBuffer is filled with the byte data from the current position in the file. + * The read operation continues until the specified ByteBuffer is filled or end-of-file is met. @n + * In the secure mode, the byte data read from the secure file is automatically decrypted by a platform security module. + * + * @since 2.0 + * + * @return An error code + * @param[in, out] buffer A reference to the buffer that is used to receive the byte data read from the file + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c buffer has no space to store the read data. + * @exception E_ILLEGAL_ACCESS Either of the following conditions has occurred: @n + * - The file is not opened for read operation. @n + * - Access is denied due to insufficient permission. + * @exception E_END_OF_FILE The file pointer has reached end-of-file. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks The ByteBuffer should be constructed before being passed to the method. + */ + result Read(Tizen::Base::ByteBuffer& buffer); + + /** + * Reads the byte data from the current file pointer and copies it into the specified buffer. @n + * In the secure mode, the byte data read from the secure file is automatically decrypted by a platform security module. + * + * @since 2.0 + * + * @return The length of the data read in bytes, @n + * else @c 0 in case of failure + * @param[out] buffer A pointer to the user-supplied buffer where the read data is copied + * @param[in] length The buffer length in bytes + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c buffer contains a @c null pointer. @n + * - The length of the specified @c buffer is equal to or smaller than @c 0. @n + * @exception E_ILLEGAL_ACCESS Either of the following conditions has occurred: @n + * - The file is not opened for read operation. @n + * - Access is denied due to insufficient permission. + * @exception E_END_OF_FILE The file pointer has reached end-of-file. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + int Read(void* buffer, int length); + + /** + * Reads the string data from the current file pointer and copies the string to the specified buffer (it is assumed that the + * file is in the UTF-8 format). @n + * The read operation continues until new line character or end-of-file is met. @n + * In the secure mode, the string data read from the secure file is automatically decrypted by a platform security module. + * + * @since 2.0 + * + * @return An error code + * @param[out] buffer A reference to the buffer where the data is copied + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The file handle is invalid (either the file is closed by another method, or the + * memory is corrupted). + * @exception E_ILLEGAL_ACCESS Either of the following conditions has occurred: @n + * - The file is not opened for read operation. @n + * - Access is denied due to insufficient permission. + * @exception E_END_OF_FILE The file pointer reached end-of-file. + * @exception E_IO Either of the following conditions has occurred: + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks To get the expected string value + * from a file, which is not in the UTF-8 format (Unicode or any other format), + * user should use other encoding or decoding methods of the Tizen::Text namespace after reading the content of + * a file in binary format. @n + * The maximum length of characters read by this method is defined as 4096. @n + * Therefore, if the length of a single line (considering new line character or end-of-file) from the current + * file position is longer than 4096, the rest of the characters remain as not read. @n + * 'ByteBuffer' or 'void*' version of the File::Read() API can be used to overcome this limitation. + */ + result Read(Tizen::Base::String& buffer); + + /** + * Writes the byte data from the specified ByteBuffer into a file beginning at the current position to the limit of the + * %ByteBuffer. @n + * In the secure mode, the byte data written by a user is automatically encrypted to the secure file by a platform security module. @n + * The size of a secure file can be greater than the size of a normal (original) file + * because of the encryption. + * However, the file pointer for the secure file is equal to the file pointer for the original file. + * + * @since 2.0 + * + * @return An error code + * @param[in] buffer A reference to the buffer that contains byte data to write + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The file handle is invalid (either the file is closed by another method, or the + * memory is corrupted). + * @exception E_ILLEGAL_ACCESS Either of the following conditions has occurred: @n + * - The file is not opened for write operation. @n + * - Access is denied due to insufficient permission. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + result Write(const Tizen::Base::ByteBuffer& buffer); + + /** + * Writes the byte data into a file. @n + * In the secure mode, the byte data written by a user is automatically encrypted to the secure file by a platform security module. @n + * The size of a secure file can be greater than the size of a normal (original) file + * because of the encryption. + * However, the file pointer for the secure file is equal to the file pointer for the original file. + * + * @since 2.0 + * + * @return An error code + * @param[in] buffer A pointer to the user-supplied buffer that contains @c byte data to write + * @param[in] length The buffer length in bytes + * @exception E_SUCCESS The method is successful. + * @exception E_ILLEGAL_ACCESS Either of the following conditions has occurred: @n + * - The file is not opened for write operation. @n + * - Access is denied due to insufficient permission. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c buffer contains a @c null pointer. @n + * - The specified @c buffer length is equal or smaller than @c 0. @n + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + result Write(const void* buffer, int length); + + /** + * Writes the string data into a file. @n + * In the secure mode, the string data written by a user is automatically encrypted to the secure file by a platform security + * module. @n + * The size of a secure file can be greater than the size of a normal (original) file + * because of the encryption. + * However, the file pointer for the secure file is equal to the file pointer for the original file. + * + * @since 2.0 + * + * @return An error code + * @param[in] buffer A reference to the buffer that contains string data to write + * @exception E_SUCCESS The method is successful. + * @exception E_ILLEGAL_ACCESS Either of the following conditions has occurred: @n + * - The file is not opened for write operation. @n + * - Access is denied due to insufficient permission. + * @exception E_INVALID_ARG The specified @c buffer contains an empty string. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + result Write(const Tizen::Base::String& buffer); + + /** + * Flushes the internally buffered data into a permanent storage immediately. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_INVALID_ARG The file handle is invalid (either the file is closed by another method, or the + * memory is corrupted). + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + result Flush(void); + + /** + * Gets the offset of the current file pointer relative to the beginning of the file. @n + * The size of a secure file can be greater than the size of a normal (original) file + * because of the encryption. + * However, the file pointer for the secure file is equal to the file pointer for the original file. + * + * @since 2.0 + * + * @return The offset of the current file pointer, @n + * else @c -1L if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The file handle is invalid (either the file is closed by another method, or the + * memory is corrupted). + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Seek() + */ + int Tell(void) const; + + /** + * Repositions the file pointer associated with an opened file. @n + * Each opened file has its own file pointer, and it points to the next byte to be read or written in the file. + * The repositioning offset can be specified with respect to the beginning of file, current position, or end of the file. + * If the file pointer is over the end-of-file, it expands the file size to the specified position and the expanded area is + * filled with zero. @n + * The size of a secure file can be greater than the size of a normal (original) file + * because of the encryption. + * However, the file pointer for the secure file is equal to the file pointer for the original file. + * + * @since 2.0 + * + * @return An error code + * @param[in] position The origin from where to start the repositioning a file pointer + * @param[in] offset The number of bytes to move a file pointer @n + * A negative offset moves the pointer backwards. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c position or @c offset is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @see FileSeekPosition + */ + result Seek(FileSeekPosition position, long offset); + + /** + * Truncates the file size to the specified length. @n + * If the specified length is less than the length of file, the bytes present between the @c length and size of a file are + * removed. + * If the file size is small, its size is increased. @n + * The size of a secure file can be greater than the size of a normal (original) file + * because of the encryption. + * However, the file pointer for a secure file is equal to the file pointer for an original file. + * + * @since 2.0 + * + * @return An error code + * @param[in] length The required file size in bytes after this method is executed + * @exception E_SUCCESS The method is successful. + * @exception E_ILLEGAL_ACCESS Either of the following conditions has occurred: @n + * - The file is not opened for write operation. @n + * - Access is denied due to insufficient permission. + * @exception E_INVALID_ARG The specified @c length has a negative value. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + result Truncate(int length); + + /** + * Gets the path associated with a constructed %File. + * + * @since 2.0 + * + * @return The file path to the currently constructed %File if successful, @n + * else an empty string in case of failure + */ + Tizen::Base::String GetName(void) const; + + /** + * Deletes the file specified. @n + * The opened file cannot be deleted. This method is static. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] filePath The path of the file to delete + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. @n + * For example, opening a read-only file in the write mode. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks The opened file cannot be deleted. + */ + static result Remove(const Tizen::Base::String& filePath); + + /** + * Moves the specified file to another location. @n + * The opened files cannot be moved. This method is static. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] oldFilePath The old file path + * @param[in] newFilePath The new file path + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. @n + * For example, opening a read-only file in the write mode. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_FILE_ALREADY_EXIST The specified file already exists. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @see Copy() + * @see Remove() + */ + static result Move(const Tizen::Base::String& oldFilePath, const Tizen::Base::String& newFilePath); + + /** + * Copies the existing source file to the destined location. @n + * This method is static. + * + * @since 2.0 + * + * @return An error code + * @param[in] srcFilePath The source file path + * @param[in] destFilePath The destination file path + * @param[in] failIfExist Set to @c true to return an error if the destination file already exists, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. @n + * For example, opening a read-only file in the write mode. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_FILE_ALREADY_EXIST The specified file already exists. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @see Move() + * @see Remove() + */ + static result Copy(const Tizen::Base::String& srcFilePath, const Tizen::Base::String& destFilePath, bool failIfExist); + + /** + * Reads the file information such as size, attribute, creation date, and so on. @n + * This method is static. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] filePath The path of the file @n + * @param[out] attribute A %File attribute instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + static result GetAttributes(const Tizen::Base::String& filePath, FileAttributes& attribute); + + /** + * Gets only the file name from the specified file path. @n + * For example, if the file path passed is 'xxx/file.txt', 'file.txt' is returned. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return The file name of type String + * @param[in] filePath The path of the file + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of the specified path is @c 0 or exceeds system limitations. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetFileExtension() + */ + static Tizen::Base::String GetFileName(const Tizen::Base::String& filePath); + + /** + * Gets the file extension of the specified file path. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return The file extension, @n + * else an empty string if the file has no extension + * @param[in] filePath The path of the file + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of the specified path is @c 0 or exceeds system limitations. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetFileName() + */ + static Tizen::Base::String GetFileExtension(const Tizen::Base::String& filePath); + + /** + * Checks whether the specified file or directory exists. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return @c true if file or directory exists, @n + * else @c false + * @param[in] filePath The path of the file or directory + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The specified path is invalid. + * @exception E_ILLEGAL_ACCESS The specified path is not permitted, or + * access is denied due to insufficient permission. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static bool IsFileExist(const Tizen::Base::String& filePath); + + /** + * Converts a normal file to a secure file. @n + * A secure file that is converted by this method can be shared among applications with the same key value. + * This method is static. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] plainFilePath The normal (non-encrypted) file path + * @param[in] secureFilePath The secure (encrypted) file path to create + * @param[in] key A key that encrypts a secure file @n + * If the secure file is converted with a specific key value, + * applications can access the same secure file with the identical key value. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. @n + * - The specified path is invalid. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_ALREADY_EXIST The specified file already exists. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. @n + * - The number of opened files has exceeded the maximum limit. + */ + static result ConvertToSecureFile(const Tizen::Base::String& plainFilePath, const Tizen::Base::String& secureFilePath, const Tizen::Base::ByteBuffer& key); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + File(const File& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + File& operator =(const File& rhs); + + class _FileImpl* __pFileImpl; + + friend class _FileImpl; + +}; // File + +}} // Tizen::Io + +#endif // _FIO_FILE_H_ + diff --git a/inc/FIoFileAttributes.h b/inc/FIoFileAttributes.h new file mode 100644 index 0000000..8c5e345 --- /dev/null +++ b/inc/FIoFileAttributes.h @@ -0,0 +1,248 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoFileAttributes.h + * @brief This is the header file for the %FileAttributes class. + * + * This header file contains the declarations of the %FileAttributes class. + */ + +#ifndef _FIO_FILE_ATTRIBUTES_H_ +#define _FIO_FILE_ATTRIBUTES_H_ + +#include + +namespace Tizen { namespace Base +{ +class DateTime; +}} + +namespace Tizen { namespace Io +{ + +/** + * @class FileAttributes + * @brief This class provides a collection of basic file attributes. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %FileAttributes class provides the attributes of a file or directory. + * It can be used to determine the various file properties such as file attributes + * (read-only, hidden, system, or directory), creation time, last modified time, and file size. + * + * For more information on the class features, + * see Io Guide. + * + * The following example demonstrates how to use the %FileAttributes class. + * + * @code +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Io; + +int main(void) +{ + String fileName(L"test.txt"); + File file; + FileAttributes attr; + long long size; + DateTime dtCreate ; + DateTime dtModified ; + result r = E_SUCCESS; + + r = File::GetAttributes(App::GetInstance()->GetAppDataPath() + fileName, attr); + if (IsFailed(r)) + { + goto CATCH; + } + + size = attr.GetFileSize(); + AppLog("* size=%d", size); + + dtCreate = attr.GetDateTime(); + AppLog("* creation time: %d year, %d month, %d day, %d hour, %d min, %d sec.\n", + dtCreate.GetYear(), + dtCreate.GetMonth(), + dtCreate.GetDay(), + dtCreate.GetHour(), + dtCreate.GetMinute(), + dtCreate.GetSecond() + ); + + dtModified = attr.GetLastModifiedTime(); + AppLog("* last modified time: %d year, %d month, %d day, %d hour, %d min, %d sec.\n", + dtModified.GetYear(), + dtModified.GetMonth(), + dtModified.GetDay(), + dtModified.GetHour(), + dtModified.GetMinute(), + dtModified.GetSecond() + ); + + if (attr.IsDirectory()) + { + AppLog("* This is a directory."); + } + if (attr.IsHidden()) + { + AppLog("* This is a hidden file."); + } + if (attr.IsReadOnly()) + { + AppLog("* This is a read-only file."); + } + + AppLog("Succeeded!"); + return 0; + +CATCH: + AppLog("Failed..."); + return -1; +} + * @endcode + */ +class _OSP_EXPORT_ FileAttributes + : public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + FileAttributes(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~FileAttributes(void); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] rhs An instance of %FileAttributes + */ + FileAttributes(const FileAttributes& rhs); + + /** + * Assigns the value of the specified instance to the current instance of %FileAttributes. + * + * @since 2.0 + * + * @return The reference of this instance + * @param[in] rhs An instance of %FileAttributes + */ + FileAttributes& operator =(const FileAttributes& rhs); + + /** + * Compares the specified instance of Object to the calling instance of %FileAttributes. + * + * @since 2.0 + * + * @return @c true if the values of the specified instance equals the values of the current instance, @n + * else @c false + * @param[in] object The object to compare with the current instance + */ + virtual bool Equals(const Tizen::Base::Object& object) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return An integer value indicating the hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Gets the file size. + * + * @since 2.0 + * + * @return The file size in bytes + */ + long long GetFileSize(void) const; + + /** + * Checks whether the current file is a directory. + * + * @since 2.0 + * + * @return @c true if the file is a directory, @n + * else @c false + */ + bool IsDirectory(void) const; + + /** + * Checks whether the file has a hidden attribute. + * + * @since 2.0 + * + * @return @c true if the file has a hidden attribute, @n + * else @c false + */ + bool IsHidden(void) const; + + /** + * Checks whether the file has a read-only attribute. + * + * @since 2.0 + * + * @return @c true if the file has a read-only attribute, @n + * else @c false + */ + bool IsReadOnly(void) const; + + /** + * Gets the date and time of the file creation. + * + * @since 2.0 + * + * @return The date and time of the file creation + */ + Tizen::Base::DateTime GetDateTime(void) const; + + /** + * Gets the date and time of the last modification to the file. + * + * @since 2.0 + * + * @return The date and time of the last modification to the file + */ + Tizen::Base::DateTime GetLastModifiedTime(void) const; + +private: + class _FileAttributesImpl* __pFileAttributesImpl; + + friend class _FileAttributesImpl; + +}; // FileAttributes + +}} // Tizen::Io + +#endif //_FIO_FILE_ATTRIBUTES_H_ + diff --git a/inc/FIoFileEventManager.h b/inc/FIoFileEventManager.h new file mode 100644 index 0000000..c07e6cb --- /dev/null +++ b/inc/FIoFileEventManager.h @@ -0,0 +1,178 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoFileEventManager.h + * @brief This is the header file for the %FileEventManager class. + * + * This header file contains the declarations of the %FileEventManager class. + */ + +#ifndef _FIO_FILE_EVENT_MANAGER_H_ +#define _FIO_FILE_EVENT_MANAGER_H_ + +#include + +namespace Tizen { namespace Base +{ +class String; +}} + +namespace Tizen { namespace Io +{ + +class IFileEventListener; +class _FileEventManagerImpl; + +/** + * @enum FileEventType + * + * Defines the file event type. + * + * @since 2.0 + */ +enum FileEventType +{ + FILE_EVENT_TYPE_ACCESS = 0x01, /**<%File was accessed (read)*/ + FILE_EVENT_TYPE_ATTRIBUTE = 0x04, /** +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class ServerChannel; + +/** +* @if OSPDEPREC +* @interface IChannelRequestEventListener +* @brief [Deprecated] This interface provides event handlers for any request events received through a channel. +* +* @deprecated This class is deprecated. Instead of using this class, use IMessagePortListener class. +* @since 2.0 +* +* The %IChannelRequestEventListener interface provides event handlers to receive channel request event. +* @endif +*/ +class _OSP_EXPORT_ IChannelRequestEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IChannelRequestEventListener(void) {} + + /** + * Called when a request is received from the client channel. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] serverChannel The reference to the server channel + * @param[in] clientChannelId The client channel ID + * @param[in] pArgs A pointer to an argument list of type String + */ + virtual void OnChannelRequestReceivedN(RequestId reqId, ServerChannel& serverChannel, const Tizen::Base::String& clientChannelId, Tizen::Base::Collection::IList* pArgs) = 0; + + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IChannelRequestEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IChannelRequestEventListener_Reserved2(void) {} +}; // IChannelRequestEventListener + +} } // Tizen::Io + +#endif // _FIO_ICHANNEL_REQUESTEVENT_LISTENER_H_ diff --git a/inc/FIoIChannelResponseEventListener.h b/inc/FIoIChannelResponseEventListener.h new file mode 100644 index 0000000..d49c916 --- /dev/null +++ b/inc/FIoIChannelResponseEventListener.h @@ -0,0 +1,97 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoIChannelResponseEventListener.h + * @brief This is the header file for the %IChannelResponseEventListener interface. + * + * This header file contains the declarations of the %IChannelResponseEventListener interface. + * + */ +#ifndef _FIO_ICHANNEL_RESPONSEEVENT_LISTENER_H_ +#define _FIO_ICHANNEL_RESPONSEEVENT_LISTENER_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class ClientChannel; +/** +* @if OSPDEPREC +* @interface IChannelResponseEventListener +* @brief [Deprecated] This interface provides event handlers for any response events received through a channel. +* +* @deprecated This class is deprecated. Instead of using this class, use MessagePortManager class. +* @since 2.0 +* +* The %IChannelResponseEventListener interface provides event handlers for receiving the channel response events. +* @endif +*/ +class _OSP_EXPORT_ IChannelResponseEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IChannelResponseEventListener(void) {} + + /** + * Called when a response is received from a server channel. + * + * @since 2.0 + * + * @param[in] reqId The request ID + * @param[in] clientChannel The reference to the client channel + * @param[in] serverChannelId The server channel ID + * @param[in] pArgs A pointer to an argument list of type String + * + */ + virtual void OnChannelResponseReceivedN(RequestId reqId, ClientChannel& clientChannel, const Tizen::Base::String& serverChannelId, Tizen::Base::Collection::IList* pArgs) = 0; + + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IChannelResponseEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IChannelResponseEventListener_Reserved3(void) {} +}; // IChannelResponseEventListener + +} } // Tizen::Io + +#endif // _FIO_ICHANNEL_RESPONSEEVENT_LISTENER_H_ diff --git a/inc/FIoIDbEnumerator.h b/inc/FIoIDbEnumerator.h new file mode 100644 index 0000000..d45f1c2 --- /dev/null +++ b/inc/FIoIDbEnumerator.h @@ -0,0 +1,409 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoIDbEnumerator.h + * @brief This is the header file for the %IDbEnumerator interface. + * + * This header file contains the declarations of the %IDbEnumerator interface. + */ + +#ifndef _FIO_IDB_ENUMERATOR_H_ +#define _FIO_IDB_ENUMERATOR_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** + * @interface IDbEnumerator + * @brief This interface provides methods for navigating the result set from the SELECT query. + * + * @since 2.0 + * + * The %IDbEnumerator interface provides methods for navigating the result set from the SELECT query. + */ +class _OSP_EXPORT_ IDbEnumerator +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IDbEnumerator(void) {} + + /** + * Moves the enumerator to the next position. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). @n + * @exception E_OUT_OF_RANGE The enumerator has reached out of the result set returned by the SELECT query. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual result MoveNext(void) = 0; + + /** + * Moves the enumerator to the previous position. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). @n + * @exception E_OUT_OF_RANGE The enumerator has reached out of the result set returned by the SELECT query. + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual result MovePrevious(void) = 0; + + /** + * Moves the enumerator to the first position. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). @n + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual result MoveFirst(void) = 0; + + /** + * Moves the enumerator to the last position. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). @n + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_INVALID_FORMAT The database file is malformed. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual result MoveLast(void) = 0; + + /** + * Resets the calling %IDbEnumerator instance back to its initial state. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to reset the enumerator of the result set that is not activated + * (the query did not yield any result). @n + * @exception E_OBJECT_LOCKED The database instance is locked. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks After this method is called, if MoveNext() is called the cursor goes to the first position. + */ + virtual result Reset(void) = 0; + + /** + * Gets an @c int value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The integer value obtained from the column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetIntAt(int columnIndex, int& value) const = 0; + + /** + * Gets a @c long @c long value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The 64-bit integer value obtained from the column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetInt64At(int columnIndex, long long& value) const = 0; + + /** + * Gets a @c double value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a double + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetDoubleAt(int columnIndex, double& value) const = 0; + + /** + * Gets a @c String value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a String + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_INVALID_ENCODING_RANGE The string conversion has failed due to invalid encoding range, or + * it is possible if the database file is corrupted. + */ + virtual result GetStringAt(int columnIndex, Tizen::Base::String& value) const = 0; + + /** + * Gets a byte array value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The user-provided buffer used to receive the blob data as a stream of type ByteBuffer @n + * The buffer will be filled from the current position and data copy will be continued + * until buffer limitation is reached or no more blob data remains. @n + * The maximum size available is limited to 100 MByte. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_OUT_OF_RANGE The byte buffer operation has failed. + * @exception E_OVERFLOW The specified @c value of the byte buffer is insufficient to save the data. + */ + virtual result GetBlobAt(int columnIndex, Tizen::Base::ByteBuffer& value) const = 0; + + /** + * Gets a blob data from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] buffer The user-provided buffer used to receive the blob data @n + * The maximum size available is limited to 100 MByte. + * @param[out] size The maximum buffer length in bytes + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range, or the specified @c size is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_OVERFLOW The specified @c buffer is insufficient to save the data. + */ + virtual result GetBlobAt(int columnIndex, void* buffer, int size) const = 0; + + /** + * Gets a @c DateTime value from the column whose index is specified. + * + * @since 2.0 + * + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a DateTime instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_INVALID_FORMAT The date is not correctly formatted, or the method is trying to access column of type String. @n + * The date format should be 'mm/dd/yyyy hh:mm:ss'. + * @exception E_OUT_OF_RANGE Either the year(%d), month(%d), day(%d), hour(%d), minute(%d), or second(%d) value is out of range, + * or the method is trying to access a column of type String. + * @remarks Note that the DateTime is constructed inside the method. + */ + virtual result GetDateTimeAt(int columnIndex, Tizen::Base::DateTime& value) const = 0; + + /** + * Gets the number of columns for this enumerator. + * + * @since 2.0 + * + * @return The number of columns in the calling enumerator, @n + * else @c -1 if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @remarks The method must be called after MoveNext(), MoveFirst(), or MoveLast(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetColumnCount(void) const = 0; + + /** + * Gets the type of the column indicated by the specified index. + * + * @since 2.0 + * + * @return The type of column, @n + * else DB_COLUMNTYPE_UNDEFINED if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @remarks The method must be called after MoveNext(), MoveFirst(), or MoveLast(). @n + * Currently, DB_COLUMNTYPE_INT is returned for a 64-bit integer. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual DbColumnType GetColumnType(int columnIndex) const = 0; + + /** + * Gets the name of the column indicated by the specified index. + * + * @since 2.0 + * + * @return The name of the column, @n + * else an empty string if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_INVALID_ENCODING_RANGE The string conversion has failed due to invalid encoding range, or + * it is possible if the database file is corrupted. + * @remarks The method must be called after MoveNext(), MoveFirst(), or MoveLast(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetColumnName(int columnIndex) const = 0; + + /** + * Gets the size of data in bytes. + * + * @since 2.0 + * + * @return The size of the data in bytes, @n + * else @c -1 if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: @n + * - This instance has not been properly constructed. @n + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). @n + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @remarks The method must be called after MoveNext(), MoveFirst(), or MoveLast(). @n + * If the destination column is of type %String, this method returns the @c byte length excluding the @c null terminator character. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetColumnSize(int columnIndex) const = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IDbEnumerator_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IDbEnumerator_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IDbEnumerator_Reserved3(void) {} + +}; // IDBEnumerator + +}} // Tizen::App + +#endif // _FIO_IDB_ENUMERATOR_H_ + diff --git a/inc/FIoIFileEventListener.h b/inc/FIoIFileEventListener.h new file mode 100644 index 0000000..44c398d --- /dev/null +++ b/inc/FIoIFileEventListener.h @@ -0,0 +1,97 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoIFileEventListener.h + * @brief This is the header file for the %IFileEventListener interface. + * + * This header file contains the declarations of the %IFileEventListener interface. + */ + +#ifndef _FIO_IFILE_EVENT_LISTENER_H_ +#define _FIO_IFILE_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +/** +* @interface IFileEventListener +* @brief This listener interface is used for receiving file event. +* +* @since 2.0 +* +* The %IFileEventListener interface is used for receiving file event. +*/ +class _OSP_EXPORT_ IFileEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ + +public: + /** + * Called when a monitored file or directory is changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] events The file event type @n + * Multiple event type can be combined using bitwise OR (see Tizen::Io::FileEventType). @n + * Tizen::Io::FILE_EVENT_TYPE_ALL is provided for all file event type. + * @param[in] path The path to the directory or file that event is occurred + * @param[in] eventId The event id associating related events for single operation such as File::Move, Directory::Rename + */ + virtual void OnFileEventOccured(const unsigned long events, const Tizen::Base::String& path, const unsigned int eventId) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IFileEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IFileEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IFileEventListener_Reserved3(void) {} + +}; // IFileEventListener + +}} // Tizen::Io + +#endif //_FIO_IFILE_EVENT_LISTENER + diff --git a/inc/FIoIMessagePortListener.h b/inc/FIoIMessagePortListener.h new file mode 100644 index 0000000..11c2f51 --- /dev/null +++ b/inc/FIoIMessagePortListener.h @@ -0,0 +1,122 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoIMessagePortListener.h + * @brief This is the header file for the %IMessagePortListener interface. + * + * This header file contains declarations of the %IMessagePortListener interface. + */ + +#ifndef _FIO_IMESSAGE_PORT_LISTENER_H_ +#define _FIO_IMESSAGE_PORT_LISTENER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class RemoteMessagePort; + +/** +* @interface IMessagePortListener +* @brief This interface provides event handlers to receive messages from other applications. +* +* @since 2.0 +* +* The %IMessagePortListener interface provides event handlers to receive messages from other applications. +*/ +class _OSP_EXPORT_ IMessagePortListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IMessagePortListener(void) {} + + /** + * Called when a message is received from a remote application. @n + * This method will be called only if the remote application uses bidirectional communication method - RemoteMessagePort::SendMessage(const LocalMessagePort* pLocalMessagePort, const Tizen::Base::Collection::IMap* pMessagee). + * The RemoteMessagePort instance can be used to send a response message to the message port of the remote application. + * + * @since 2.0 + * + * @param[in] pRemoteMessagePort The message port of a remote application which has sent this message + * @param[in] pMessage A pointer to an argument map of key (String) and value (String or ByteBuffer) pair + */ + virtual void OnMessageReceivedN(RemoteMessagePort* pRemoteMessagePort, Tizen::Base::Collection::IMap* pMessage) {} + + /** + * Called when a message is received from a remote application. @n + * This method will be called only if the remote application uses unidirectional communication method - RemoteMessagePort::SendMessage(const Tizen::Base::Collection::IMap* pMessage). + * + * @since 2.0 + * + * @param[in] pMessage A pointer to an argument map of key (String) and value (String or ByteBuffer) pair + */ + virtual void OnMessageReceivedN(Tizen::Base::Collection::IMap* pMessage) {} + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMessagePortListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMessagePortListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMessagePortListener_Reserved3(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IMessagePortListener_Reserved4(void) {} +}; // IMessagePortListener + +} } // Tizen::Io + +#endif // _FIO_IMESSAGE_PORT_LISTENER_H_ diff --git a/inc/FIoIMmcStorageFormatListener.h b/inc/FIoIMmcStorageFormatListener.h new file mode 100644 index 0000000..04a6c8c --- /dev/null +++ b/inc/FIoIMmcStorageFormatListener.h @@ -0,0 +1,92 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FIoIMmcStorageFormatListener.h +* @brief This is the header file for the %IMmcStorageFormatListener interface. +* +* This header file contains the declarations of the %IMmcStorageFormatListener interface. +*/ + +#ifndef _FIO_IMMC_STORAGE_FORMAT_LISTENER_H_ +#define _FIO_IMMC_STORAGE_FORMAT_LISTENER_H_ + +#include + +namespace Tizen { namespace Io +{ + +/** +* @interface IMmcStorageFormatListener +* @brief This interface is the listener to receive the result of external MMC format operations. +* @since 2.0 +* +* The %IMmcStorageFormatListener interface must be registered and implemented by an application to receive the result of +* external MMC format operations. +* +* @see MmcStorageManager +*/ +class _OSP_EXPORT_ IMmcStorageFormatListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface called. + * + * @since 2.0 + */ + virtual ~IMmcStorageFormatListener(void) {} + + /** + * Called when external MMC format operation is done. + * + * @since 2.0 + * + * @param[in] r The result of external MMC format operation + * @exception E_SUCCESS The format operation is successful. + * @exception E_IO An unexpected device failure has occurred as the media ejected suddenly. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual void OnMmcStorageFormatted(result r) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IMmcStorageFormatListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IMmcStorageFormatListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IMmcStorageFormatListener_Reserved3(void) {} + +}; // IMmcStorageFormatListener + +} } // Tizen::Io + +#endif // _FIO_IMMC_STORAGE_FORMAT_LISTENER_H diff --git a/inc/FIoIMmcStorageMountListener.h b/inc/FIoIMmcStorageMountListener.h new file mode 100644 index 0000000..182777c --- /dev/null +++ b/inc/FIoIMmcStorageMountListener.h @@ -0,0 +1,106 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FIoIMmcStorageMountListener.h +* @brief This is the header file for the %IMmcStorageMountListener interface. +* +* This header file contains the declarations of the %IMmcStorageMountListener interface. +*/ + +#ifndef _FIO_IMMC_STORAGE_MOUNT_LISTENER_H_ +#define _FIO_IMMC_STORAGE_MOUNT_LISTENER_H_ + +#include + +namespace Tizen { namespace Io +{ + +/** +* @interface IMmcStorageMountListener +* @brief This interface is the listener to receive the result of external MMC mount or unmount operations. +* @since 2.0 +* +* The %IMmcStorageMountListener interface must be registered and implemented by an application to receive the result of +* external MMC mount or unmount operations. +* +* @see MmcStorageManager +*/ +class _OSP_EXPORT_ IMmcStorageMountListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface called. + * + * @since 2.0 + */ + virtual ~IMmcStorageMountListener(void) {} + + /** + * Called when external MMC mount operation is done. + * + * @since 2.0 + * + * @param[in] r The result of external MMC mount operation + * @exception E_SUCCESS The mount operation is successful. + * @exception E_IO Either of the following conditions has occurred: @n + * - The file system to be mounted has an invalid superblock. + * - An unexpected device failure has occurred as the media ejected suddenly. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual void OnMmcStorageMounted(result r) = 0; + + /** + * Called when external MMC unmount operation is done. + * + * @since 2.0 + * + * @param[in] r The result of external MMC unmount operation + * @exception E_SUCCESS The unmount operation is successful. + * @exception E_IO An unexpected device failure has occurred as the media ejected suddenly. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual void OnMmcStorageUnmounted(result r) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IMmcStorageMountListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IMmcStorageMountListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IMmcStorageMountListener_Reserved3(void) {} + +}; // IMmcStorageMountListener + +} } // Tizen::Io + +#endif // _FIO_IMMC_STORAGE_MOUNT_LISTENER_H diff --git a/inc/FIoISerialPortEventListener.h b/inc/FIoISerialPortEventListener.h new file mode 100644 index 0000000..452cd23 --- /dev/null +++ b/inc/FIoISerialPortEventListener.h @@ -0,0 +1,109 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoISerialPortEventListener.h + * @brief This is the header file for the %ISerialPortEventListener interface. + * + * This header file contains the declarations of the %ISerialPortEventListener interface. + */ + +#ifndef _FIO_SERIAL_PORT_EVENT_LISTENER_H_ +#define _FIO_SERIAL_PORT_EVENT_LISTENER_H_ + +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** + * @interface ISerialPortEventListener + * @brief This interface provides event handlers to receive serial port events synchronously. + * + * @since 2.0 + * + * The %ISerialPortEventListener interface provides event handlers to receive serial port events synchronously. @n + * + * For more information on the class features, see Serial Port Communication. + * + */ + +class _OSP_EXPORT_ ISerialPortEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ + +public: + /** + * Called when the data is received on the serial port. + * + * @since 2.0 + * + * @param[in] byteBuffer A byte buffer that contains the received data + * @remarks The ByteBuffer instance needs to be deleted by the application. + */ + virtual void OnSerialPortDataReceivedN(Tizen::Base::ByteBuffer& byteBuffer) = 0; + + /** + * Called when an error occurs on the serial port. + * + * @since 2.0 + * + * @param[in] r The error code + * @exception E_INVALID_DATA The data is invalid. + * @exception E_SYSTEM A system error has occurred. + */ + virtual void OnSerialPortErrorOccured(result r) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISerialPortEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISerialPortEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISerialPortEventListener_Reserved3(void) {} + +}; // ISerialPortEventListener + +}} // Tizen::Io + +#endif // _FIO_SERIAL_PORT_EVENT_LISTENER_H_ + diff --git a/inc/FIoLocalMessagePort.h b/inc/FIoLocalMessagePort.h new file mode 100644 index 0000000..a3bebbe --- /dev/null +++ b/inc/FIoLocalMessagePort.h @@ -0,0 +1,189 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoLocalMessagePort.h + * @brief This is the header file for the %LocalMessagePort class. + * + * This header file contains declarations of the %LocalMessagePort class. + */ +#ifndef _FIO_LOCAL_MESSAGE_PORT_H_ +#define _FIO_LOCAL_MESSAGE_PORT_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class IMessagePortListener; + +/** +* @class LocalMessagePort +* @brief This class provides methods for receiving messages from other applications. +* +* @since 2.0 +* +* @final This class is not intended for extension. +* +* The %LocalMessagePort class provides methods for receiving messages from other applications. +* +* For more information on the class features, +* see Message Port Communication. +* +* @see Tizen::Io::MessagePortManager +* @see Tizen::Io::RemoteMessagePort +* +* The following example demonstrates how to use the %LocalMessagePort class. +* +* @code +* +* #include +* #include +* +* using namespace Tizen::Base; +* using namespace Tizen::Base::Collection; +* using namespace Tizen::Io; +* +* class MyAppClass +* : public Tizen::Io::IMessagePortListener +* { +* public: +* result Initialize(void); +* virtual void OnMessageReceivedN(RemoteMessagePort* pRemoteMessagePort, IMap* pMessage); +* IMap* GetOnlineFriends(void); +* +* private: +* LocalMessagePort* pLocalPort; +* }; +* +* void +* MyAppClass::Initialize(void) +* { +* pLocalPort = MessagePortManager::RequestLocalMessagePort(L"PortB"); +* pLocalPort->AddMessagePortListener(*this); +* } +* +* void +* MyAppClass::OnMessageReceivedN(RemoteMessagePort* pRemoteMessagePort, IMap* pMessage); +* { +* String* pValue = pMessage->GetValue(L"Request"); +* +* if (*pValue == L"Friend") +* { +* HashMap* pMap = GetOnlineFriends(); +* pRemoteMessagePort->SendMessage(pLocalPort, pMap); +* +* delete pMap; +* } + +* delete pMessage; +* } +* +* IMap* +* MyAppClass::GetOnlineFriends(void) +* { +* HashMap* pMap = new HashMap(SingleObjectDeleter); +* pMap->Construct(); +* +* pMap->Add(new String(L"Reply"), new String(L"Kim")); +* +* return pMap; +* } +* +* @endcode +*/ + +class _OSP_EXPORT_ LocalMessagePort + : public Tizen::Base::Object +{ +public: + /** + * Adds a message port listener that is called when a message is received. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The message port listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_ALREADY_EXIST The listener instance already exists. + */ + result AddMessagePortListener(IMessagePortListener& listener); + + /** + * Removes a message port listener. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The message port listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The listener instance is not found. + */ + result RemoveMessagePortListener(IMessagePortListener& listener); + + /** + * Gets the name of a local message port. + * + * @since 2.0 + * + * @return The name of a local message port + */ + Tizen::Base::String GetName(void) const; + + /** + * Checks whether an instance is a trusted message port or not. + * + * @since 2.0 + * + * @return @c true if this instance is a trusted message port, @n + * else @c false + */ + bool IsTrusted(void) const; + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + LocalMessagePort(void); + + /** + * This destructor is intentionally declared as private so that only the platform can delete an instance. + */ + virtual ~LocalMessagePort(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + LocalMessagePort(const LocalMessagePort& localMessagePort); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + LocalMessagePort& operator =(const LocalMessagePort& localMessagePort); + + + friend class _LocalMessagePortImpl; + + class _LocalMessagePortImpl * __pLocalMessagePortImpl; + +}; // LocalMessagePort + +} } // Tizen::Io + +#endif //_FIO_LOCAL_MESSAGE_PORT_H_ diff --git a/inc/FIoMemoryMappedFile.h b/inc/FIoMemoryMappedFile.h new file mode 100644 index 0000000..c60f6d6 --- /dev/null +++ b/inc/FIoMemoryMappedFile.h @@ -0,0 +1,219 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoMemoryMappedFile.h + * @brief This is the header file for the %MemoryMappedFile class. + * + * This header file contains the declarations of the %MemoryMappedFile class. + */ + +#ifndef _FIO_MEMORY_MAPPED_FILE_H_ +#define _FIO_MEMORY_MAPPED_FILE_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +/** + * @enum MemoryMappedFileFlag + * + * Defines flags providing information about the handling of a memory mapped file. + * + * @since 2.0 + */ +enum MemoryMappedFileFlag +{ + MEMORY_MAPPED_FILE_FLAG_SHARED = 0x01, /**< Changes are shared with other processes mapping the same file */ + MEMORY_MAPPED_FILE_FLAG_PRIVATE = 0x02, /**< Changes are not visible to other processes mapping the same file */ + MEMORY_MAPPED_FILE_FLAG_FIXED = 0x10 /**< This forces the system to use the specified mapping address exactly, + which should be a multiple of the page size */ +}; + +/** + * @enum MemoryMappedFileSyncFlag + * + * Defines synchronization flags of a memory mapped file. + * + * @since 2.0 + */ +enum MemoryMappedFileSyncFlag +{ + MEMORY_MAPPED_FILE_SYNC_FLAG_ASYNC = 0x01, /**< Asynchronous update */ + MEMORY_MAPPED_FILE_SYNC_FLAG_SYNC = 0x02 /**< Synchronous update */ +}; + +/** + * @class MemoryMappedFile + * @brief This class provides features mapping a file to virtual address space. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %MemoryMappedFile class provides features for using a memory mapped file, + * which maps the data of a file to an application's virtual address space. + */ +class _OSP_EXPORT_ MemoryMappedFile + : public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + MemoryMappedFile(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + ~MemoryMappedFile(void); + + /** + * Initializes this instance of %MemoryMappedFile with a specified file. + * + * @since 2.0 + * + * @return An error code + * @param[in] file The File instance for memory mapping + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c file is not opened for reading. @n + * The opening mode should not be "w" or "a". + * @remarks The specified @c file should be initialized by the Io::File::Construct() method. + * @see Tizen::Io::File + */ + result Construct(const File& file); + + /** + * Creates a new mapping for the specified file in the virtual address space of the calling process. + * + * @since 2.0 + * + * @return The mapped address space, @n + * else @c null pointer if this method fails + * @param[in] address A starting address of the mapping @n + * If the specified @c address is @c null, the system chooses the address. + * It should be a multiple of the page size. + * @param[in] length The length of the mapping space + * @param[in] protection The memory protection of the mapping @n + * It is either Base::Runtime::MEMORY_PROTECTION_MODE_NONE or the bitwise-inclusive OR of one + * or more of the other modes in Base::Runtime::MemoryProtectionMode. + * @param[in] flag The flag providing information about the handling of a memory mapped file @n + * It is the bitwise-inclusive OR of the flags in Tizen::Io::MemoryMappedFileFlag. + * @param[in] offset The start offset of the specified file @n + * It should be a multiple of the page size. + * @exception E_SUCCESS The method is successful. + * @exception E_ILLEGAL_ACCESS The specified @c flag is MEMORY_MAPPED_FILE_FLAG_SHARED and the specified @c + * protection is MEMORY_PROTECTION_MODE_WRITE, but the specified file of + * MemoryMappedFile::Construct() is not opened with read-write mode. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c address or @c offset is not aligned on a page boundary. @n + * - The specified @c length is not positive. @n + * - The specified @c protection, @c flag, or @c offset @ is invalid. @n + * - The specified @c flag cannot contain both MEMORY_MAPPED_FILE_FLAG_PRIVATE and + * MEMORY_MAPPED_FILE_FLAG_SHARED. + * @exception E_MAX_EXCEEDED The number of mapped regions has exceeded the maximum limit. + * @exception E_OBJECT_LOCKED The mapped file has been locked. + * @exception E_OUT_OF_MEMORY Either of the following conditions has occurred: @n + * - The memory is insufficient. @n + * - The specified @c flag is MEMORY_MAPPED_FILE_FLAG_FIXED, and the specified address + * range exceeds that allowed for the address space of a current process. + * @exception E_IO Either of the following conditions has occurred: @n + * - The underlying file system does not support memory mapping. @n + * - The specified @c protection is MEMORY_PROTECTION_MODE_EXEC, but the mapped file + * exists on a file system that has been mounted no-exec. + * @remarks The specific error code can be accessed using the GetLastResult() method. @n + * When this instance is destructed, all mappings are deleted automatically. + * @see Tizen::Base::Runtime::MemoryManager + */ + void* Map(void* address, long long length, unsigned long protection, unsigned long flag, long long offset); + + /** + * Deletes the mapping of the specified address space. @n + * Further references to the addresses within the range result in generation of an invalid memory access. @n + * This method flushes all changes of a shared mapping to the correlated file on the permanent storage. + * + * @since 2.0 + * + * @return An error code + * @param[in] address The memory mapping address to unmap + * @param[in] length The length of the mapping space + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c address is not aligned on a page boundary. @n + * - The specified @c length is not positive. @n + * - The specified address range is out of the valid address space of a current process. + * @remarks When this instance is destructed, all mappings of the instance are not unmapped automatically. + */ + result Unmap(void* address, long long length); + + /** + * Flushes all changes of an address range to the correlated file on the permanent storage. + * + * @since 2.0 + * + * @return An error code + * @param[in] address The memory mapping address to synchronize + * @param[in] length The length of the mapping space + * @param[in] syncFlag The synchronization option + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c address is not aligned on a page boundary. @n + * - The specified @c length is not positive. @n + * - The specified @c syncFlag is invalid. @n + * - The specified @c address space is not mapped. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @remarks The specific page size of a current file system is provided by Tizen::System::SystemInfo class with + * "StorageInfo" key. + * @see Tizen::Io::MemoryMappedFileSyncFlag + * @see Tizen::System::SystemInfo + */ + result Sync(void* address, long long length, MemoryMappedFileSyncFlag syncFlag); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + MemoryMappedFile(const MemoryMappedFile& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + MemoryMappedFile& operator =(const MemoryMappedFile& rhs); + + class _MemoryMappedFileImpl* __pMemoryMappedFileImpl; + + friend class _MemoryMappedFileImpl; + +}; // MemoryMappedFile + +}} // Tizen::Io + +#endif // _FIO_MEMORY_MAPPED_FILE_H_ + diff --git a/inc/FIoMessagePortManager.h b/inc/FIoMessagePortManager.h new file mode 100644 index 0000000..74e88ba --- /dev/null +++ b/inc/FIoMessagePortManager.h @@ -0,0 +1,152 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoMessagePortManager.h + * @brief This is the header file for the %MessagePortManager class. + * + * This header file contains declarations of the %MessagePortManager class. + */ +#ifndef _FIO_MESSAGE_PORT_MANAGER_H_ +#define _FIO_MESSAGE_PORT_MANAGER_H_ + +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** +* @class MessagePortManager +* @brief This class provides methods for managing message ports. +* +* @since 2.0 +* +* @final This class is not intended for extension. +* +* The %MessagePortManager class provides methods for managing message ports. +* +* For more information on the class features, +* see Message Port Communication. +* +* @see Tizen::Io::LocalMessagePort +* @see Tizen::Io::RemoteMessagePort +*/ + +class _OSP_EXPORT_ MessagePortManager +{ +public: + /** + * Requests for a LocalMessagePort instance with the specified message port name. @n + * This method returns the same %LocalMessagePort instance if it has already been called with the same message port name. @n + * + * @since 2.0 + * + * @return A pointer to the LocalMessagePort instance, @n + * else @c null if it fails + * @param[in] localMessagePortName The name of a local message port + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c localMessagePortName is empty. + * @exception E_SYSTEM The method has failed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static LocalMessagePort* RequestLocalMessagePort(const Tizen::Base::String& localMessagePortName); + + /** + * Requests the RemoteMessagePort instance with the specified remote application ID and message port name. @n + * This method returns the same %RemoteMessagePort instance if it has already been called with the same remote application ID and message port name. + * + * @since 2.0 + * + * @return A pointer to the RemoteMessagePort instance, @n + * else @c null if it fails + * @param[in] remoteAppId The remote application ID + * @param[in] remoteMessagePortName The remote message port name + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The remote application ID or the remote message port name is empty. + * @exception E_OBJ_NOT_FOUND The message port of the target application is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static RemoteMessagePort* RequestRemoteMessagePort(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remoteMessagePortName); + + /** + * Requests for a trusted LocalMessagePort instance with the specified message port name. @n + * This method returns the same %LocalMessagePort instance if it has already been called with the same message port name. @n + * Communications over a trusted message port is allowed only if both the applications are signed with a certificate that is uniquely assigned to the developer. + * + * @since 2.0 + * + * @return A pointer to the trusted LocalMessagePort instance, @n + * else @c null if it fails + * @param[in] localMessagePortName The name of a local message port + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The @c localMessagePortName is empty. + * @exception E_SYSTEM The method has failed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static LocalMessagePort* RequestTrustedLocalMessagePort(const Tizen::Base::String& localMessagePortName); + + /** + * Requests the trusted RemoteMessagePort instance with the specified message port name. @n + * This method returns the same %RemoteMessagePort instance if it has already been called with the same remote application ID and message port name. @n + * This message port allows communications only if the applications are signed with the same certificate which is uniquely assigned to the developer. + * + * @since 2.0 + * + * @return A pointer to the trusted RemoteMessagePort instance, @n + * else @c null if it fails + * @param[in] remoteAppId The remote application ID + * @param[in] remoteMessagePortName The name of a remote message port + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either @c remoteAppId or @c remoteMessagePortName is empty. + * @exception E_OBJ_NOT_FOUND The message port of the target application is not found. + * @exception E_CERTIFICATE_VERIFICATION_FAILED The target application is not signed with the same certificate. + * @exception E_SYSTEM The method has failed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static RemoteMessagePort* RequestTrustedRemoteMessagePort(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remoteMessagePortName); + +private: + /** + * This default constructor is intentionally declared as private because this class cannot be constructed. + */ + MessagePortManager(void); + + /** + * This destructor is intentionally declared as private because this class cannot be constructed. + */ + virtual ~MessagePortManager(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + MessagePortManager(const MessagePortManager& messagePortManager); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + MessagePortManager& operator =(const MessagePortManager& messagePortManager); + +}; // MessagePortManager + +} } // Tizen::Io + +#endif //_FIO_MESSAGE_PORT_MANAGER_H_ diff --git a/inc/FIoMmcStorageManager.h b/inc/FIoMmcStorageManager.h new file mode 100755 index 0000000..c013b5a --- /dev/null +++ b/inc/FIoMmcStorageManager.h @@ -0,0 +1,205 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FIoMmcStorageManager.h +* @brief This is the header file for the %MmcStorageManager class. +* +* This header file contains the declarations of the %MmcStorageManager class. +*/ + +#ifndef _FIO_MMC_STORAGE_MANAGER_H_ +#define _FIO_MMC_STORAGE_MANAGER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** +* @class MmcStorageManager +* @brief This class provides methods to mount, unmount, and format external MMC. +* +* @since 2.0 +* +* @final This class is not intended for extension. +* +* The %MmcStorageManager class provides methods to mount, unmount, and format external MMC. +* +* @see IMmcStorageMountListener +* @see IMmcStorageFormatListener +*/ +class _OSP_EXPORT_ MmcStorageManager + : public Tizen::Base::Object +{ + +public: + /** + * Gets the MMC storage manager instance. + * + * @since 2.0 + * + * @return A pointer to %MmcStorageManager instance if this method is successful, @n + * else @c null + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static MmcStorageManager* GetInstance(void); + + /** + * @if VISPARTNER-MANUFACTURER + * Mounts file system of external MMC. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/systemsetting.read + * + * @return An error code + * @exception E_SUCCESS Mount operation is successfully started. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_OPERATION The external MMC has already been mounted. + * @exception E_SERVICE_BUSY One of mount, unmount and format operations is ongoing. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The directory path of the mounted external MMC can be obtained by calling + * Environment::GetExternalStoragePath(). + * @endif + */ + result Mount(void); + + /** + * @if VISPARTNER-MANUFACTURER + * Unmounts file system of external MMC. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/systemsetting.read + * + * @return An error code + * @exception E_SUCCESS Unmount operation is successfully started. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_OPERATION The external MMC has already been unmounted. + * @exception E_SERVICE_BUSY One of mount, unmount and format operations is ongoing. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @endif + */ + result Unmount(void); + + /** + * @if VISPARTNER-MANUFACTURER + * Formats file system of external MMC. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/systemsetting.read + * + * @return An error code + * @exception E_SUCCESS Format operation is successfully started. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_OPERATION The external MMC should be unmounted for format operation. + * @exception E_SERVICE_BUSY One of mount, unmount and format operations is ongoing. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @endif + */ + result Format(void); + + /** + * Adds the listener for receiving the result of external MMC mount or unmount operations. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The listener to add + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result AddMmcStorageMountListener(IMmcStorageMountListener& listener); + + /** + * Removes the listener for receiving the result of external MMC mount or unmount operations. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The listener to add + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result RemoveMmcStorageMountListener(IMmcStorageMountListener& listener); + + /** + * Adds the listener for receiving the result of external MMC format operation. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The listener to add + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result AddMmcStorageFormatListener(IMmcStorageFormatListener& listener); + + /** + * Removes the listener for receiving the result of external MMC format operation. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The listener to add + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result RemoveMmcStorageFormatListener(IMmcStorageFormatListener& listener); + +private: + /** + * This default constructor is intentionally declared as private to implement the Singleton semantic. + */ + MmcStorageManager(void); + + /** + * This destructor is intentionally declared as private to implement the Singleton semantic. + */ + virtual ~MmcStorageManager(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + MmcStorageManager(const MmcStorageManager& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + MmcStorageManager& operator =(const MmcStorageManager& rhs); + + static void InitSingleton(void); + + static void DestroySingleton(void); + +private: + static MmcStorageManager* __pMmcStorageManagerInstance; + friend class _MmcStorageManagerImpl; + class _MmcStorageManagerImpl* __pMmcStorageManagerImpl; + +}; // MmcStorageManager + +}} // Tizen::Io + +#endif // _FIO_MMC_STORAGE_MANAGER_H_ diff --git a/inc/FIoRegistry.h b/inc/FIoRegistry.h new file mode 100644 index 0000000..c6e448f --- /dev/null +++ b/inc/FIoRegistry.h @@ -0,0 +1,962 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoRegistry.h + * @brief This is the header file for the %Registry class. + * + * This header file contains the declarations of the %Registry class. + */ + +#ifndef _FIO_REGISTRY_H_ +#define _FIO_REGISTRY_H_ + +#include +#include +#include +#include +#include +#include + +namespace Tizen {namespace Base +{ +class String; +class ByteBuffer; +}} + +namespace Tizen { namespace Io +{ + +static const long REG_OPEN_READ_ONLY = 0x00000001L; +static const long REG_OPEN_READ_WRITE = 0x00000002L; +static const long REG_OPEN_CREATE = 0x00000004L; + +/** + * @class Registry + * @brief This class provides a mechanism to access and manipulate registry files. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Registry class provides a mechanism to access and manipulate registry files. + * + * For more information on the class features, + * see Io Guide. + * + * The following example demonstrates how to use the %Registry class. + * + * @code +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Io; +using namespace Tizen::App; + +void +RegistryTest() +{ + Registry reg; + String regPathName(L"regTest.ini"); + + // Section name + String sect1(L"section1"); + String sect2(L"section2"); + String sect3(L"section3"); + + // Entry name + String entry1(L"entry1"); + String entry2(L"entry2"); + + int iVal; + result r; + + r = reg.Construct(App::GetInstance()->GetAppDataPath() + regPathName, "a+"); + if (IsFailed(r)) + { + goto CATCH; + } + + // Create sections + r = reg.AddSection(sect1); + r = reg.AddSection(sect2); + r = reg.AddSection(sect3); + + // Add value: section1 { entry1 = 999 } + r = reg.AddValue(sect1, entry1, 999); + if (IsFailed(r)) + { + goto CATCH; + } + + // Change value: section1 { entry1 = 3 } + r = reg.SetValue(sect1, entry1, 3); + if (IsFailed(r)) + { + goto CATCH; + } + + // Add value: section2 { entry2 = 1.1234599 } + r = reg.AddValue(sect2, entry2, 1.1234599); + if (IsFailed(r)) + { + goto CATCH; + } + + // Get value: section1 { entry1 = ? } + r = reg.GetValue(sect1, entry1, iVal); + if (IsFailed(r)) + { + goto CATCH; + } + + // Write to the file + r = reg.Flush(); + if (IsFailed(r)) + { + goto CATCH; + } + + return; + +CATCH: + // Do some error handling + return; +} + * @endcode + */ + +class _OSP_EXPORT_ Registry + : public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + Registry(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Registry(void); + + /** + * @if OSPDEPREC + * @{ + * Initializes this instance of %Registry with the specified parameters. @n + * This method loads a registry file in the read-write mode. + * + * @if OSPCOMPAT + * @brief [Deprecated] [Compatibility] + * @endif + * @deprecated This method is deprecated. Instead of using this method, use Directory::Create(const Tizen::Base::String &dirPath, + * bool createParentDirectories=false) and Registry::Construct(const Tizen::Base::String& regPath, const Tizen::Base::String& openMode). + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] regPath The path of the registry file to open or create + * @param[in] createIfNotExist Set to @c true to create a registry file, @n + * else @c false to open an existing registry file + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified string of a file path is less + * than or equal to @c 0. @n + * - The translated overall length of the specified path exceeds the + * system limitation. @n + * - The specified path is invalid. @n + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_END_OF_FILE The file pointer has reached end-of-file. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_INVALID_FORMAT The input registry file contains '0x00' in the middle of the file. + * @exception E_PARSING_FAILED The method has failed to parse the registry file. + * @remarks To load the registry in read-only mode, use the Registry::Construct(const Tizen::Base::String& regPath, + * long openMode, long option) method with REG_OPEN_READ_ONLY as a value for the open mode flag. + * @} + * @endif + */ + result Construct(const Tizen::Base::String& regPath, bool createIfNotExist); + + /** + * @if OSPDEPREC + * @{ + * Initializes this instance of %Registry with the specified parameters. @n + * This method loads a registry file in the read-only or the read-write mode. + * + * @if OSPCOMPAT + * @brief [Deprecated] [Compatibility] + * @endif + * @deprecated This method is deprecated. Instead of using this method, use Directory::Create(const Tizen::Base::String &dirPath, + * bool createParentDirectories=false) and Registry::Construct(const Tizen::Base::String& regPath, const Tizen::Base::String& openMode). + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] regPath The path of the registry file to open or create + * @param[in] openMode An open mode flag @n + * Currently, the following flags can be used in combination with + * the logical OR operator: @n + * (1) REG_OPEN_READ_ONLY @n + * (2) REG_OPEN_READ_WRITE @n + * (3) REG_OPEN_READ_WRITE | REG_OPEN_CREATE + * @param[in] option This argument is reserved for further use @n It is recommended to use @c 0. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified string of a file path is less + * than or equal to @c 0. @n + * - The translated overall length of the specified path exceeds the + * system limitation. @n + * - The specified path is invalid. @n + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_END_OF_FILE The file pointer has reached end-of-file. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_INVALID_FORMAT The input registry file contains '0x00' in the middle of the file. + * @exception E_PARSING_FAILED The method has failed to parse the registry file. + * @} + * @endif + */ + result Construct(const Tizen::Base::String& regPath, long openMode, long option); + + /** + * Initializes this instance of %Registry with the specified parameters. @n + * This method opens an existing registry file or creates a new one according to the specified file opening mode. + * And this method loads data of the registry file to system memory and flushes the data to the storage when this instance + * is released or Registry::Flush() is called. + * + * @since 2.0 + * + * @return An error code + * @param[in] regPath The path of the registry file to open or create + * @param[in] pOpenMode The file opening mode @n + * It can be one of the following: + * - r : Open for reading. + * - r+: Open for reading and writing. + * - w : Open for writing. The registry file is created if it does not exist, + * otherwise it is truncated to zero length. + * - w+: Open for writing and reading. The registry file is created if it does not exist, + * otherwise it is truncated to zero length. + * - a : Open for appending. The registry file is created if it does not exist. + * - a+: Open for appending and reading. The registry file is created if it does not exist. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified @c regPath is equal to @c 0 or + * exceeds system limitations. @n + * - The combination of the specified @c pOpenMode is not allowed. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The specified @c regPath cannot be found. + * @exception E_INVALID_FORMAT Either of the following conditions has occurred: @n + * - The section or entry name of the registry file includes one of the following characters: + * '\0', '\n', '#' and '='. + * - The entry value of the registry file includes one of the following characters: + * '\0' and '\n'. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result Construct(const Tizen::Base::String& regPath, const char* pOpenMode); + + /** + * Initializes this instance of %Registry with the specified parameters. @n + * This method opens an existing secure registry file or creates a new one according to the specified file opening mode. + * And this method loads data of the secure registry file to system memory and flushes the data to the storage when this instance + * is released or Registry::Flush() is called. + * The contents written to the secure registry file is automatically encrypted and the contents read from the secure registry + * file is automatically decrypted by the platform. @n + * Applications using this method can access the same secure registry files that are created by other applications with the + * identical key value in same device. However, the secure registry files created by this method cannot be accessed in other devices. + * + * @since 2.0 + * + * @return An error code + * @param[in] regPath The path of the registry file to open or create + * @param[in] pOpenMode The file opening mode @n + * It can be one of the following: + * - r : Open for reading. + * - r+: Open for reading and writing. + * - w : Open for writing. The registry file is created if it does not exist, + * otherwise it is truncated to zero length. + * - w+: Open for writing and reading. The registry file is created if it does not exist, + * otherwise it is truncated to zero length. + * - a : Open for appending. The registry file is created if it does not exist. + * - a+: Open for appending and reading. The registry file is created if it does not exist. + * @param[in] secretKey A key used to encrypt data of a registry file or decrypt a secure registry file @n + * If a secure registry file is created with a specific key value, + * other applications can access the same secure registry file with the identical key value. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The overall length of the specified path is equal to @c 0 or + * exceeds system limitations. + * - The combination of the specified @c pOpenMode is not allowed. @n + * - The specified @c secretKey is incorrect or the secure registry file is corrupted. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_NOT_FOUND The specified @c regPath cannot be found. + * @exception E_INVALID_FORMAT Either of the following conditions has occurred: @n + * - The section or entry name of the registry file includes one of the following characters: + * '\0', '\n', '#' and '='. + * - The entry value of the registry file includes one of the following characters: + * '\0' and '\n'. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. @n + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result Construct(const Tizen::Base::String& regPath, const char* pOpenMode, const Tizen::Base::ByteBuffer& secretKey); + + /** + * Writes the current contents of a registry in memory to the non-volatile storage. @n + * If the secure mode is set to be @c true, the contents of the registry are automatically encrypted + * and saved by the platform. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_MAX_EXCEEDED The number of opened files has exceeded the maximum limit. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. @n + * - The memory is insufficient. + */ + result Flush(void); + + /** + * Creates the specified section then adds it into the registry. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of the specified string for a section name is less than + * or equal to @c 0. + * @exception E_SECTION_ALREADY_EXIST A section with the specified name already exists. + */ + result AddSection(const Tizen::Base::String& sectionName); + + /** + * Removes the section from %Registry. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of the specified string for a section is less than + * or equal to @c 0. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + */ + result RemoveSection(const Tizen::Base::String& sectionName); + + /** + * Gets all section names in the registry. + * + * @since 2.0 + * + * @return A list of section names @n + * If this method fails, @c null value is returned. @n + * The specific error code can be accessed using the GetLastResult() method. @n + * When there are no sections at all, the method returns an empty list instance. @n + * Use the Tizen::Base::Collection::ICollection::GetCount() method to check the number of elements in the list. + * @exception E_SUCCESS The method is successful. + * @remarks Do not forget to delete not only the returned IList instance, but also its + * contents by invoking IList::RemoveAll(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetAllSectionNamesN(void) const; + + /** + * Gets all entry names in the specified section of the registry. + * + * @since 2.0 + * + * @return A list of entry names @n + * If this method fails, @c null value is returned. @n + * When there are no entries at all, the method returns an empty list instance. @n + * Use the Tizen::Base::Collection::ICollection::GetCount() method to check the number of element in the list. + * @param[in] sectionName The section name + * @exception E_SUCCESS The method is successful. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_IO A system error has occurred. + * @remarks Do not forget to delete not only the returned IList instance, but also its + * contents by invoking IList::RemoveAll(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetAllEntryNamesN(const Tizen::Base::String& sectionName) const; + + /** + * Adds the name-value pair of type integer as an entry of the specific section. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name + * @param[in] value The @c int value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_ALREADY_EXIST The specified @c entryName already exists in this section. + */ + result AddValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, int value); + + /** + * Adds the name-value pair of type double as an entry of the specific section. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name + * @param[in] value The @c double value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_ALREADY_EXIST The specified @c entryName already exists in this section. + */ + result AddValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, double value); + + /** + * Adds the name-value pair of type float as an entry of the specific section. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name + * @param[in] value The @c float value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_ALREADY_EXIST The specified @c entryName already exists in this section. + */ + result AddValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, float value); + + /** + * Adds the name-value pair of type String as an entry of the specific section. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name + * @param[in] value The String value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0. + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_ALREADY_EXIST The specified @c entryName already exists in this section. + */ + result AddValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::String& value); + + /** + * Adds the name-value pair of type UuId as an entry for the specified section. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name + * @param[in] value The UuId value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_ALREADY_EXIST The specified @c entryName already exists in this section. + */ + result AddValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::UuId& value); + + /** + * Adds the name-value pair of type ByteBuffer as an entry for the specified section. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name + * @param[in] value The @c ByteBuffer value @n + * Note that, it should be constructed before being passed to the method. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_ALREADY_EXIST The specified @c entryName already exists in this section. + * @remarks Note that all the contents of @c ByteBuffer are saved as an entry value. + * That is, byte data from @c 0 up to the buffer limit is saved. + * @see Tizen::Base::ByteBuffer + */ + result AddValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::ByteBuffer& value); + + /** + * Gets the @c int value of the specified entry. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The name of entry where its value will be fetched + * @param[out] retVal The return value obtained from the registry + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @exception E_PARSING_FAILED The method has failed to parse the encoded entry value string, or the value is retrieved by using an incorrect data type. + * @exception E_DATA_NOT_FOUND The name-value pair has no value assigned (if the value is retrieved using the REGTYPE_STRING type, an empty string is returned even if no value is assigned). + */ + result GetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, int& retVal) const; + + /** + * Gets the @c double value of the specified entry. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The name of entry where its value will be fetched + * @param[out] retVal The return value obtained from the registry + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @exception E_PARSING_FAILED The method has failed to parse the encoded entry value string, or the value is retrieved by using an incorrect data type. + * @exception E_DATA_NOT_FOUND The name-value pair has no value assigned (if the value is retrieved using the REGTYPE_STRING type, an empty string is returned even if no value is assigned). + */ + result GetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, double& retVal) const; + + /** + * Gets the @c float value of the specified entry. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The name of entry where its value will be fetched + * @param[out] retVal The return value obtained from the registry + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @exception E_PARSING_FAILED The method has failed to parse the encoded entry value string, or the value is retrieved by using an incorrect data type. + * @exception E_DATA_NOT_FOUND The name-value pair has no value assigned (if the value is retrieved using the REGTYPE_STRING type, an empty string is returned even if no value is assigned). + */ + result GetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, float& retVal) const; + + /** + * Gets the String value of a specific entry. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The name of entry where its value will be fetched + * @param[out] retVal The return value obtained from the registry + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @exception E_PARSING_FAILED The method has failed to parse the encoded entry value string, or the value is retrieved by using an incorrect data type. + * @exception E_DATA_NOT_FOUND The name-value pair has no value assigned (if the value is retrieved using the REGTYPE_STRING type, an empty string is returned even if no value is assigned). + */ + result GetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, Tizen::Base::String& retVal) const; + + /** + * Gets the UuId value of the specified entry. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The name of entry where its value will be fetched + * @param[out] retVal The return value obtained from the registry + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @exception E_PARSING_FAILED The method has failed to parse the encoded entry value string, or the value is retrieved by using an incorrect data type. + * @exception E_DATA_NOT_FOUND The name-value pair has no value assigned (if the value is retrieved using the REGTYPE_STRING type, an empty string is returned even if no value is assigned). + */ + result GetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, Tizen::Base::UuId& retVal) const; + + /** + * Gets the ByteBuffer value of the specified entry. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The name of entry where its value will be fetched + * @param[out] retVal The return value obtained from the registry + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @exception E_PARSING_FAILED The method has failed to parse the encoded entry value string, or the value is retrieved by using an incorrect data type. + * @exception E_DATA_NOT_FOUND The name-value pair has no value assigned (if the value is retrieved using the REGTYPE_STRING type, an empty string is returned even if no value is assigned). + * @remarks The ByteBuffer should be constructed before passing it to the method. + * That is, the size of the binary data to be fetched should be decided beforehand. + * When the %ByteBuffer capacity is less than the actual binary data stored in the registry, + * this method reads the data as much as the %ByteBuffer capacity. The position of the %ByteBuffer and + * limit are not changed. When the %ByteBuffer capacity is greater than the actual data size, + * the method reads the whole data and adjusts the limit of the buffer accordingly. + * @see Tizen::Base::ByteBuffer + */ + result GetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, Tizen::Base::ByteBuffer& retVal) const; + + /** + * Modifies the value of the specified entry using the specified @c int value. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name to modify + * @param[in] newValue The @c int value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @remarks This method will not add a name-value pair as an entry of a specific section + * if no entry with the specified name exists. + * In such a case, it returns E_KEY_NOT_FOUND. Use AddValue() to insert a new entry. + * @see AddValue() + */ + result SetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, int newValue); + + /** + * Modifies the value of the specified entry using the specified @c double value. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name to modify + * @param[in] newValue The @c double value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @remarks This method will not add a name-value pair as an entry of a specific section + * if no entry with the specified name exists. + * In such a case, it returns E_KEY_NOT_FOUND. Use AddValue() to insert a new entry. + * @see AddValue() + */ + result SetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, double newValue); + + /** + * Modifies the value of the specified entry using the specified @c float value. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name to modify + * @param[in] newValue The @c float value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @remarks This method will not add a name-value pair as an entry of a specific section + * if no entry with the specified name exists. + * In such a case, it returns E_KEY_NOT_FOUND. Use AddValue() to insert a new entry. + * @see AddValue() + */ + result SetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, float newValue); + + /** + * Modifies the value of the specified entry using the specified String value. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name to modify + * @param[in] newValue The String value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0. + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @remarks This method will not add a name-value pair as an entry of a specific section + * if no entry with the specified name exists. + * In such a case, it returns E_KEY_NOT_FOUND. Use AddValue() to insert a new entry. + * @see AddValue() + */ + result SetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::String& newValue); + + /** + * Modifies the value of the specified entry using the specified UuID value. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name to modify + * @param[in] newValue The UuId value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @remarks This method will not add a name-value pair as an entry of a specific section if no + * entry with the specified name exists. + * In such a case, it returns E_KEY_NOT_FOUND. Use AddValue() to insert a new entry. + * @see AddValue() + */ + result SetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::UuId& newValue); + + /** + * Modifies the value of the specified entry using the specified ByteBuffer value. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name to modify + * @param[in] newValue The @c ByteBuffer value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either the length of the specified string for a section + * or an entry is less than or equal to @c 0, + * or a @c null value is passed. @n + * Note that, it is also possible that the data inside a registry instance is + * corrupted due to its usage in a multi-threaded environment without + * synchronization. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + * @remarks This method will not add a name-value pair as an entry of a specific section + * if no entry with the specified name exists. + * In such a case, it returns E_KEY_NOT_FOUND. Use AddValue() to insert a new entry. + * @see AddValue() + */ + result SetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::ByteBuffer& newValue); + + /** + * Removes the name-value pair entry from specific section. + * + * @since 2.0 + * + * @return An error code + * @param[in] sectionName The section name + * @param[in] entryName The entry name to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is less + * than or equal to @c 0. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName is not found within the registry. + * @exception E_KEY_NOT_FOUND The specified @c entryName is not found within the registry. + */ + result RemoveValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName); + + /** + * Removes the specified registry file. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] regPath The path of the registry file to remove + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified string of a file path is less + * than or equal to @c 0. @n + * - The translated overall length of the specified path exceeds the + * system limitation. @n + * - The specified path is invalid. @n + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. + */ + static result Remove(const Tizen::Base::String& regPath); + + /** + * Converts a normal registry file to a secure registry file. @n + * A secure registry file that is converted by this method can be shared among applications with the same key value. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatible applications. @n + * For more information, see @ref CompIoPathPage "here". + * @endif + * + * @return An error code + * @param[in] plainRegPath The normal (non-encrypted) registry file path + * @param[in] secureRegPath The secure (encrypted) registry file path to create + * @param[in] key A key that encrypts a secure registry file @n + * If the secure registry file is converted with a specific key value, + * applications can access the same secure registry file with the identical key value. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The length of the specified string of a file path is less + * than or equal to @c 0. @n + * - The translated overall length of the specified path exceeds the + * system limitation. @n + * - The specified path is invalid. @n + * @exception E_ILLEGAL_ACCESS Access is denied due to insufficient permission. + * @exception E_FILE_ALREADY_EXIST The specified file already exists. + * @exception E_FILE_NOT_FOUND An entry for the specified file or path cannot be found. + * @exception E_INVALID_FORMAT The input registry file contains '0x00' in the middle of the file. + * @exception E_PARSING_FAILED The method has failed to parse the registry file. + * @exception E_STORAGE_FULL The disk space is full. + * @exception E_IO Either of the following conditions has occurred: @n + * - An unexpected device failure has occurred as the media ejected suddenly. @n + * - %File corruption is detected. @n + * - The number of opened files has exceeded the maximum limit. + */ + static result ConvertToSecureRegistry(const Tizen::Base::String& plainRegPath, const Tizen::Base::String& secureRegPath, const Tizen::Base::ByteBuffer& key); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + Registry(const Registry& source); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + */ + Registry& operator =(const Registry& source); + + class _RegistryImpl* __pRegistryImpl; + + friend class _RegistryImpl; + +}; // Registry + +}} // Tizen::Io + +#endif //_FIO_REGISTRY_H_ + diff --git a/inc/FIoRemoteMessagePort.h b/inc/FIoRemoteMessagePort.h new file mode 100644 index 0000000..a2c735e --- /dev/null +++ b/inc/FIoRemoteMessagePort.h @@ -0,0 +1,205 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoRemoteMessagePort.h + * @brief This is the header file for the %RemoteMessagePort class. + * + * This header file contains declarations of the %RemoteMessagePort class. + */ +#ifndef _FIO_REMOTE_MESSAGE_PORT_H_ +#define _FIO_REMOTE_MESSAGE_PORT_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class LocalMessagePort; + +/** +* @class RemoteMessagePort +* @brief This class provides methods for sending messages to message ports of another application. +* +* @since 2.0 +* +* @final This class is not intended for extension. +* +* The %RemoteMessagePort class provides methods for sending messages to message ports of another application. +* +* For more information on the class features, +* see Message Port Communication. +* +* @see Tizen::Io::MessagePortManager +* @see Tizen::Io::LocalMessagePort +* +* @code +* +* #include +* #include +* +* using namespace Tizen::Base; +* using namespace Tizen::Base::Collection; +* using namespace Tizen::Io; +* +* class MyAppClass +* : public Tizen::Io::IMessagePortListener +* { +* public: +* result Initialize(void); +* virtual void OnMessageReceivedN(RemoteMessagePort* pRemoteMessagePort, IMap* pMessage); +* void GetOnlineFriends(void); +* +* private: +* LocalMessagePort* pLocalPort; +* RemoteMessagePort* pRemotePort; +* }; +* +* void +* MyAppClass::Initialize(void) +* { +* pLocalPort = MessagePortManager::RequestLocalMessagePort(L"PortA"); +* pLocalPort->AddMessagePortListener(*this); +* +* pRemotePort = MessagePortManager::RequestRemoteMessagePort(L"1234567890.RemoteApp", L"PortB"); +* } +* +* void +* MyAppClass::OnMessageReceivedN(RemoteMessagePort* pRemoteMessagePort, IMap* pMessage); +* { +* String* pValue = static_cast(pMessage->GetValue(L"Reply")); +* +* AppLog("My friend's name is %ls", pValue->GetPointer()); +* +* delete pMessage; +* } + +* void +* MyAppClass::GetOnlineFriends(void) +* { +* HashMap* pMap = new HashMap(SingleObjectDeleter); +* pMap->Construct(); +* +* pMap->Add(new String(L"Request"), new String(L"Friend")); +* +* pRemotePort->SendMessage(pLocalPort, pMap); +* +* delete pMap; +* } +* +* @endcode +*/ + +class _OSP_EXPORT_ RemoteMessagePort + : public Tizen::Base::Object +{ +public: + + /** + * Gets the name of a remote message port. + * + * @since 2.0 + * + * @return The name of a remote message port + */ + Tizen::Base::String GetName(void) const; + + /** + * Gets the ID of a remote application. + * + * @since 2.0 + * + * @return The ID of a remote application + */ + Tizen::App::AppId GetAppId(void) const; + + /** + * Checks whether an instance is a trusted message port or not. + * + * @since 2.0 + * + * @return @c true if the instance is a trusted message port, @n + * else @c false + */ + bool IsTrusted(void) const; + + /** + * Sends a message to the message port of a remote application. This method is used for the unidirectional communication. + * + * @since 2.0 + * + * @return An error code + * @param[in] pMessage A pointer to an argument map of key (String) and value (String or ByteBuffer) pair + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The message argument is not a map of key (String) and value (String or ByteBuffer) pair. + * @exception E_OBJ_NOT_FOUND The message port of the target application is not found. + * @exception E_SYSTEM The method has failed due to a severe system error. + */ + result SendMessage(const Tizen::Base::Collection::IMap* pMessage); + + + /** + * Sends a message to the message port of a remote application. This method is used for the bidirectional communication. + * + * @since 2.0 + * + * @return An error code + * @param[in] pLocalMessagePort The local message port + * @param[in] pMessage A pointer to an argument map of key (String) and value (String or ByteBuffer) pair + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The local message port is null. @n + * - The message argument is not a map of key (String) and value (String or ByteBuffer) pair. + * @exception E_OBJ_NOT_FOUND The message port of the target application is not found. + * @exception E_SYSTEM The method has failed due to a severe system error. + */ + result SendMessage(const LocalMessagePort* pLocalMessagePort, const Tizen::Base::Collection::IMap* pMessage); + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + RemoteMessagePort(void); + + /** + * This destructor is intentionally declared as private so that only the platform can delete an instance. + */ + virtual ~RemoteMessagePort(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + RemoteMessagePort(const RemoteMessagePort& localMessagePort); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + RemoteMessagePort& operator =(const RemoteMessagePort& localMessagePort); + + + friend class _RemoteMessagePortImpl; + + class _RemoteMessagePortImpl * __pRemoteMessagePortImpl; + +}; // RemoteMessagePort + +} } // Tizen::Io + +#endif //_FIO_REMOTE_MESSAGE_PORT_H_ diff --git a/inc/FIoSerialPort.h b/inc/FIoSerialPort.h new file mode 100644 index 0000000..646aec7 --- /dev/null +++ b/inc/FIoSerialPort.h @@ -0,0 +1,176 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Flora License, Version 1.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://floralicense.org/license/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoSerialPort.h + * @brief This is the header file for the %SerialPort class. + * + * This header file contains the declarations of the %SerialPort class. + */ + +#ifndef _FIO_SERIAL_PORT_H_ +#define _FIO_SERIAL_PORT_H_ + +#include + +namespace Tizen { namespace Io +{ + +class ISerialPortEventListener; + +/** + * @class SerialPort + * @brief This class provides an interface for controlling a serial port resource. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * @remarks The serial communication feature is reset when the USB connection is broken or a host device sends the + * deactivate command. Any serial port options are not supported by the current version. + * + * The %SerialPort class provides an interface for controlling a serial port resource. @n + * + * For more information on the class features, see Serial Port Communication. + * + * + * @see ISerialPortEventListener + * + * The following example demonstrates how to use the %SerialPort class. + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Io; + * + * class SerialRecv + * : public Tizen::Io::ISerialPortEventListener + * { + * void OnSerialPortDataReceivedN(Tizen::Base::ByteBuffer& byteBuffer) + * { + * //Read data. + * } + * + * void OnSerialPortErrorOccured(result r) + * { + * //Check error status. + * } + * } + * void + * MyClass::SerialPortSample(void) + * { + * SerialPort serialPort; + * ByteBuffer buf; + * String szMessage = L"Hello"; + * SerialRecv listener; + * + * buf.Construct(1024); + * buf.SetArray(szMessage.GetPointer(), 0, 6); + * buf.Flip(); + * + * //Construct serial port. + * serialPort.Construct(listener); + * + * //Write buf on output buffer. + * serialPort.Write(buf); + * + * } + * @endcode + * + * + * + */ +class _OSP_EXPORT_ SerialPort + : public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + SerialPort(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~SerialPort(void); + + /** + * Constructs a new serial port connection. @n + * If the specified port is open, E_SYSTEM is returned. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The serial port event listener + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(ISerialPortEventListener& listener); + + /** + * Writes data to the output buffer synchronously. + * + * @since 2.0 + * + * @return An error code + * @param[in] byteBuffer A reference to the buffer that contains the string data to write + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The buffer size has exceeded the maximum limit of the current device. + * @exception E_SYSTEM A system error has occurred. + * @see GetWriteBufferSize() + */ + result Write(const Tizen::Base::ByteBuffer& byteBuffer); + + /** + * Gets the size of the write buffer. + * + * @since 2.0 + * + * @return The size of the write buffer + * @remarks The size of the write buffer depends on the device. + */ + int GetWriteBufferSize(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + SerialPort(const SerialPort& serialPort); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + SerialPort& operator =(const SerialPort& serialPort); + +private: + class _SerialPortImpl* __pSerialPortImpl; + + friend class _SerialPortImpl; + +}; // SerialPort + +}} // Tizen::Io + +#endif // _FIO_SERIAL_PORT_H_ + diff --git a/inc/FIoServerChannel.h b/inc/FIoServerChannel.h new file mode 100644 index 0000000..f156ef2 --- /dev/null +++ b/inc/FIoServerChannel.h @@ -0,0 +1,212 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoServerChannel.h + * @brief This is the header file for the %ServerChannel class. + * + * This header file contains the declarations of the %ServerChannel class. + */ +#ifndef _FIO_SERVER_CHANNEL_H_ +#define _FIO_SERVER_CHANNEL_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ +/** +* @if OSPDEPREC +* @class ServerChannel +* @brief [Deprecated] This class provides methods to receive a request from a client application. +* +* @deprecated This class is deprecated. Instead of using this class, use LocalMessagePort, RemoteMessagePort, and MessagePortManager classes. +* @since 2.0 +* +* @final This class is not intended for extension. +* +* The %ServerChannel class provides methods to receive a request from a client application. An application can receive a request from another application using the %ServerChannel class. The instance of %ServerChannel is retrieved using ServerChannel::GetInstance(). +* @n +* For more information on the class features, see Channel Communication. +* +* The following example demonstrates how to use the %ServerChannel class. +* +* @code +* +* #include +* #include +* +* using namespace Tizen::Base; +* using namespace Tizen::Base::Collection; +* using namespace Tizen::Io; +* using namespace Tizen::App; +* +* class MyAppClass +* : public Tizen::Io::IChannelRequestEventListener +* { +* public: +* result Initialize(void); +* ArrayList* GetOnlineFriends(void); +* void virtual OnChannelRequestReceivedN(RequestId reqId, Tizen::Io::ServerChannel& serverChannel +* , const Tizen::Base::String& clientChannelId +* , Tizen::Base::Collection::IList* pArgs); +* }; +* +* result +* MyAppClass::Initialize(void) +* { +* result r = E_SUCCESS; +* +* // Sets the channel request event listener. +* ServerChannel::GetInstance()->SetChannelRequestEventListener(this); +* +* return r; +* } +* +* ArrayList* +* MyAppClass::GetOnlineFriends(void) +* { +* ArrayList* pDataList = new ArrayList(); +* pDataList->Construct(); + +* String* pData = new String(L"Tom"); +* String* pData2 = new String(L"Jane"); +* +* pDataList->Add(*pData); +* pDataList->Add(*pData2); +* +* return pDataList; +* } +* +* void +* MyAppClass::OnChannelRequestReceivedN(RequestId reqId, ServerChannel& serverChannel +* , const String& clientChannelId +* , IList* pArgs) +* { +* // Handles the request. +* ArrayList* pList = GetOnlineFriends(); +* +* // Sends the response to the client. +* serverChannel.SendResponse(clientChannelId, reqId, pList); +* +* // Removes the arguments. +* pList->RemoveAll(true); +* delete pList; +* +* pArgs->RemoveAll(true); +* delete pArgs; +* } +* +* @endcode +* @endif +*/ + +class _OSP_EXPORT_ ServerChannel + : public Tizen::Base::Object +{ +public: + /** + * Sets the request event listener. @n + * The listener is called when a request arrives. To reset the event listener, @c null must be passed. + * + * @since 2.0 + * + * @param[in] pRequestListener The request event listener + */ + void SetChannelRequestEventListener(IChannelRequestEventListener* pRequestListener); + + /** + * Gets the default server channel of the application. + * + * @since 2.0 + * + * @return A pointer to the %ServerChannel instance, @n + * else @c null if it fails + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + + static ServerChannel* GetInstance(void); + + /** + * Gets the specific server channel of the application. + * + * @since 2.0 + * + * @return A pointer to the %ServerChannel instance, @n + * else @c null if it fails + * @param[in] channelName The channel name + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static ServerChannel* GetInstance(const Tizen::Base::String& channelName); + + /** + * Sends a response to the specific client channel of an application specified by the clientChannelId. + * + * @since 2.0 + * + * @return An error code + * @param[in] clientChannelId The client channel ID which can be either application ID or appicationID.ChannelName + * @param[in] reqId The request ID + * @param[in] pArgs A pointer to an argument list of type String + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified client channel is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + result SendResponse(const Tizen::Base::String& clientChannelId, RequestId reqId, const Tizen::Base::Collection::IList* pArgs); + + +private: + /** + * This default constructor is intentionally declared as private to implement the Singleton semantic. + */ + ServerChannel(void); + + /** + * This destructor is intentionally declared as private to implement the Singleton semantic. + */ + virtual ~ServerChannel(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + ServerChannel(const ServerChannel& serverChannel); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + ServerChannel& operator =(const ServerChannel& serverChannel); + + static void InitSingleton(void); + + static void DestroySingleton(void); + + friend class _ServerChannelImpl; + + class _ServerChannelImpl * __pServerChannelImpl; + + static ServerChannel* __pServerChannelInstance; +}; // ServerChannel + +} } // Tizen::Io + +#endif //_FIO_SERVER_CHANNEL_H_ diff --git a/inc/FIoSqlStatementBuilder.h b/inc/FIoSqlStatementBuilder.h new file mode 100644 index 0000000..f629799 --- /dev/null +++ b/inc/FIoSqlStatementBuilder.h @@ -0,0 +1,202 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoSqlStatementBuilder.h + * @brief This is the header file for the %SqlStatementBuilder class. + * + * This header file contains the declarations of the %SqlStatementBuilder class. + */ + +#ifndef _FIO_SQL_STATEMENT_BUILDER_H_ +#define _FIO_SQL_STATEMENT_BUILDER_H_ + +#include + +namespace Tizen { namespace Base +{ +class String; +namespace Collection +{ +class IList; +class IMap; +} +}} + +namespace Tizen { namespace Io +{ + +/** + * @class SqlStatementBuilder + * @brief This class provides methods for building SQL statement. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %SqlStatementBuilder class provides methods for building SQL statement. + */ +class _OSP_EXPORT_ SqlStatementBuilder + : public Tizen::Base::Object +{ + +public: + /** + * Creates SQL SELECT statement. + * + * @since 2.0 + * + * @return A created SQL SELECT statement, @n + * else an empty string in case of failure + * @param[in] table A table name to query from + * @param[in] pColumnList A list of column names to query @n + * The type of objects contained in the specified @c pColumnList must be + * Tizen::Base::String class. + * If it is null, all columns are returned in result set. + * @param[in] pWhere A filter to select desired rows to query @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * @param[in] pOrder Sorting order of rows to query @n + * It is an SQL 'ORDER BY' clause excluding the 'ORDER BY' itself. + * @param[in] pLimit Limitation of the number of rows to query @n + * It is the SQL 'LIMIT' clause excluding the 'LIMIT' itself. + * @param[in] pGroup A filter to select a column grouping rows to query @n + * It is the SQL 'GROUP BY' clause excluding the 'GROUP BY' itself. + * @param[in] pHaving A filter for the group @n + * It is the SQL 'HAVING' clause excluding the 'HAVING' itself. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: + * - The specified @c pColumnList is empty. + * - The specified @c pOrder is null and @c pLimit is not null. + * - The specified @c pGroup is null and @c pHaving is not null. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the value specified in the @c pWhere is string, the value must be wrapped in + * single quotes. Otherwise it is not needed to wrap the numeric value in single quotes. + * For more information on the SQL statement, see SQLite SQL documents. + */ + static Tizen::Base::String CreateSelectStatement(const Tizen::Base::String& table, const Tizen::Base::Collection::IList* pColumnList, + const Tizen::Base::String* pWhere, const Tizen::Base::String* pOrder = null, const Tizen::Base::String* pLimit = null, + const Tizen::Base::String* pGroup = null, const Tizen::Base::String* pHaving = null); + + /** + * Creates SQL INSERT statement. + * + * @since 2.0 + * + * @return A created SQL INSERT statement, @n + * else an empty string in case of failure @n + * @param[in] table A table name to insert + * @param[in] insertMap Column-value pairs to insert @n + * The type of objects contained in the specified @c insertMap must be + * Tizen::Base::String class. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c insertMap is empty. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the value specified in the @c insertMap is string, the value must be wrapped in + * single quotes. Otherwise it is not needed to wrap the numeric value in single quotes. + * For more information on the SQL statement, see SQLite SQL documents. + */ + static Tizen::Base::String CreateInsertStatement(const Tizen::Base::String& table, const Tizen::Base::Collection::IMap& insertMap); + + /** + * Creates SQL UPDATE statement. + * + * @since 2.0 + * + * @return A created SQL UPDATE statement, @n + * else an empty string in case of failure @n + * @param[in] table A table name to update + * @param[in] updateMap Column-value pairs to update @n + * The type of objects contained in the specified @c updateMap must be + * Tizen::Base::String class. + * @param[in] pWhere A filter to select desired rows to update @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c updateMap is empty. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the value specified in the @c pWhere or @c updateMap is string, the value must be wrapped in + * single quotes. Otherwise it is not needed to wrap the numeric value in single quotes. + * For more information on the SQL statement, see SQLITE SQL documents. + */ + static Tizen::Base::String CreateUpdateStatement(const Tizen::Base::String& table, const Tizen::Base::Collection::IMap& updateMap, + const Tizen::Base::String* pWhere); + + /** + * Creates SQL DELETE statement. + * + * @since 2.0 + * + * @return A created SQL DELETE statement, @n + * else an empty string in case of failure @n + * @param[in] table A table name to query + * @param[in] pWhere A filter to select desired rows to delete @n + * It is an SQL 'WHERE' clause excluding the 'WHERE' itself such as + * column1 = 'stringValue' AND column2 = numericValue. + * If it is null, all rows are deleted. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks If the value specified in the @c pWhere is string, the value must be wrapped in + * single quotes. Otherwise it is not needed to wrap the numeric value in single quotes. + * For more information on the SQL statement, see SQLITE SQL documents. + */ + static Tizen::Base::String CreateDeleteStatement(const Tizen::Base::String& table, const Tizen::Base::String* pWhere); + +private: + /** + * This default constructor is intentionally declared as private because this class cannot be constructed. + * + * @since 2.0 + */ + SqlStatementBuilder(void); + + /** + * This destructor is intentionally declared as private because this class cannot be constructed. + * + * @since 2.0 + */ + virtual ~SqlStatementBuilder(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * @remarks This constructor is hidden. + */ + SqlStatementBuilder(const SqlStatementBuilder& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * @remarks This operator is hidden. + */ + SqlStatementBuilder& operator =(const SqlStatementBuilder& rhs); + + class _SqlStatementBuilderImpl* __pSqlStatementBuilderImpl; + +}; // SqlStatementBuilder + +}} // Tizen::Io + +#endif // _FIO_SQL_STATEMENT_BUILDER_H_ + diff --git a/inc/FLclCalendar.h b/inc/FLclCalendar.h new file mode 100644 index 0000000..14b09c6 --- /dev/null +++ b/inc/FLclCalendar.h @@ -0,0 +1,1145 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclCalendar.h + * @brief This is the header file for the %Calendar class. + * + * This header file contains the declarations of the %Calendar class. + * + */ +#ifndef _FLCL_CALENDAR_H_ +#define _FLCL_CALENDAR_H_ + +#include +#include +#include + +namespace Tizen { namespace Locales +{ +/** + * @class Calendar + * @brief This class provides methods for displaying a calendar. + * + * @since 2.0 + * + * The %Calendar class is an abstract base class for displaying a calendar. It is used to convert between the Tizen::Base::DateTime instance and a set of time fields, such as TIME_FIELD_YEAR, TIME_FIELD_MONTH, and TIME_FIELD_DAY_OF_MONTH. + * Subclasses of %Calendar interpret %Tizen::Base::DateTime according to the rules of a specific calendar system. GregorianCalendar is commonly used. + * + * For more information on the class features, see Calendar. + * + * @see Tizen::Locales::TimeZone + * + * The following example demonstrates how to use the %Calendar class to set or add the time field. + * + @code + * + #include + #include + + using namespace Tizen::Base; + using namespace Tizen::Locales; + + void + MyClass::CalendarExample(void) + { + int offset = 60; + String timeZoneName(L"Europe/Paris"); + TimeZone timeZone(offset, timeZoneName); + + Calendar* pCalendar = Calendar::CreateInstanceN(timeZone, CALENDAR_GREGORIAN); + pCalendar->SetTime(2012,7,18); + + // Increase one day. The date will be 2012/7/19 + pCalendar->AddTimeField(TIME_FIELD_DAY_OF_MONTH, 1); + + // Decrease two months. The date will be 2012/5/19 + pCalendar->AddTimeField(TIME_FIELD_MONTH, -2); + + delete pCalendar; + } + @endcode + */ +#define GET_TIME_FIELD_MASK(X) (static_cast(1 << (X))) +/** +* @enum TimeField +* +* Defines the time fields for date and time. @n +* This enum is used in %Calendar. +* +* @since 2.0 +*/ +enum TimeField +{ + TIME_FIELD_ERA, /**< Era : 0 - BC, 1 - AD */ + TIME_FIELD_YEAR, /**< Year : 1-based */ + TIME_FIELD_MONTH, /**< Month : 1-based (1~13)*/ + TIME_FIELD_WEEK_OF_YEAR, /**< Week of Year : 1-based (1~53) */ + TIME_FIELD_WEEK_OF_MONTH, /**< Week of Month : 1-based (1~5, may be specified as 0) */ + TIME_FIELD_DAY_OF_MONTH, /**< Date : 1-based (1~31) */ + TIME_FIELD_DAY_OF_YEAR, /**< Day of Year : 1-based (1~366) */ + TIME_FIELD_DAY_OF_WEEK, /**< Day of Week : 1-based (1~7) */ + TIME_FIELD_DAY_OF_WEEK_IN_MONTH, /**< Day of Week in Month : 1-based (1~5, may be specified as -1) */ + TIME_FIELD_AM_PM, /**< AmPm : 0 - AM, 1 - PM */ + TIME_FIELD_HOUR, /**< Hour : 0-based (0~11) */ + TIME_FIELD_HOUR_OF_DAY, /**< Hour of Day : 0-based (0~23) */ + TIME_FIELD_MINUTE, /**< Minute : 0-based (0~59) */ + TIME_FIELD_SECOND, /**< Second : 0-based (0~59) */ + TIME_FIELD_MILLISECOND, /**< Millisecond : 0-based (0~999) */ + TIME_FIELD_ZONE_OFFSET, /**< Time Zone Offset : 0-based (-43200000~54000000 in milliseconds) */ + TIME_FIELD_DST_OFFSET, /**< Daylight Saving Offset : 0-based (0~3600000 in milliseconds)*/ + TIME_FIELD_FIELD_COUNT /**< The number of time field */ +}; + +class _OSP_EXPORT_ Calendar + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Calendar(void); + + /** + * Adds the specified amount to the given time field, based on the calendar rules. @n + * It is equivalent to calling SetTimeField(field, GetTimeField(field)+amount) with two adjustments. @n + * + * @b Add @b Rule1: The value of the time field @c field after the call minus the value of the field + * before the call is delta modulo any overflow that has occurred in the field. + * Overflow occurs when a time field value exceeds its range and, as a result, the next larger field + * is incremented or decremented and the field value is adjusted back into its range. @n + * + * @b Add @b Rule2: If a smaller field is expected to be invariant, but it is impossible for it to be + * equal to its prior value because of changes in its minimum or maximum value after the time field @c field + * is changed, then its value is adjusted to be as close as possible to its expected value. @n + * + * A smaller field represents a smaller unit of time. TIME_FIELD_HOUR is a smaller field than TIME_FIELD_DAY_OF_MONTH. + * No adjustment is made to smaller fields that are not expected to be invariant. + * The calendar system determines what fields are expected to be invariant. + * + * In addition, this method forces re-computation of the calendar's milliseconds and + * all time fields immediately. @n + * + * For example, consider a GregorianCalendar set to Oct 31, 2004. + * Calling AddTimeField(TIME_FIELD_MONTH, 13) sets the calendar to Nov 30, 2005. @n + * The TIME_FIELD_MONTH field is set to NOVEMBER by @b Rule1, since adding 13 months to October gives the + * November of the next year. + * Since, the TIME_FIELD_DAY_OF_MONTH cannot be 31 in November in a %GregorianCalendar, the TIME_FIELD_DAY_OF_MONTH is set to 30 by @b Rule2. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCalendarAddTimeFieldPage "here". + * @endif + * + * @return An error code + * @param[in] field The time field + * @param[in] amount The amount to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + */ + virtual result AddTimeField(TimeField field, int amount) = 0; + + /** + * @if OSPCOMPAT + * @page CompCalendarAddTimeFieldPage Compatibility for AddTimeField() + * @section CompCalendarAddTimeFieldIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_INVALID_STATE if the time field is invalid. + * + * @section CompCalendarAddTimeFieldSolutionSection Resolutions + * This issue has been resolved in Tizen. @n + * + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the time field is invalid. + * @endif + */ + + /** + * Compares the current instance of %Calendar with the specified instance. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCalendarAfterPage "here". + * @endif + * + * @return An error code + * @param[in] otherCalendar The instance of %Calendar to compare + * @param[out] after Set to @c true if the current instance of %Calendar is after the specified instance of %Calendar, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c otherCalendar is invalid. + * @exception E_INVALID_STATE In this method, the time fields of this instance are calculated. @n + * If any time field value previously set is invalid, this exception is returned. + * @exception E_OUT_OF_RANGE In this method, the time fields of this instance are calculated. @n + * If the value of the time fields goes out of range, this exception is returned. + */ + result After(const Calendar& otherCalendar, bool& after); + + /** + * @if OSPCOMPAT + * @page CompCalendarAfterPage Compatibility for After() + * @section CompCalendarAfterIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_INVALID_STATE and E_OUT_OF_RANGE if the instance of %Calendar to be compared is invalid. + * + * @section CompCalendarAfterSolutionSection Resolutions + * This issue has been resolved in Tizen. @n + * + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the instance of %Calendar to be compared is invalid. + * -# The method returns E_INVALID_STATE if any time field value previously set is invalid. + * -# The method returns E_OUT_OF_RANGE if the value of the time fields goes out of range. + * @endif + */ + + /** + * Compares the current instance of %Calendar with the specified instance. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCalendarBeforePage "here". + * @endif + * + * @return An error code + * @param[in] otherCalendar The instance of %Calendar to compare + * @param[out] before Set to @c true if the current instance of %Calendar is before the specified instance of %Calendar, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c otherCalendar is invalid. + * @exception E_INVALID_STATE In this method, the time fields of this instance are calculated. @n + * If any time field value previously set is invalid, this exception is returned. + * @exception E_OUT_OF_RANGE In this method, the time fields of this instance are calculated. @n + * If the value of the time fields goes out of range, this exception is returned. + */ + result Before(const Calendar& otherCalendar, bool& before); + + /** + * @if OSPCOMPAT + * @page CompCalendarBeforePage Compatibility for Before() + * @section CompCalendarBeforeIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_INVALID_STATE and E_OUT_OF_RANGE if the instance of %Calendar to be compared is invalid. + * + * @section CompCalendarBeforeSolutionSection Resolutions + * This issue has been resolved in Tizen. @n + * + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the instance of %Calendar to be compared is invalid. + * -# The method returns E_INVALID_STATE if any time field value previously set is invalid. + * -# The method returns E_OUT_OF_RANGE if the value of the time fields goes out of range. + * @endif + */ + + /** + * Clears all the time fields and sets it to @c 0. @n + * Zero is not the default value for each field. It means the field is cleared. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + */ + result Clear(void); + + /** + * Clears the specified time field and sets it to @c 0. @n + * Zero is not the default value for each field. It means the field is cleared. + * + * @since 2.0 + * + * @return An error code + * @param[in] field The time field to clear + * @exception E_SUCCESS The method is successful. + */ + result Clear(TimeField field); + + /** + * Checks whether the value of the specified instance of Tizen::Base::Object is equal to the value of the current instance of %Calendar. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance of Tizen::Base::Object is equal to the value of the current instance of %Calendar, @n + * else @c false + * @param[in] obj An instance of Tizen::Base::Object to compare + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Rolls up or down as per the specified @c amount in the specified time field without changing the larger fields (for example, TIME_FIELD_YEAR field cannot be changed when the input field is TIME_FIELD_MONTH). @n + * If the specified @c amount is negative, the amount value is deducted from the specified time field value. + * In this method, the time field of this instance is operated upon. If the value of the specified @c field goes out of range, E_OUT_OF_RANGE is returned. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCalendarRollPage "here". + * @endif + * + * @return An error code + * @param[in] field The time field to roll + * @param[in] amount The amount to add to the time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid (for example, TIME_FIELD_DST_OFFSET, TIME_FIELD_ZONE_OFFSET). + * @exception E_OUT_OF_RANGE In this method, the time fields of this instance are calculated. @n + * If the value of the time fields goes out of range, this exception is returned. + */ + virtual result Roll(TimeField field, int amount); + + /** + * @if OSPCOMPAT + * @page CompCalendarRollPage Compatibility for Roll() + * @section CompCalendarRollIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_INVALID_STATE if the time field is invalid. + * + * @section CompCalendarRollSolutionSection Resolutions + * This issue has been resolved in Tizen. @n + * + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the time field is invalid. + * @endif + */ + + /** + * Sets the specified time field with the specified @c value. @n + * This sets an internal member variable to indicate that the field has been changed. + * Although the time field is changed, the milliseconds of %Calendar are not recomputed + * until GetTimeField(), GetTime(), or GetTimeInMillisec() is called. + * Thus, even if you call this method several times, unnecessary multiple computations are not triggered. @n + * + * As a result of changing a field using SetTimeField(), other fields may also change + * depending on the field, the field value, and the calendar system. @n + * + * For example, consider a GregorianCalendar set to Oct. 31, 2004. + * Calling SetTimeField(TIME_FIELD_MONTH, NOVEMBER) sets the calendar to Nov 31, 2004. @n + * But, if you call GetTime(), then Dec 1, 2004 is returned because Nov 31, 2004 does not exist. + * However, a call to SetTimeField(TIME_FIELD_MONTH, SEPTEMBER) before a call to GetTime() sets the calendar + * to Sep 30, 2004, since no re-computation has occurred after the first call to SetTimeField(). + * + * The value of field is not affected by it being local time or UTC time. + * The value is only overwritten. + * + * @since 2.0 + * + * @return An error code + * @param[in] field The time field to set + * @param[in] value The value to set + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The value is out of range in lenient mode. + * @exception E_INVALID_ARG The specified @c field is invalid. + */ + result SetTimeField(TimeField field, int value); + + /** + * Sets the first day of the week. + * + * @since 2.0 + * + * @return An error code + * @param[in] dayOfWeek The value to set as the first day of the week + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c dayOfWeek is invalid. + */ + result SetFirstDayOfWeek(DayOfWeek dayOfWeek); + + /** + * Sets the leniency of date and time interpretations. + * + * @since 2.0 + * + * @return An error code + * @param[in] lenient Set to @c true if the date and time interpretation is set to lenient, @n + * else @c false + * @exception E_SUCCESS The method is successful. + */ + result SetLenient(bool lenient); + + /** + * Sets the minimal days required in the first week. + * + * @since 2.0 + * + * @return An error code + * @param[in] value The minimal days required in the first week + * @exception E_SUCCESS The method is successful. + */ + result SetMinDaysInFirstWeek(short value); + + /** + * Sets the value of year, month, day, hour, minute, and seconds. @n + * The date and time are local time. + * + * @since 2.0 + * + * @return An error code + * @param[in] year The value to set for year + * @param[in] month The value to set for month @n + * The indexing is 1-based. Therefore, 1 means January. + * @param[in] day The value to set for day + * @param[in] hour The value to set for hour + * @param[in] minute The value to set for minute + * @param[in] second The value to set for second + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE A time field or its value is out of range in lenient mode. + */ + result SetTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0); + + /** + * Sets the calendar's current time with the specified Tizen::Base::DateTime. + * + * @since 2.0 + * + * @return An error code + * @param[in] dateTime The Tizen::Base::DateTime instance to set + * @exception E_SUCCESS The method is successful. + * @remarks The time specified is the local time. + */ + result SetTime(const Tizen::Base::DateTime& dateTime); + + /** + * Sets the current time of this %Calendar instance with the specified value. + * + * @since 2.0 + * + * @return An error code + * @param[in] millisec The new time in milliseconds from the starting day (Jan 1, 1.) + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE A time field or its value is out of range. + */ + result SetTimeInMillisec(long long millisec); + + /** + * Sets the time zone of the calendar to the specified time zone. + * + * @since 2.0 + * + * @return An error code + * @param[in] timeZone The time zone to set + * @exception E_SUCCESS The method is successful. + */ + result SetTimeZone(const TimeZone& timeZone); + + /** + * Gets the actual maximum value that the specified field can have, given the current date. @n + * For example, if the current date is "Feb 10, 2004" and the time field specified is TIME_FIELD_DAY_OF_MONTH, then the actual + * maximum value for this time field is 29. + * + * @since 2.0 + * + * @return An integer value indicating the actual maximum value + * @param[in] field The time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetActualMaxTimeField(TimeField field) const; + + /** + * Gets the actual minimum value that the specified time field can have, given the current date. @n + * For the Gregorian calendar, this is the same as GetMinTimeField() and + * GetGreatestMinTimeField(). + * + * @since 2.0 + * + * @return An integer value indicating the actual minimum value + * @param[in] field The time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetActualMinTimeField(TimeField field) const; + + /** + * Gets the value of the first day of the week. @n + * For example, in USA, the first day of the week is SUNDAY. But, it is MONDAY in France. + * + * @since 2.0 + * + * @return An integer value indicating the first day of the week, @n + * else @c -1 if the method fails + */ + int GetFirstDayOfWeek(void) const; + + /** + * Gets the greatest minimum value that the specified time field can have. + * + * @since 2.0 + * + * @return An integer value indicating the greatest minimum value for the specified time field + * @param[in] field The time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetGreatestMinTimeField(TimeField field) const; + + /** + * Gets the least maximum value that the specified time field can have. + * + * @since 2.0 + * + * @return An integer value indicating the least maximum value for the specified time field + * @param[in] field The time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetLeastMaxTimeField(TimeField field) const; + + /** + * Gets the maximum value that the specified time field can have. + * + * @since 2.0 + * + * @return An integer value indicating the maximum value for the specified time field + * @param[in] field The time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetMaxTimeField(TimeField field) const; + + /** + * Gets the minimum value that the specified time field can have. + * + * @since 2.0 + * + * @return An integer value indicating the minimum value for the specified time field + * @param[in] field The time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetMinTimeField(TimeField field) const; + + /** + * Gets the minimum number of days required in the first week of the year. @n + * For example, if the first week is defined as the one that contains the first day of + * the first month of a year, this method returns @c 1. + * + * @since 2.0 + * + * @return An integer value indicating the minimum number of days required in the first week + */ + int GetMinDaysInFirstWeek(void) const; + + /** + * Gets the date and time of the current instance of %Calendar. + * + * @since 2.0 + * + * @return An instance of Tizen::Base::DateTime with the current time in local time + * @remarks The time specified is local time. + */ + Tizen::Base::DateTime GetTime(void) const; + + /** + * Gets the value of the specified time field. + * + * @since 2.0 + * + * @return An integer value indicating the value of the specified time field + * + * @param[in] field The given time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks This method is semantically const, but may alter the instance in memory. + * All fields are re-computed if any field is invalid. + * The specific error code can be accessed using the GetLastResult() method. + */ + int GetTimeField(TimeField field) const; + + /** + * Gets the current time of the instance in the @c long format. + * + * @since 2.0 + * + * @return An error code + * @param[out] millisec The current time in milliseconds from starting day (Jan 1, 1.) + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE In this method, the time fields of this instance are calculated. @n + * If any time field value previously set is invalid, this exception is returned. + * @exception E_OUT_OF_RANGE The value of the argument is out of the valid range defined by the method. + */ + result GetTimeInMillisec(long long& millisec) const; + + /** + * Gets a reference to the time zone owned by this instance of %Calendar. + * + * @since 2.0 + * + * @return The TimeZone instance associated with the current instance of %Calendar + * @remarks The returned reference is valid only until the SetTimeZone() method is called or this instance of %Calendar is destroyed. + * @see SetTimeZone() + */ + TimeZone GetTimeZone(void) const; + + /** + * Gets the calendar type of the current instance of %Calendar. + * + * @since 2.0 + * + * @return An instance of CalendarType representing the calendar type of the current instance of %Calendar @n + * For example, CALENDAR_GREGORIAN. + */ + virtual CalendarType GetType(void) const = 0; + + /** + * Checks whether the current date for the instance of %Calendar is in Daylight Saving Time (DST). + * + * @since 2.0 + * + * @return An error code + * @param[out] isInDst Set to @c true if the current date is in DST, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE In this method, the time fields of this instance are calculated. @n + * If any time field value previously set is invalid, this exception is returned. + * @exception E_OUT_OF_RANGE A time field or its value is out of range. @n + * In this method, the time fields of this instance are calculated. If the value of the time fields goes out of range, this exception is returned. + */ + virtual result IsInDst(bool& isInDst) const = 0; + + /** + * Checks whether the date and time interpretation is lenient. + * + * @since 2.0 + * + * @return @c true if the date and time interpretation is set to lenient, @n + * else @c false + */ + bool IsLenient(void) const; + + /** + * Checks whether the specified time field has a value. + * + * @since 2.0 + * + * @return @c true if the specified time field has a value, @n + * else @c false + * @param[in] field The time field + */ + bool IsSet(TimeField field) const; + + /** + * Creates an instance of %Calendar of the specified type with the GMT time zone and the system locale. @n + * The time zone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the locale. + * + * @since 2.0 + * + * @return A pointer to the created %Calendar instance, @n + * else @c null if the method fails + * @param[in] calendarType The type of calendar @n + * Default calendar is the Gregorian calendar (CALENDAR_GREGORIAN). + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Calendar* CreateInstanceN(CalendarType calendarType = CALENDAR_GREGORIAN); + + /** + * Creates an instance of %Calendar of the specified type with the specified time zone and the system locale. @n + * The @c timeZone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the locale. + * + * @since 2.0 + * + * @return A pointer to the created %Calendar instance, @n + * else @c null if the method fails + * @param[in] timeZone An instance of TimeZone + * @param[in] calendarType The type of calendar @n + * Default calendar is the Gregorian calendar (CALENDAR_GREGORIAN). + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Calendar* CreateInstanceN(const TimeZone& timeZone, CalendarType calendarType = CALENDAR_GREGORIAN); + + /** + * Creates an instance of %Calendar of the specified type with the specified @c locale and the GMT time zone. @n + * The time zone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCalendarCreateInstanceNPage "here". + * @endif + * + * @return A pointer to the created %Calendar instance, @n + * else @c null if the method fails + * @param[in] locale The locale for whose country the %Calendar instance is needed + * @param[in] calendarType The type of calendar @n + * Default calendar is the Gregorian calendar (CALENDAR_GREGORIAN). + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Calendar* CreateInstanceN(const Locale& locale, CalendarType calendarType = CALENDAR_GREGORIAN); + + /** + * Creates an instance of %Calendar of the specified type with the specified time zone and @c locale. @n + * The @c timeZone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCalendarCreateInstanceNPage "here". + * @endif + * + * @return A pointer to the created %Calendar instance, @n + * else @c null if the method fails + * @param[in] timeZone An instance of TimeZone + * @param[in] locale The locale for whose country the %Calendar instance is needed + * @param[in] calendarType The type of calendar @n + * Default calendar is the Gregorian calendar (CALENDAR_GREGORIAN). + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Calendar* CreateInstanceN(const TimeZone& timeZone, const Locale& locale, CalendarType calendarType = CALENDAR_GREGORIAN); + + /** + * @if OSPCOMPAT + * @page CompCalendarCreateInstanceNPage Compatibility for CreateInstanceN() + * @section CompCalendarCreateInstanceNIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the locale is invalid. + * + * @section CompCalendarCreateInstanceNSolutionSection Resolutions + * This issue has been resolved in Tizen. @n + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the locale is invalid. + * @endif + */ + +protected: + /** + * @enum AmPm + * + * Defines the AM/PM mode. @n + * This is a.m./p.m. The indexing is 0-based. + * + * @since 2.0 + */ + enum AmPm + { + AM, /**< The time is in A.M */ + PM /**< The time is in P.M */ + }; + + /** + * @enum CalendarLimitType + * + * Defines the calendar limitations. + * + * @since 2.0 + */ + enum CalendarLimitType + { + CALENDAR_LIMIT_MINIMUM = 0, /**< The minimum limit */ + CALENDAR_LIMIT_GREATEST_MINIMUM, /**< The greatest minimum limit */ + CALENDAR_LIMIT_LEAST_MAXIMUM, /**< The least maximum limit */ + CALENDAR_LIMIT_MAXIMUM, /**< The maximum limit */ + CALENDAR_LIMIT_COUNT /**< The number of limit type */ + }; + + /** + * @enum StampValue + * + * Defines the stamp value. + * + * @since 2.0 + */ + enum StampValue + { + UNSET = 0, /**< Unset */ + COMPUTED, /**< Computed */ + MINIMUM_USER_STAMP /**< Minimum user stamp */ + }; + + /** + * This is the default constructor for this class. @n + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @see Construct() + */ + Calendar(void); + + /** + * Initializes this instance of %Calendar. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + */ + result Construct(void); + + /** + * Initializes this instance of %Calendar with the specified parameter. + * + * @since 2.0 + * + * @return An error code + * @param[in] calendar The %Calendar instance to copy + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * + */ + result Construct(const Calendar& calendar); + + /** + * Initializes this instance of %Calendar with the specified time zone and @c locale. @n + * The @c timeZone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCalendarConstructPage "here". + * @endif + * + * @return An error code + * @param[in] timeZone An instance of TimeZone + * @param[in] locale An instance of Locale + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c locale is invalid. + */ + result Construct(const Tizen::Locales::TimeZone& timeZone, const Locale& locale); + + /** + * @if OSPCOMPAT + * @page CompCalendarConstructPage Compatibility for Construct() + * @section CompCalendarConstructIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the locale is invalid. + * + * @section CompCalendarConstructSolutionSection Resolutions + * This issue has been resolved in Tizen. @n + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the locale is invalid. + * @endif + */ + + /** + * Rolls up or down with a single unit of time on a given time field without changing larger fields. @n + * When rolling on the MONTH field, other fields such as DATE field might conflict + * and needs to be changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] field The time field to change + * @param[in] up Set to @c true if the time field must be rolled upwards, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE In this method, the time fields of this instance are calculated. @n + * If any time field value previously set is invalid, this exception is returned. + * @exception E_INVALID_ARG The specified @c field is invalid (for example, TIME_FIELD_DST_OFFSET, TIME_FIELD_ZONE_OFFSET). + * @exception E_OUT_OF_RANGE A time field or its value is out of range. @n + * In this method, the time fields of this instance are calculated. + * If the value of the time fields goes out of range, this exception is returned. + */ + virtual result RollWithSingleUnit(TimeField field, bool up) = 0; + + /** + * Checks whether the current instance of %Calendar is equivalent to the specified instance of %Calendar. + * + * @since 2.0 + * + * @return @c true if the current instance of %Calendar is equivalent to the specified %Calendar instance, @n + * else @c false + * @param[in] calendar The instance of %Calendar to compare with + * @remarks If the specified %Calendar instance is equivalent to the current instance, the two instances behave + * exactly the same, but they may be set to different times. + */ + virtual bool IsEquivalentTo(const Calendar& calendar) const; + + /** + * Computes the time field value. @n + * Converts the current millisecond time value to TimeField. @n + * This allows synching up the time field values with a new time that is set for the calendar. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The time fields contain an invalid value. @n + * In this method, the time fields of this instance are calculated. If the value of the time fields goes out of range, this exception is returned. + */ + virtual result ComputeTimeFields(void) = 0; + + /** + * Computes the time value. @n + * Converts the current values of time field to the millisecond time value. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE A value of the internal time field is invalid. + */ + virtual result ComputeTime(void) = 0; + + /** + * Gets the length of the specified month. + * + * @since 2.0 + * + * @return An integer value indicating the number of days in the specified month + * @param[in] extendedYear An extended year + * @param[in] month A month + */ + virtual int GetMonthLength(int extendedYear, int month) const = 0; + + /** + * Handles the limits of different types. @n + * Derived classes must implement this method for the following fields: + * TIME_FIELD_ERA, TIME_FIELD_YEAR, TIME_FIELD_MONTH, TIME_FIELD_WEEK_OF_YEAR, TIME_FIELD_WEEK_OF_MONTH, + * TIME_FIELD_DAY_OF_MONTH, TIME_FIELD_DAY_OF_YEAR, TIME_FIELD_DAY_OF_WEEK_IN_MONTH, TIME_FIELD_YEAR_WOY, + * TIME_FIELD_EXTENDED_YEAR. + * + * @since 2.0 + * + * @return The limit of the specified field + * @param[in] field The time field + * @param[in] limitType The type of limit + */ + virtual int HandleGetLimit(TimeField field, CalendarLimitType limitType) const = 0; + + /* + * Creates and returns a polymorphic copy of this calendar. + * + * @since 2.0 + * + * @return A polymorphic copy of this calendar + */ + virtual Tizen::Locales::Calendar* CloneN(void) const = 0; + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Calendar_Reserved1(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Calendar_Reserved2(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Calendar_Reserved3(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Calendar_Reserved4(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Calendar_Reserved5(void) { } + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. Use CloneN() to get an exact copy of the instance. + */ + Calendar(const Calendar& calendar); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. Use CloneN() to get an exact copy of the instance. + */ + Calendar& operator =(const Calendar& calendar); + +public: + /** + * Millisecond constants for one day. + * + * @since 2.0 + */ + static const int ONE_DAY_IN_MILLISEC = 86400000; + + /** + * Millisecond constants for one hour. + * + * @since 2.0 + */ + static const int ONE_HOUR_IN_MILLISEC = 60 * 60 * 1000; + + /** + * Millisecond constants for one minute. + * + * @since 2.0 + */ + static const int ONE_MINUTE_IN_MILLISEC = 60000; + + /** + * Millisecond constants for one second. + * + * @since 2.0 + */ + static const int ONE_SECOND_IN_MILLISEC = 1000; + + /** + * Millisecond constants for one week. + * + * @since 2.0 + */ + static const long long ONE_WEEK_IN_MILLISEC = 7 * ONE_DAY_IN_MILLISEC; + +protected: + /** + * The field values for the currently set time for this calendar. + */ + int _timeFields[TIME_FIELD_FIELD_COUNT]; + + /** + * Pseudo-time-stamps which specify when each field is set. + * There are two special values - UNSET and INTERNALLY_SET. + */ + int _stamp[TIME_FIELD_FIELD_COUNT]; + + /** + * The flags which tell if a specified time field for the calendar is set. + */ + bool _isSet[TIME_FIELD_FIELD_COUNT]; + + long long _time; // UTC time + Tizen::Locales::TimeZone _timeZone; + + bool _isTimeSet; + bool _areFieldsSet; + bool _areAllFieldsSet; + int _nextStamp; + bool _isLenient; + bool _isConstructed; + + // Mask values for calendar fields + static const int ERA_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_ERA); + static const int YEAR_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_YEAR); + static const int MONTH_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_MONTH); + static const int WEEK_OF_YEAR_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_WEEK_OF_YEAR); + static const int WEEK_OF_MONTH_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_WEEK_OF_MONTH); + static const int DAY_OF_MONTH_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_DAY_OF_MONTH); + static const int DAY_OF_YEAR_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_DAY_OF_YEAR); + static const int DAY_OF_WEEK_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_DAY_OF_WEEK); + static const int DAY_OF_WEEK_IN_MONTH_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_DAY_OF_WEEK_IN_MONTH); + static const int AM_PM_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_AM_PM); + static const int HOUR_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_HOUR); + static const int HOUR_OF_DAY_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_HOUR_OF_DAY); + static const int MINUTE_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_MINUTE); + static const int SECOND_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_SECOND); + static const int MILLISECOND_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_MILLISECOND); + static const int ZONE_OFFSET_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_ZONE_OFFSET); + static const int DST_OFFSET_MASK = GET_TIME_FIELD_MASK(TIME_FIELD_DST_OFFSET); + static const int ALL_FIELDS = GET_TIME_FIELD_MASK(TIME_FIELD_FIELD_COUNT) - 1; + +//private: + friend class _CalendarImpl; + class _CalendarImpl* _pCalendarImpl; + +}; // Calendar + +}} // Tizen::Locales + +#endif //_FLCL_CALENDAR_H_ diff --git a/inc/FLclCurrency.h b/inc/FLclCurrency.h new file mode 100644 index 0000000..7aa2017 --- /dev/null +++ b/inc/FLclCurrency.h @@ -0,0 +1,209 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclCurrency.h + * @brief This is the header file for the %Currency class. + * + * This header file contains the declarations of the %Currency class. + * + */ +#ifndef _FLCL_CURRENCY_H_ +#define _FLCL_CURRENCY_H_ + +#include +#include + +namespace Tizen {namespace Locales +{ + +// Forward declaration +class Locale; + +/** + * @class Currency + * @brief This class represents currencies. + * + * @since 2.0 + * + * The %Currency class represents currencies, and is used when the localized currency symbol is retrieved. + * + * For more information on the class features, see Number Symbols and Currencies. + * @see Locale + * @see LanguageCode + * @see CountryCode + * + */ +class _OSP_EXPORT_ Currency + : public Tizen::Base::Object +{ +public: + + /** + * This is the default constructor for this class. @n + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @see Construct() + */ + Currency(void); + + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Currency(void); + + + /** + * Initializes this instance of %Currency with the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCurrencyConstructPage "here". + * @endif + * + * @return An error code + * @param[in] locale The specified @c locale to get the currency symbol + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c locale is not supported. + */ + result Construct(const Locale& locale); + + + /** + * Initializes this instance of %Currency with the specified currency code. @n + * Currencies are enumerated as defined by ISO 4217. For example, if the locale is Korean (language) and Korea (country), the currency code is "KRW". + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompCurrencyConstructPage "here". + * @endif + * + * @return An error code + * @param[in] currencyCode The specified currency code to get the currency symbol + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c currencyCode is not supported. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const Tizen::Base::String& currencyCode); + /** + * @if OSPCOMPAT + * @page CompCurrencyConstructPage Compatibility for Construct() + * @section CompCurrencyConstructIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the argument is invalid. + * + * @section CompCurrencyConstructSolutionSection Resolutions + * This issue has been resolved in Tizen. @n + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the argument is invalid. + * @endif + */ + + + /** + * Gets the ISO 4217 currency code for the specified currency. + * + * @since 2.0 + * + * @return The currency code that is already set + * @see GetSymbol() + */ + Tizen::Base::String GetCurrencyCode(void) const; + + + /** + * Gets the symbol of this currency. @n + * The symbol will be localized for the locale of the currency. + * For example, if the locale of this currency is kor_KR and the system locale is eng_US, + * the symbol will be the Korean won sign "₩ "; if the locale of this currency is eng_US and the system locale is kor_KR, + * the symbol will be "$". + * + * @since 2.0 + * + * @return symbol The currency symbol string + */ + Tizen::Base::String GetSymbol(void) const; + + /** + * Compares the value of the specified instance to that of the current instance. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance is equal to that of the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Gets a list of all available currencies. + * + * @since 2.0 + * + * @return A pointer to an array of %Currency objects, @n + * else a @c null pointer is returned if there is no currency available or there is some failure @n + * The array is a list of all the available currencies. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Tizen::Base::Collection::IList* GetAvailableCurrenciesN(void); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Currency(const Currency& currency); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Currency& operator =(const Currency& currency); + + Tizen::Base::String __currencyCodeSymbol; + + friend class _CurrencyImpl; + class _CurrencyImpl* __pCurrencyImpl; +}; // Currency + +}} // Tizen::Locales + +#endif //_FLCL_CURRENCY_H_ diff --git a/inc/FLclDateTimeFormatter.h b/inc/FLclDateTimeFormatter.h new file mode 100644 index 0000000..7f3f284 --- /dev/null +++ b/inc/FLclDateTimeFormatter.h @@ -0,0 +1,386 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclDateTimeFormatter.h + * @brief This is the header file for the %DateTimeFormatter class. + * + * This header file contains the declarations of the %DateTimeFormatter class. + * + */ +#ifndef _FLCL_DATE_TIME_FORMATTER_H_ +#define _FLCL_DATE_TIME_FORMATTER_H_ + +// Includes +#include +#include +#include + + +namespace Tizen { namespace Locales +{ + +// forward declaration +class NumberFormatter; +class _FieldPosition; +class _DateTimeFormatterImpl; + + +/** + * @enum DateTimeStyle + * + * Defines the style for date and time. + * + * @since 2.0 + */ +enum DateTimeStyle +{ + DATE_TIME_STYLE_NONE = -1, /**< The date time style: None */ + DATE_TIME_STYLE_FULL = 0, /**< The date time style: FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42PM PST */ + DATE_TIME_STYLE_LONG = 1, /**< The date time style: LONG is longer, such as July 18, 2012 or 3:30:32PM */ + DATE_TIME_STYLE_MEDIUM = 2, /**< The date time style: MEDIUM is a little longer, such as Jan 12, 1952 */ + DATE_TIME_STYLE_SHORT = 3, /**< The date time style: SHORT is completely numeric, such as 12/13/52 or 3:30PM */ + DATE_TIME_STYLE_DEFAULT = DATE_TIME_STYLE_MEDIUM /**< The default date time style: Medium */ +}; + +/** + * @class DateTimeFormatter + * @brief This class provides methods for formatting the date and time formats. + * + * @since 2.0 + * + * The %DateTimeFormatter class is used to format the date and time formats in a language-independent manner. + * The date and time are represented as a Tizen::Base::DateTime instance. + * + * For more information on the class features, see Date and Time Formatter. + * + * @see Tizen::Base::DateTime + * @see DateTimeSymbols + * + * The following example demonstrates how to use the %DateTimeFormatter class. + * + * @code +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Locales; +using namespace Tizen::System; + +void +LocaleApp::DateTimeFormatterExample(void) +{ + // Construct locale + Locale locale(LANGUAGE_ENG, COUNTRY_US); + + // Get today + DateTime today; + SystemTime::GetCurrentTime(TIME_MODE_UTC, today); + + // Get date formatter + DateTimeFormatter* pDateFormatter = DateTimeFormatter::CreateDateFormatterN(locale, DATE_TIME_STYLE_DEFAULT); + + String formattedString; + + // Format today with date formatter + pDateFormatter->Format(today, formattedString); + + // Get time formatter + DateTimeFormatter* pTimeFormatter = DateTimeFormatter::CreateTimeFormatterN(locale, DATE_TIME_STYLE_DEFAULT); + + // Format today with time formatter + pTimeFormatter->Format(today, formattedString); + + // Customized pattern + String cutomizedPattern = L"EEE d MMM yy"; + pDateFormatter->ApplyPattern(cutomizedPattern); + + // Format today with date formatter + pDateFormatter->Format(today, formattedString); + + delete pDateFormatter; + delete pTimeFormatter; +} +@endcode + * + */ +class _OSP_EXPORT_ DateTimeFormatter + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DateTimeFormatter(void); + + /** + * Creates the date formatter with the specified formatting style for the system locale. + * + * @since 2.0 + * + * @return A pointer to the system locale date formatter, @n + * else @c null if an error occurs + * @param[in] style The formatting style @n + * For example, "M/d/yy" is the short form for displaying only date in the US locale. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_OPERATION The current locale is not supported. + * @exception E_INVALID_ARG The specified @c style is an invalid value. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static DateTimeFormatter* CreateDateFormatterN(DateTimeStyle style = DATE_TIME_STYLE_DEFAULT); + + + /** + * Creates the date formatter with the specified formatting style for the specified locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompDateTimeFormatterCreateDateFormatterNPage "here". + * @endif + * + * @return A pointer to the specified locale date formatter, @n + * else @c null if an error occurs + * @param[in] locale The locale + * @param[in] style The formatting style @n + * For example, "M/d/yy" is the short form for displaying only date in the US locale. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale or @c style is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static DateTimeFormatter* CreateDateFormatterN(const Locale& locale, DateTimeStyle style = DATE_TIME_STYLE_DEFAULT); + + /** + * @if OSPCOMPAT + * @page CompDateTimeFormatterCreateDateFormatterNPage Compatibility for CreateDateFormatterN() + * @section CompDateTimeFormatterCreateDateFormatterNIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the @c locale is invalid. + * + * @section CompDateTimeFormatterCreateDateFormatterNtSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the @c locale or @c style is invalid. + * @endif + */ + + + /** + * Creates the time formatter with the specified formatting style for the system locale. + * + * @since 2.0 + * + * @return A pointer to the system locale time formatter, @n + * else @c null if an error occurs + * @param[in] style The formatting style @n + * For example, "h:mm a" is the short form for displaying the 12-hour time format in the US locale. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_OPERATION The current locale is not supported. + * @exception E_INVALID_ARG The specified @c style is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static DateTimeFormatter* CreateTimeFormatterN(DateTimeStyle style = DATE_TIME_STYLE_DEFAULT); + + + /** + * Creates the time formatter with the specified formatting style for the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompDateTimeFormatterCreateTimeFormatterNPage "here". + * @endif + * + * @return A pointer to the specified locale time formatter, @n + * else @c null if an error occurs + * @param[in] locale The locale + * @param[in] style The formatting style @n + * For example, "h:mm a" is the short form for displaying the 12-hour time format in the US locale. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale or @c style is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static DateTimeFormatter* CreateTimeFormatterN(const Locale& locale, DateTimeStyle style = DATE_TIME_STYLE_DEFAULT); + + /** + * @if OSPCOMPAT + * @page CompDateTimeFormatterCreateTimeFormatterNPage Compatibility for CreateTimeFormatterN() + * @section CompDateTimeFormatterCreateTimeFormatterNIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the @c locale is invalid. + * + * @section CompGrDateTimeFormatterCreateTimeFormatterNSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the @c locale or @c style is invalid. + * @endif + */ + + /** + * Creates the date/time formatter with the specified formatting style for the system locale. + * + * @since 2.0 + * + * @return A pointer to the system locale date/time formatter, @n + * else @c null if an error occurs + * @param[in] dateStyle The date formatting style @n + * For example, "M/d/yy" is the short form for displaying only date in the US locale. + * @param[in] timeStyle The time formatting style @n + * For example, "h:mm a" is the short form for displaying the 12-hour time format in the US locale. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_OPERATION The current locale is not supported. + * @exception E_INVALID_ARG The specified @c dateStyle or @c timeStyle is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static DateTimeFormatter* CreateDateTimeFormatterN(DateTimeStyle dateStyle = DATE_TIME_STYLE_DEFAULT, DateTimeStyle timeStyle = DATE_TIME_STYLE_DEFAULT); + + + /** + * Creates the date/time formatter with the specified formatting style for the specified @c locale. + * + * @since 2.0 + * + * @return A pointer to the specified locale date/time formatter, @n + * else @c null if an error occurs + * @param[in] locale The locale + * @param[in] dateStyle The date formatting style @n + * For example, "M/d/yy" is the short form for displaying only date in the US locale. + * @param[in] timeStyle The time formatting style @n + * For example, "h:mm a" is the short form for displaying the 12-hour time format in the US locale. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is not supported, or the @c dateStyle or the @c timeStyle is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static DateTimeFormatter* CreateDateTimeFormatterN(const Locale& locale, DateTimeStyle dateStyle = DATE_TIME_STYLE_DEFAULT, DateTimeStyle timeStyle = DATE_TIME_STYLE_DEFAULT); + + /** + * Formats a Tizen::Base::DateTime object into a date/time string and appends the resulting string to the specified string buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] date The Tizen::Base::DateTime object to format + * @param[out] str The string to append to the resultant string + * @exception E_SUCCESS The method is successful. + * @remarks This method does not handle the time zone information, so "z" pattern always returns "GMT+00:00". + * @see Tizen::Base::DateTime + */ + virtual result Format(const Tizen::Base::DateTime& date, Tizen::Base::String& str) const; + + + /** + * Formats a Calendar object into a date/time string and appends the resulting string to the specified string buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] calendar The Calendar object to format + * @param[out] str The string to append to the resultant string + * @exception E_SUCCESS The method is successful. + * @see Tizen::Base::DateTime + */ + virtual result Format(const Calendar& calendar, Tizen::Base::String& str) const; + + + /** + * Applies the specified pattern string to the date format. + * + * @since 2.0 + * + * @param[in] pattern The new date and time pattern for the date format + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of the specified @c pattern is @c 0. + */ + result ApplyPattern(const Tizen::Base::String& pattern); + + + /** + * Gets a pattern string describing the date format. + * + * @since 2.0 + * + * @return A string describing the date format + */ + Tizen::Base::String GetPattern(void) const; + + + /** + * Gets the date and time format symbols of the formatter. + * + * @since 2.0 + * + * @return A pointer to DateTimeSymbols for the formatter instance + * @see SetDateTimeSymbols() + */ + const DateTimeSymbols* GetDateTimeSymbols(void) const; + + + /** + * Sets the date and time format symbols of the date format. + * + * @since 2.0 + * + * @param[in] newSymbols The new date and time format symbols + * @see GetDateTimeSymbols() + */ + void SetDateTimeSymbols(const DateTimeSymbols& newSymbols); + +private: + NumberFormatter* __pNumberFormat; + Calendar* __pCalendar; + + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + DateTimeFormatter(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + DateTimeFormatter(const DateTimeFormatter& dateTimeFormatter); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + DateTimeFormatter& operator =(const DateTimeFormatter& dateTimeFormatter); + + friend class _DateTimeFormatterImpl; + class _DateTimeFormatterImpl* __pDateTimeFormatterImpl; +}; // DateTimeFormatter + +}} // Tizen::Locales + +#endif //_FLCL_DATE_TIME_FORMATTER_H_ + diff --git a/inc/FLclDateTimeSymbols.h b/inc/FLclDateTimeSymbols.h new file mode 100644 index 0000000..18a0c19 --- /dev/null +++ b/inc/FLclDateTimeSymbols.h @@ -0,0 +1,401 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclDateTimeSymbols.h + * @brief This is the header file for the %DateTimeSymbols class. + * + * This header file contains the declarations of the %DateTimeSymbols class. + * + */ +#ifndef _FLCL_DATE_TIME_SYMBOLS_H_ +#define _FLCL_DATE_TIME_SYMBOLS_H_ + +#include +#include +#include + +namespace Tizen { namespace Locales +{ + +/** + * @class DateTimeSymbols + * @brief This class provides methods that help in providing date and time symbols. + * + * @since 2.0 + * + * The %DateTimeSymbols class is used for encapsulating localizable date-time formatting data, such as the names of the months, the days of the week, and the time zone data. + * It is also used by DateTimeFormatter. + * %DateTimeSymbols specifies the exact character strings to use for various parts of a date or time. For example, the names of the months and days of the week, the strings for AM and PM, and the day of the week considered to be the first day of the week. + * + * For more information on the class features, see Date and Time Formatter. + * + * @see Tizen::Locales::DateTimeFormatter + * + */ +class _OSP_EXPORT_ DateTimeSymbols + : public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. @n + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @see Construct() + */ + DateTimeSymbols(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DateTimeSymbols(void); + + + /** + * Initializes this instance of %DateTimeSymbols with the specified @c locale and @c calendarType. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompDateTimeSymbolsConstructPage "here". + * @endif + * + * @return An error code + * @param[in] locale The locale + * @param[in] calendarType The calendar type + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale or @c calendarType is invalid. + */ + result Construct(const Locale& locale, CalendarType calendarType = CALENDAR_GREGORIAN); + + + /** + * Initializes this instance of %DateTimeSymbols with the specified parameter. @n + * This method loads the format data from the resources for the default locale into the default calendar. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompDateTimeSymbolsConstructPage "here". + * @endif + * + * @return An error code + * @param[in] calendarType The calendar type + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c calendarType is invalid. + */ + result Construct(CalendarType calendarType); + + /** + * @if OSPCOMPAT + * @page CompDateTimeSymbolsConstructPage Compatibility for Construct() + * @section CompDateTimeSymbolsConstructIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the @c calendarType is invalid. + * + * @section CompDateTimeSymbolsConstructSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the @c calendarType is invalid. + * @endif + */ + + + /** + * Initializes this instance of %DateTimeSymbols with the specified parameter. + * + * @since 2.0 + * + * @return An error code + * @param[in] other An instance of %DateTimeSymbols + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const DateTimeSymbols& other); + + + /** + * Gets the list of the era strings. @n + * For example: "AD" and "BC". + * + * @since 2.0 + * + * @return A pointer to the list of era strings, @n + * else @c null if this instance has not been constructed as yet + * @see SetEras() + */ + const Tizen::Base::Collection::IList* GetEras(void) const; + + + /** + * Sets the era strings. @n + * Multiple strings can be concatenated by '|'. For example: "AD|BC". + * + * @since 2.0 + * + * @return An error code + * @param[in] eras The era strings concatenated by '|' + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c eras contains an invalid value. + * @see GetEras() + */ + result SetEras(const Tizen::Base::String& eras); + + + /** + * Gets the list of the month name strings. @n + * For example: "January", "February", etc. + * + * @since 2.0 + * + * @return A pointer to the list of month name strings, @n + * else @c null if this instance has not been constructed as yet + * @see SetMonths() + */ + const Tizen::Base::Collection::IList* GetMonths(void) const; + + + /** + * Sets the month name strings concatenated by '|'. @n + * For example: "January|February|March|April|May|June|July|August|September|October|November|December". + * + * @since 2.0 + * + * @return An error code + * @param[in] months The new month strings concatenated by '|' + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c months contains an invalid value. + * @see GetMonths() + */ + result SetMonths(const Tizen::Base::String& months); + + + /** + * Gets the list of the short month name strings. @n + * For example: "Jan", "Feb", etc. + * + * @since 2.0 + * + * @return A pointer to the list of short month name strings, @n + * else @c null if this instance has not been constructed as yet + * @see SetShortMonths() + */ + const Tizen::Base::Collection::IList* GetShortMonths(void) const; + + + /** + * Sets the short month name strings concatenated by '|'. @n + * For example: "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec". + * + * @since 2.0 + * @return An error code + * @param[in] shortMonths The new short month name strings concatenated by '|' + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c shortMonths contains an invalid value. @n See the valid string in the description of the method. + * @see GetShortMonths() + */ + result SetShortMonths(const Tizen::Base::String& shortMonths); + + + /** + * Gets the list of the weekday name strings. @n + * For example: "Sunday", "Monday", etc. + * + * @since 2.0 + * + * @return A pointer to the list of weekday name strings, @n + * else @c null if this instance has not been constructed as yet + * @see SetWeekdays() + */ + const Tizen::Base::Collection::IList* GetWeekdays(void) const; + + + /** + * Sets the weekday name strings concatenated by '|'. @n + * For example: "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday". + * + * @since 2.0 + * + * @return An error code + * @param[in] weekdays The new weekday name strings concatenated by '|' + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c weekdays contains an invalid value. + * @see GetWeekdays() + */ + result SetWeekdays(const Tizen::Base::String& weekdays); + + + /** + * Gets the list of the short weekday name strings. @n + * For example: "Sun", "Mon", etc. + * + * @since 2.0 + * + * @return A pointer to the list of short weekday name strings, @n + * else @c null if this instance has not been constructed as yet + * @see SetShortWeekdays() + */ + const Tizen::Base::Collection::IList* GetShortWeekdays(void) const; + + + /** + * Sets the weekday name strings concatenated by '|'. @n + * For example: "Sun|Mon|Tue|Wed|Thu|Fri|Sat". + * + * @since 2.0 + * + * @return An error code + * @param[in] shortWeekdays The new short weekday strings concatenated by '|' + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c shortWeekdays contains an invalid value. + * @see GetShortWeekdays() + */ + result SetShortWeekdays(const Tizen::Base::String& shortWeekdays); + + + /** + * Gets the list of the AM/PM strings. @n + * For example: "AM" and "PM". + * + * @since 2.0 + * + * @return A pointer to the list of AM/PM strings, @n + * else @c null if this instance has not been constructed as yet + * @see SetAmPm() + */ + const Tizen::Base::Collection::IList* GetAmPm(void) const; + + + /** + * Sets the AM/PM strings concatenated by '|'. @n + * For example: "AM|PM". + * + * @since 2.0 + * + * @return An error code + * @param[in] amPm The new AM/PM strings concatenated by '|' + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c amPm contains an invalid value. + * @see GetAmPm() + */ + result SetAmPm(const Tizen::Base::String& amPm); + + + /** + * Gets the name of the time zone. @n + * For example: "Eastern European Time (EET)", "Eastern European Summer Time (EEST)". + * + * @since 2.0 + * + * @return The time zone name, @n + * else an empty string if @c timeZoneId is not found @n + * or the time zone name of @c timeZoneStyle is not found. + * @param[in] timeZoneId The time zone ID + * @param[in] timeZoneStyle The parameter may contain one of the following time zone styles: + * @li The normal time zone (0) + * @li The abbreviated time zone (1) + * @li The normal summer time zone (2) + * @li The abbreviated summer time zone (3) + * @see SetTimeZoneName() + * @see AddTimeZoneName() + */ + Tizen::Base::String GetTimeZoneName(Tizen::Base::String& timeZoneId, int timeZoneStyle = 0) const; + + + /** + * Sets the time zone name string related to the specified time zone ID. + * + * @since 2.0 + * + * @return An error code + * @param[in] timeZoneId The time zone ID @n + * For example: "Europe/Helsinki". + * @param[in] concatenatedTimeZoneName The new concatenated time zone name @n + * For example, "Eastern European Time|EET|Eastern European Summer Time|EEST". + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c timeZoneId or @c concatenatedTimeZoneName contains an invalid value. + * @exception E_OBJ_NOT_FOUND The specified @c timeZoneId is not found. + * @see GetTimeZoneName() + * @see AddTimeZoneName() + */ + result SetTimeZoneName(const Tizen::Base::String& timeZoneId, const Tizen::Base::String& concatenatedTimeZoneName); + + + /** + * Adds a new time zone name string that is related to time zone ID. + * + * @since 2.0 + * + * @return An error code + * @param[in] timeZoneId The time zone ID @n + * For example: "Europe/Helsinki". + * @param[in] concatenatedTimeZoneName The concatenated time zone name @n + * For example, "Eastern European Time|EET|Eastern European Summer Time|EEST". + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OBJ_ALREADY_EXIST The specified @c timeZoneId already exists. + * @see GetTimeZoneName() + * @see SetTimeZoneName() + */ + result AddTimeZoneName(const Tizen::Base::String& timeZoneId, const Tizen::Base::String& concatenatedTimeZoneName); + + + /* + * Gets the non-localized date-time pattern characters. + * + * @since 2.0 + * + * @return The non-localized date-time pattern characters + */ + static Tizen::Base::WcharBuffer* GetNonLocalizedDateTimePatternN(void); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + DateTimeSymbols(const DateTimeSymbols& dateTimeSymbols); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + DateTimeSymbols& operator =(const DateTimeSymbols& dateTimeSymbols); + + friend class _DateTimeSymbolsImpl; + class _DateTimeSymbolsImpl* __pDateTimeSymbolsImpl; + +}; // DateTimeSymbols + +}} // Tizen::Locales + +#endif //_FLCL_DATE_TIME_SYMBOLS_H_ + diff --git a/inc/FLclGregorianCalendar.h b/inc/FLclGregorianCalendar.h new file mode 100644 index 0000000..c4f1ddb --- /dev/null +++ b/inc/FLclGregorianCalendar.h @@ -0,0 +1,649 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclGregorianCalendar.h + * @brief This is the header file for the %GregorianCalendar class. + * + * This header file contains the declarations of the %GregorianCalendar class. + */ +#ifndef _FLCL_GREGORIAN_CALENDAR_H_ +#define _FLCL_GREGORIAN_CALENDAR_H_ + +#include + +#include +#include +#include + +namespace Tizen { namespace Locales +{ + +/** + * @class GregorianCalendar + * @brief This class is a concrete subclass of calendar and provides the Gregorian calendar that is the most commonly used standard calendar. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %GregorianCalendar class is a concrete subclass of calendar and provides the Gregorian calendar that is the most commonly used standard calendar. + * + * For more information on the class features, see Gregorian Calendar. + * + * @see Tizen::Locales::Locale + * @see Tizen::Locales::TimeZone + * + * The following example demonstrates how to use the %GregorianCalendar class. + * @code + #include + #include + + using namespace Tizen::Base; + using namespace Tizen::Locales; + + void + MyClass::GregorianCalendarExample(void) + { + Calendar* pGregorianCalendar = Calendar::CreateInstanceN(CALENDAR_GREGORIAN); + + pGregorianCalendar->SetTimeField(TIME_FIELD_YEAR, 2005); + pGregorianCalendar->SetTimeField(TIME_FIELD_MONTH, JANUARY); + pGregorianCalendar->SetTimeField(TIME_FIELD_DAY_OF_MONTH, 3); + + int dayOfWeek = pGregorianCalendar->GetTimeField(TIME_FIELD_DAY_OF_WEEK);// It is Monday. + + pGregorianCalendar->Clear(); + pGregorianCalendar->SetTimeField(TIME_FIELD_YEAR, 1972); + pGregorianCalendar->SetTimeField(TIME_FIELD_MONTH, OCTOBER); + pGregorianCalendar->SetTimeField(TIME_FIELD_DAY_OF_MONTH, 26); // It is Thursday + + pGregorianCalendar->AddTimeField(TIME_FIELD_DAY_OF_MONTH, 1); + dayOfWeek = pGregorianCalendar->GetTimeField(TIME_FIELD_DAY_OF_WEEK); // It is Friday. +} + @endcode + * + */ + +class _OSP_EXPORT_ GregorianCalendar + : public Calendar +{ +public: + /** + * This is the default constructor for this class. @n + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @see Construct() + */ + GregorianCalendar(void); + + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Locales::Calendar::~Calendar(). + * + * @since 2.0 + */ + virtual ~GregorianCalendar(void); + + + /** + * Initializes this instance of %GregorianCalendar with the current GMT time zone and the system locale. + * The time zone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set and weekend cease. + * The weekdata are set as default values by the locale. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(void); + + + /** + * Initializes this instance of %GregorianCalendar with the specified parameter. + * + * @since 2.0 + * + * @return An error code + * @param[in] gc An instance of %GregorianCalendar to copy + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const GregorianCalendar& gc); + + + /** + * Initializes this instance of %GregorianCalendar based on the current time in the specified time zone with the system locale. @n + * The @c timeZone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the locale. + * + * @since 2.0 + * + * @return An error code + * @param[in] timeZone An instance of TimeZone + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const TimeZone& timeZone); + + + /** + * Initializes this instance of %GregorianCalendar based on the current time in the GMT time zone with the specified @c locale. + * The time zone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompGregorianCalendarConstructPage "here". + * @endif + * + * @return An error code + * @param[in] locale An instance of Locale + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is invalid. + */ + result Construct(const Locale& locale); + + + /** + * Initializes this instance of %GregorianCalendar based on the current time in the specified time zone with the specified system locale. @n + * The @c timeZone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompGregorianCalendarConstructPage "here". + * @endif + * + * @return An error code + * @param[in] timeZone An instance of TimeZone + * @param[in] locale An instance of Locale + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is invalid. + */ + result Construct(const TimeZone& timeZone, const Locale& locale); + + /** + * @if OSPCOMPAT + * @page CompGregorianCalendarConstructPage Compatibility for Construct() + * @section CompGregorianCalendarConstructIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the @c locale is invalid. + * + * @section CompGregorianCalendarConstructSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the @c locale is invalid. + * @endif + */ + + /** + * Initializes this instance of %GregorianCalendar based on the specified @c year, @c month, @c day, @c hour, @c minute, and @c second + * in the GMT time zone with the system locale. @n + * The time zone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the locale. + * The Gregorian calendar is lenient: time fields are normalized when the user calls the Calendar::GetTimeField() method. + * + * @since 2.0 + * + * @return An error code + * @param[in] year An integer value used to set the year time field + * @param[in] month An integer value used to set the month time field @n + * The indexing is 1-based. Therefore, 1 means January. + * @param[in] day An integer value used to set the date time field + * @param[in] hour An integer value used to set the hour time field + * @param[in] minute An integer value used to set the minute time field + * @param[in] second An integer value used to set the second time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG An argument is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OUT_OF_RANGE In this method, time fields of this instance are calculated. @n + * If the value of the time fields goes out of range, this exception is returned. + */ + result Construct(int year, int month, int day, int hour = 0, int minute = 0, int second = 0); + + + /** + * Initializes this instance of %GregorianCalendar based on the specified date and time in the GMT time zone with the system locale. @n + * The time zone is used for the zone offset and the DST offset. + * An instance has weekdata which are the first of week, minimal days in the first week, weekend on set, and weekend cease. + * The weekdata are set as default values by the locale. + * + * @since 2.0 + * + * @return An error code + * @param[in] dateTime An instance of Tizen::Base::DateTime + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c dateTime is invalid. + * @exception E_OUT_OF_RANGE In this method, time fields of this instance are calculated. @n + * If the value of the time fields goes out of range, this exception is returned. + */ + result Construct(const Tizen::Base::DateTime& dateTime); + + + /** + * Adds the specified amount to the specified time field, based on the calendar rules. @n + * It is equivalent to calling Set(field, GetTimeField(field)+amount) with two adjustments. @n + * + * @b Add @b Rule1: The value of @c field after the call minus the value of @c field before the call is delta, modulo any overflow that has occurred in @c field. + * Overflow occurs when the @c field value exceeds its range and, as a result, the next larger field is incremented or decremented and the @c field value is adjusted back into its range. @n + * + * @b Add @b Rule2: If a smaller field is expected to be invariant, but it is impossible for it to be equal to its prior value because of + * changes in its minimum or maximum value after the @c field value is changed, then its value is adjusted to the closest possible value. @n + * + * A smaller field represents a smaller unit of time. The TIME_FIELD_HOUR field is smaller than the TIME_FIELD_DAY_OF_MONTH field. + * No adjustment is made to smaller fields that are not expected to be invariant. + * The calendar system determines what fields are expected to be invariant. @n + * + * In addition, this method forces re-computation of the calendar's milliseconds and all time fields immediately. + * @n + * For example, consider a %GregorianCalendar set to Oct. 31. 2004. Calling AddTimeField(TIME_FIELD_MONTH, 13) sets the calendar to Nov. 30. 2005. + * The TIME_FIELD_MONTH field is set to TIME_FIELD_NOVEMBER by @b Rule1, since adding 13 months to October gives November of the next year. Since + * the TIME_FIELD_DAY_OF_MONTH cannot be 31 in November in a %GregorianCalendar, TIME_FIELD_DAY_OF_MONTH is set to 30 by @b Rule2. + * + * @since 2.0 + * + * @return An error code + * @param[in] field The time field + * @param[in] amount The amount to add + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c field is invalid. + * @exception E_OUT_OF_RANGE In this method, time fields of this instance are calculated. @n + * If the value of the time fields goes out of range, this exception is returned. + * @remarks The TIME_FIELD_EXTENDED_YEAR and TIME_FIELD_YEAR_WOY fields cannot be added. + */ + virtual result AddTimeField(TimeField field, int amount); + + + /** + * Gets the actual minimum value that the specified time field can have, given the current date. @n + * For the Gregorian calendar, this is the same as Calendar::GetMinTimeField() and Calendar::GetGreatestMinTimeField(). + * + * @since 2.0 + * + * @return An integer value indicating the actual minimum value + * @param[in] field The time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified time field is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetActualMinTimeField(TimeField field) const; + + + /** + * Gets the actual maximum value that the specified time field can have, given the current date. @n + * For example, if the current date is "Feb. 3. 2004", then the maximum value of the DATE field is 29. + * + * @since 2.0 + * + * @return An integer value indicating the actual maximum value + * @param[in] field The time field + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified time field is invalid. + + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetActualMaxTimeField(TimeField field) const; + + + /* + * Gets the Gregorian Calendar change date. @n + * This is the point when the switch from Julian dates to Gregorian dates occurred. + * Default is 00:00:00 local time, October 15, 1582. Previous to this the time and date are Julian dates. + * + * @since 2.0 + * + * @return The milliseconds which is the Gregorian cutover time for this calendar + */ + long long GetGregorianChange(void) const; + + + /** + * Gets the calendar type of the current instance. + * + * @since 2.0 + * + * @return An instance of CalendarType representing the calendar type of the current instance of Calendar @n + * In this case, CALENDAR_GREGORIAN. + */ + virtual CalendarType GetType(void) const; + + /** + * Checks whether the current date for the current instance is in Daylight Saving Time (DST). + * + * @since 2.0 + * + * @return An error code + * @param[out] isInDst Set to @c true if the current date is in DST, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE In this method, time fields of this instance are calculated. @n + * If the value of the time fields goes out of range, this exception is returned. + * @exception E_INVALID_STATE In this method, time fields of this instance are calculated. @n + * If any time field value previously set is invalid, this exception is returned. + */ + virtual result IsInDst(bool& isInDst) const; + + + /** + * Checks whether the specified year is a leap year. + * + * @since 2.0 + * + * @return @c true if the specified year is a leap year, @n + * else @c false + * @param[in] year The year to check + */ + bool IsLeapYear(int year) const; + + + /** + * Sets the Gregorian Calendar change date. @n + * This is the point when the switch from Julian dates to Gregorian dates occurred. + * Default is 00:00:00 local time, Oct 15, 1582. Previous to this, dates are in the Julian calendar. + * + * To obtain a pure Julian calendar, set the change @c change to MAX_MILLISECOND. + * To obtain a pure Gregorian calendar, set the change @c change to MIN_MILLISECOND. + * + * @since 2.0 + * + * @return An error code + * @param[in] change The given Gregorian cutover date + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result SetGregorianChange(long long change); + + /** + * Rolls up or down as per the specified amount in the specified field. @n + * This method overrides Calendar(). @n + * For more details, refer to Tizen::Locales::Calendar::Roll(TimeField, int). + * + * @since 2.0 + * + * @return An error code + * @param[in] field The time field + * @param[in] amount The amount to roll up/down + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE In this method, time fields of this instance are calculated. @n + * If any time field value previously set is invalid, this exception is returned. + * @exception E_INVALID_ARG The specified @c field is invalid (for example, TIME_FIELD_DST_OFFSET, TIME_FIELD_ZONE_OFFSET). + * @exception E_OUT_OF_RANGE In this method, time fields of this instance are calculated. @n + * If the value of the time fields goes out of range, this exception is returned. + */ + virtual result Roll(TimeField field, int amount); + + + /* + * Gets the millisecond which is midnight, local time at or before the Gregorian cutover. + * + * @since 2.0 + * + * @return The millisecond which is midnight, local time at or before the Gregorian cutover + * If this method fails, @c -1 is returned. + * The specific error code can be accessed using the GetLastResult() method. + */ + long long GetNormalizedGregorianCutover(void) const; + + /* + * Gets the year of the Gregorian cutover, with @c 0 representing 1 BC, @c -1 representing 2 BC, and so on. + * + * @since 2.0 + * + * @return The year of the Gregorian cutover + * If this method fails, @c -1 is returned. + * The specific error code can be accessed using the GetLastResult() method. + */ + int GetGregorianCutoverYear(void) const; + + /* + * Gets the Julian day number of the Gregorian cutover. + * + * @since 2.0 + * + * @return The Julian day number of the Gregorian cutover + */ + int GetCutoverJulianDay(void) const; + + + /** + * Checks whether the current calendar is a Gregorian calendar or not. + * + * @since 2.0 + * + * @return @c true if the current calendar is a Gregorian calendar, @n + * else @c false + */ + bool IsGregorian() const; + + + /** + * Gets the current time of the instance in milliseconds from epoch. + * + * @since 2.0 + * + * @return An error code + * @param[out] millisec The current time in milliseconds from the epoch + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE If any time field value previously set is invalid, this exception is returned. + * @exception E_OUT_OF_RANGE A time field or its value is out of range. + */ + result GetTimeInMillisecFromEpoch(long long& millisec) const; + + + /** + * Sets the current time of the instance with the specified milliseconds value. + * + * @since 2.0 + * + * @return An error code + * @param[in] millisec The new time in milliseconds from the epoch + * @exception E_OUT_OF_RANGE A time field or its value is out of range. + */ + result SetTimeInMillisecFromEpoch(long long millisec); + + + /** + * Converts the 1970-epoch day number to the Gregorian year, month, date, day of week, and day of year. + * + * @since 2.0 + * + * @param[in] day The 1970-epoch day number + * @param[out] year The year to convert + * @param[out] month The month to convert + * @param[out] dayOfMonth The date to convert + * @param[out] dayOfWeek The day of week to convert + * @param[out] dayOfYear The day of year to convert + */ + static void DayToFields(int day, int& year, int& month, int& dayOfMonth, int& dayOfWeek, int& dayOfYear); + +private: + /** + * @enum GregorianCalendarEras + * + * Defines Era for Gregorian calendar. The indexing is 0-based. + */ + enum GregorianCalendarEras + { + GREGORIAN_CALENDAR_BC = 0, // BC + GREGORIAN_CALENDAR_AD = 1, // AD + + GREGORIAN_CALENDAR_BCE = 0, // BCE + GREGORIAN_CALENDAR_CE = 1, // CE + }; + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + GregorianCalendar(const GregorianCalendar& gregorianCalendar); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + GregorianCalendar& operator =(const GregorianCalendar& gregorianCalendar); + + // added for backward compatibility + virtual result RollWithSingleUnit(TimeField field, bool up); + virtual result ComputeTimeFields(void); + virtual result ComputeTime(void); + virtual int GetMonthLength(int extendedYear, int month) const; + virtual int HandleGetLimit(TimeField field, CalendarLimitType limitType) const; + virtual Calendar* CloneN(void) const; + +public: + /** + * Defines the length of months. + * + * @since 2.0 + */ + static const int MONTH_LENGTH[24]; + + /** + * Defines the days of a year. + * + * @since 2.0 + */ + static const int NUM_DAYS[24]; + + /** + * The Gregorian cutover number for Julian day. + * + * @since 2.0 + */ + static const int CUTOVER_JULIAN_DAY = 2299161; // Oct 15, 1582 + + /** + * The epoch year. + * + * @since 2.0 + */ + static const int EPOCH_YEAR = 1970; + + /** + * The epoch start for Julian day. + * + * @since 2.0 + */ + static const int EPOCH_START_AS_JULIAN_DAY = 2440588; // Jan 1, 1970(Gregorian) + + /** + * Jan 1, 1 epoch start for Julian day. + * + * @since 2.0 + */ + static const int JAN_1_1_JULIAN_DAY = 1721426; // Jan 1, 1 CE Gregorian + + /** + * Temporary value for the Gregorian cutover. + * + * @since 2.0 + */ + static const long long PAPAL_CUTOVER = + ((long long) (GregorianCalendar::CUTOVER_JULIAN_DAY - + GregorianCalendar::EPOCH_START_AS_JULIAN_DAY) * (long long) ONE_DAY_IN_MILLISEC); + + /** + * Maximum value for longlong. + * + * @since 2.0 + */ + static const long long MAX_LONGLONG = (2 ^ 63) - 1; + + /** + * Minimum value for longlong. + * + * @since 2.0 + */ + static const long long MIN_LONGLONG = -1 * (2 ^ 63); + + /** + * Maximum value for Julian day. + * + * @since 2.0 + */ + static const int MAX_JULIAN = 0x7F000000; + + /** + * Minimum value for Julian day. + * + * @since 2.0 + */ + static const int MIN_JULIAN = -0x7F000000; + + /** + * Maximum millisecond value for Julian day. + * + * @since 2.0 + */ + static const long long MAX_MILLISEC = ((GregorianCalendar::MAX_JULIAN - GregorianCalendar::EPOCH_START_AS_JULIAN_DAY) * (long long) ONE_DAY_IN_MILLISEC); + + /** + * Minimum millisecond value for Julian day. + * + * @since 2.0 + */ + static const long long MIN_MILLISEC = ((GregorianCalendar::MIN_JULIAN - GregorianCalendar::EPOCH_START_AS_JULIAN_DAY) * (long long) ONE_DAY_IN_MILLISEC); + + /** + * Epoch offset in millisecond value. + * + * @since 2.0 + */ + static const long long EPOCH_OFFSET_IN_MILLISEC = 62135596800000LL; // Jan 1, 1970 + + /** + * Default Gregorian cutover. + * + * @since 2.0 + */ + static const long long DEFAULT_GREGORIAN_CUTOVER = -12219292800000LL; + +private: + long long __normalizedGregorianCutover; // = __gregorianCutover; + int __gregorianCutoverYear; // 1582 + int __cutoverJulianDay; + + friend class _GregorianCalendarImpl; + class _GregorianCalendarImpl* __pGregorianCalendarImpl; + +}; // GregorianCalendar + +}} // Tizen::Locales + +#endif //_FLCL_GREGORIAN_CALENDAR_H_ diff --git a/inc/FLclLocale.h b/inc/FLclLocale.h new file mode 100644 index 0000000..b2a1950 --- /dev/null +++ b/inc/FLclLocale.h @@ -0,0 +1,1176 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclLocale.h + * @brief This is the header file for the %Locale class. + * + * This header file contains the declarations of the %Locale class. + */ +#ifndef _FLCL_LOCALE_H_ +#define _FLCL_LOCALE_H_ + +#include +#include + +namespace Tizen { namespace Locales +{ + +/** + * @enum CalendarType + * + * Defines the calendar type. + * + * @since 2.0 + */ +enum CalendarType +{ + CALENDAR_GREGORIAN, /**< The calendar type: Gregorian calendar (default) */ + CALENDAR_BUDDHIST, /**< The calendar type: Buddhist calendar (same as Gregorian except for the year) */ + CALENDAR_CHINESE, /**< The calendar type: Traditional Chinese calendar */ + CALENDAR_COPTIC, /**< The calendar type: Coptic calendar */ + CALENDAR_ETHIOPIC_AMETE_ALEM, /**< The calendar type: Ethiopic calendar, Amete Alem (epoch approx. 5493 B.C.E.) */ + CALENDAR_ETHIOPIC, /**< The calendar type: Ethiopic calendar, Amete Mihret (epoch approx. 8 C.E.) */ + CALENDAR_HEBREW, /**< The calendar type: TraditionalHebrew calendar */ + CALENDAR_INDIAN, /**< The calendar type: Indian calendar */ + CALENDAR_ISLAMIC, /**< The calendar type: Astronomical Arabic calendar */ + CALENDAR_ISLAMIC_CIVIL, /**< The calendar type: Civil (algorithmic) Arabic calendar */ + CALENDAR_JAPANESE, /**< The calendar type: Japanese Imperial calendar (same as Gregorian except for the year, with one era for each Emperor) */ + CALENDAR_PERSIAN, /**< The calendar type: Persian calendar */ + CALENDAR_ROC, /**< The calendar type: Republic of China calendar */ + CALENDAR_TAIWAN, /**< The calendar type: Taiwan calendar */ + CALENDAR_ISO8601, /**< The calendar type: ISO8601 calendar */ + CALENDAR_COUNT, +}; + +/** + * @enum LanguageCode + * + * Defines the ISO 639-2 language code. @n + * The LanguageCode enumerator represents the ISO 639-2 language codes. @n + * The specified LanguageCode represents the language code with the locale's ISO-15924 abbreviation script code. + * + * @since 2.0 + */ +enum LanguageCode +{ + LANGUAGE_AAR, /**< Afar */ + LANGUAGE_ABK, /**< Abkhazian */ + LANGUAGE_ACE, /**< Achinese */ + LANGUAGE_ACH, /**< Acoli */ + LANGUAGE_ADA, /**< Adangme */ + LANGUAGE_ADY, /**< Adyghe; Adygei */ + LANGUAGE_AFA, /**< Afro-Asiatic languages */ + LANGUAGE_AFH, /**< Afrihili */ + LANGUAGE_AFR, /**< Afrikaans */ + LANGUAGE_AIN, /**< Ainu */ + LANGUAGE_AKA, /**< Akan */ + LANGUAGE_AKK, /**< Akkadian */ + LANGUAGE_SQI, /**< Albanian */ + LANGUAGE_ALE, /**< Aleut */ + LANGUAGE_ALG, /**< Algonquian languages */ + LANGUAGE_ALT, /**< Southern Altai */ + LANGUAGE_AMH, /**< Amharic */ + LANGUAGE_ANG, /**< English, Old (ca.450-1100) */ + LANGUAGE_ANP, /**< Angika */ + LANGUAGE_APA, /**< Apache languages */ + LANGUAGE_ARA, /**< Arabic */ + LANGUAGE_ARC, /**< Official Aramaic (700-300 BCE); Imperial Aramaic (700-300 BCE) */ + LANGUAGE_ARG, /**< Aragonese */ + LANGUAGE_HYE, /**< Armenian */ + LANGUAGE_ARN, /**< Mapudungun; Mapuche */ + LANGUAGE_ARP, /**< Arapaho */ + LANGUAGE_ART, /**< Artificial languages */ + LANGUAGE_ARW, /**< Arawak */ + LANGUAGE_ASM, /**< Assamese */ + LANGUAGE_AST, /**< Asturian; Bable; Leonese; Asturleonese */ + LANGUAGE_ATH, /**< Athapascan languages */ + LANGUAGE_AUS, /**< Australian languages */ + LANGUAGE_AVA, /**< Avaric */ + LANGUAGE_AVE, /**< Avestan */ + LANGUAGE_AWA, /**< Awadhi */ + LANGUAGE_AYM, /**< Aymara */ + LANGUAGE_AZE, /**< Azerbaijani */ + LANGUAGE_AZE_ARAB, /**< Azerbaijani (Arabic) */ + LANGUAGE_AZE_CYRL, /**< Azerbaijani (Cyrillic) */ + LANGUAGE_AZE_LATIN, /**< Azerbaijani (Latin) */ + LANGUAGE_BAD, /**< Banda languages */ + LANGUAGE_BAI, /**< Bamileke languages */ + LANGUAGE_BAK, /**< Bashkir */ + LANGUAGE_BAL, /**< Baluchi */ + LANGUAGE_BAM, /**< Bambara */ + LANGUAGE_BAN, /**< Balinese */ + LANGUAGE_EUS, /**< Basque */ + LANGUAGE_BAS, /**< Basa */ + LANGUAGE_BAT, /**< Baltic languages */ + LANGUAGE_BEJ, /**< Beja; Bedawiyet */ + LANGUAGE_BEL, /**< Belarusian */ + LANGUAGE_BEM, /**< Bemba */ + LANGUAGE_BEN, /**< Bengali */ + LANGUAGE_BER, /**< Berber languages */ + LANGUAGE_BHO, /**< Bhojpuri */ + LANGUAGE_BIH, /**< Bihari */ + LANGUAGE_BIK, /**< Bikol */ + LANGUAGE_BIN, /**< Bini; Edo */ + LANGUAGE_BIS, /**< Bislama */ + LANGUAGE_BLA, /**< Siksika */ + LANGUAGE_BNT, /**< Bantu (Other) */ + LANGUAGE_BOS, /**< Bosnian */ + LANGUAGE_BRA, /**< Braj */ + LANGUAGE_BRE, /**< Breton */ + LANGUAGE_BTK, /**< Batak languages */ + LANGUAGE_BUA, /**< Buriat */ + LANGUAGE_BUG, /**< Buginese */ + LANGUAGE_BUL, /**< Bulgarian */ + LANGUAGE_MYA, /**< Burmese */ + LANGUAGE_BYN, /**< Blin; Bilin */ + LANGUAGE_CAD, /**< Caddo */ + LANGUAGE_CAI, /**< Central American Indian languages */ + LANGUAGE_CAR, /**< Galibi Carib */ + LANGUAGE_CAT, /**< Catalan; Valencian */ + LANGUAGE_CAU, /**< Caucasian languages */ + LANGUAGE_CEB, /**< Cebuano */ + LANGUAGE_CEL, /**< Celtic languages */ + LANGUAGE_CHA, /**< Chamorro */ + LANGUAGE_CHB, /**< Chibcha */ + LANGUAGE_CHE, /**< Chechen */ + LANGUAGE_CHG, /**< Chagatai */ + LANGUAGE_ZHO, /**< Chinese */ + LANGUAGE_ZHO_HANS, /**< Chinese (Simplified) */ + LANGUAGE_ZHO_HANT, /**< Chinese (Traditional) */ + LANGUAGE_CHK, /**< Chuukese */ + LANGUAGE_CHM, /**< Mari */ + LANGUAGE_CHN, /**< Chinook jargon */ + LANGUAGE_CHO, /**< Choctaw */ + LANGUAGE_CHP, /**< Chipewyan; Dene Suline */ + LANGUAGE_CHR, /**< Cherokee */ + LANGUAGE_CHU, /**< Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic */ + LANGUAGE_CHV, /**< Chuvash */ + LANGUAGE_CHY, /**< Cheyenne */ + LANGUAGE_CMC, /**< Chamic languages */ + LANGUAGE_COP, /**< Coptic */ + LANGUAGE_COR, /**< Cornish */ + LANGUAGE_COS, /**< Corsican */ + LANGUAGE_CPE, /**< Creoles and pidgins, English based */ + LANGUAGE_CPF, /**< Creoles and pidgins, French-based */ + LANGUAGE_CPP, /**< Creoles and pidgins, Portuguese-based */ + LANGUAGE_CRE, /**< Cree */ + LANGUAGE_CRH, /**< Crimean Tatar; Crimean Turkish */ + LANGUAGE_CRP, /**< Creoles and pidgins */ + LANGUAGE_CSB, /**< Kashubian */ + LANGUAGE_CUS, /**< Cushitic languages */ + LANGUAGE_CES, /**< Czech */ + LANGUAGE_DAK, /**< Dakota */ + LANGUAGE_DAN, /**< Danish */ + LANGUAGE_DAR, /**< Dargwa */ + LANGUAGE_DAY, /**< Land Dayak languages */ + LANGUAGE_DEL, /**< Delaware */ + LANGUAGE_DEN, /**< Slave (Athapascan) */ + LANGUAGE_DGR, /**< Dogrib */ + LANGUAGE_DIN, /**< Dinka */ + LANGUAGE_DIV, /**< Divehi; Dhivehi; Maldivian */ + LANGUAGE_DOI, /**< Dogri */ + LANGUAGE_DRA, /**< Dravidian languages */ + LANGUAGE_DSB, /**< Lower Sorbian */ + LANGUAGE_DUA, /**< Duala */ + LANGUAGE_DUM, /**< Dutch, Middle (ca.1050-1350) */ + LANGUAGE_NLD, /**< Dutch; Flemish */ + LANGUAGE_DYU, /**< Dyula */ + LANGUAGE_DZO, /**< Dzongkha */ + LANGUAGE_EFI, /**< Efik */ + LANGUAGE_EGY, /**< Egyptian (Ancient) */ + LANGUAGE_EKA, /**< Ekajuk */ + LANGUAGE_ELX, /**< Elamite */ + LANGUAGE_ENG, /**< English */ + LANGUAGE_ENM, /**< English, Middle (1100-1500) */ + LANGUAGE_EPO, /**< Esperanto */ + LANGUAGE_EST, /**< Estonian */ + LANGUAGE_EWE, /**< Ewe */ + LANGUAGE_EWO, /**< Ewondo */ + LANGUAGE_FAN, /**< Fang */ + LANGUAGE_FAO, /**< Faroese */ + LANGUAGE_FAT, /**< Fanti */ + LANGUAGE_FIJ, /**< Fijian */ + LANGUAGE_FIL, /**< Filipino; Pilipino */ + LANGUAGE_FIN, /**< Finnish */ + LANGUAGE_FIU, /**< Finno-Ugrian languages */ + LANGUAGE_FON, /**< Fon */ + LANGUAGE_FRA, /**< French */ + LANGUAGE_FRM, /**< French, Middle (ca.1400-1600) */ + LANGUAGE_FRO, /**< French, Old (842-ca.1400) */ + LANGUAGE_FRR, /**< Northern Frisian */ + LANGUAGE_FRS, /**< Eastern Frisian */ + LANGUAGE_FRY, /**< Western Frisian */ + LANGUAGE_FUL, /**< Fulah */ + LANGUAGE_FUR, /**< Friulian */ + LANGUAGE_GAA, /**< Ga */ + LANGUAGE_GAY, /**< Gayo */ + LANGUAGE_GBA, /**< Gbaya */ + LANGUAGE_GEM, /**< Germanic languages */ + LANGUAGE_KAT, /**< Georgian */ + LANGUAGE_DEU, /**< German */ + LANGUAGE_GEZ, /**< Geez */ + LANGUAGE_GIL, /**< Gilbertese */ + LANGUAGE_GLA, /**< Gaelic; Scottish Gaelic */ + LANGUAGE_GLE, /**< Irish */ + LANGUAGE_GLG, /**< Galician */ + LANGUAGE_GLV, /**< Manx */ + LANGUAGE_GMH, /**< German, Middle High (ca.1050-1500) */ + LANGUAGE_GOH, /**< German, Old High (ca.750-1050) */ + LANGUAGE_GON, /**< Gondi */ + LANGUAGE_GOR, /**< Gorontalo */ + LANGUAGE_GOT, /**< Gothic */ + LANGUAGE_GRB, /**< Grebo */ + LANGUAGE_GRC, /**< Greek, Ancient (to 1453) */ + LANGUAGE_ELL, /**< Greek, Modern (1453-) */ + LANGUAGE_GRN, /**< Guarani */ + LANGUAGE_GSW, /**< Swiss German; Alemannic; Alsatian */ + LANGUAGE_GUJ, /**< Gujarati */ + LANGUAGE_GWI, /**< Gwich'in */ + LANGUAGE_HAI, /**< Haida */ + LANGUAGE_HAT, /**< Haitian; Haitian Creole */ + LANGUAGE_HAU, /**< Hausa */ + LANGUAGE_HAU_LATIN, /**< Hausa (Latin) */ + LANGUAGE_HAW, /**< Hawaiian */ + LANGUAGE_HEB, /**< Hebrew */ + LANGUAGE_HER, /**< Herero */ + LANGUAGE_HIL, /**< Hiligaynon */ + LANGUAGE_HIM, /**< Himachali */ + LANGUAGE_HIN, /**< Hindi */ + LANGUAGE_HIT, /**< Hittite */ + LANGUAGE_HMN, /**< Hmong */ + LANGUAGE_HMO, /**< Hiri Motu */ + LANGUAGE_HRV, /**< Croatian */ + LANGUAGE_HSB, /**< Upper Sorbian */ + LANGUAGE_HUN, /**< Hungarian */ + LANGUAGE_HUP, /**< Hupa */ + LANGUAGE_IBA, /**< Iban */ + LANGUAGE_IBO, /**< Igbo */ + LANGUAGE_ISL, /**< Icelandic */ + LANGUAGE_IDO, /**< Ido */ + LANGUAGE_III, /**< Sichuan Yi; Nuosu */ + LANGUAGE_IJO, /**< Ijo languages */ + LANGUAGE_IKU, /**< Inuktitut */ + LANGUAGE_ILE, /**< Interlingue; Occidental */ + LANGUAGE_ILO, /**< Iloko */ + LANGUAGE_INA, /**< Interlingua (International Auxiliary Language Association) */ + LANGUAGE_INC, /**< Indic languages */ + LANGUAGE_IND, /**< Indonesian */ + LANGUAGE_INE, /**< Indo-European languages */ + LANGUAGE_INH, /**< Ingush */ + LANGUAGE_IPK, /**< Inupiaq */ + LANGUAGE_IRA, /**< Iranian languages */ + LANGUAGE_IRO, /**< Iroquoian languages */ + LANGUAGE_ITA, /**< Italian */ + LANGUAGE_JAV, /**< Javanese */ + LANGUAGE_JBO, /**< Lojban */ + LANGUAGE_JPN, /**< Japanese */ + LANGUAGE_JPR, /**< Judeo-Persian */ + LANGUAGE_JRB, /**< Judeo-Arabic */ + LANGUAGE_KAA, /**< Kara-Kalpak */ + LANGUAGE_KAB, /**< Kabyle */ + LANGUAGE_KAC, /**< Kachin; Jingpho */ + LANGUAGE_KAL, /**< Kalaallisut; Greenlandic */ + LANGUAGE_KAM, /**< Kamba */ + LANGUAGE_KAN, /**< Kannada */ + LANGUAGE_KAR, /**< Karen languages */ + LANGUAGE_KAS, /**< Kashmiri */ + LANGUAGE_KAU, /**< Kanuri */ + LANGUAGE_KAW, /**< Kawi */ + LANGUAGE_KAZ, /**< Kazakh */ + LANGUAGE_KAZ_CYRL, /**< Kazakh (Cyrillic) */ + LANGUAGE_KBD, /**< Kabardian */ + LANGUAGE_KHA, /**< Khasi */ + LANGUAGE_KHI, /**< Khoisan languages */ + LANGUAGE_KHM, /**< Central Khmer */ + LANGUAGE_KHO, /**< Khotanese; Sakan */ + LANGUAGE_KIK, /**< Kikuyu; Gikuyu */ + LANGUAGE_KIN, /**< Kinyarwanda */ + LANGUAGE_KIR, /**< Kirghiz; Kyrgyz */ + LANGUAGE_KMB, /**< Kimbundu */ + LANGUAGE_KOK, /**< Konkani */ + LANGUAGE_KOM, /**< Komi */ + LANGUAGE_KON, /**< Kongo */ + LANGUAGE_KOR, /**< Korean */ + LANGUAGE_KOS, /**< Kosraean */ + LANGUAGE_KPE, /**< Kpelle */ + LANGUAGE_KRC, /**< Karachay-Balkar */ + LANGUAGE_KRL, /**< Karelian */ + LANGUAGE_KRO, /**< Kru languages */ + LANGUAGE_KRU, /**< Kurukh */ + LANGUAGE_KUA, /**< Kuanyama; Kwanyama */ + LANGUAGE_KUM, /**< Kumyk */ + LANGUAGE_KUR, /**< Kurdish */ + LANGUAGE_KUT, /**< Kutenai */ + LANGUAGE_LAD, /**< Ladino */ + LANGUAGE_LAH, /**< Lahnda */ + LANGUAGE_LAM, /**< Lamba */ + LANGUAGE_LAO, /**< Lao */ + LANGUAGE_LAT, /**< Latin */ + LANGUAGE_LAV, /**< Latvian */ + LANGUAGE_LEZ, /**< Lezghian */ + LANGUAGE_LIM, /**< Limburgan; Limburger; Limburgish */ + LANGUAGE_LIN, /**< Lingala */ + LANGUAGE_LIT, /**< Lithuanian */ + LANGUAGE_LOL, /**< Mongo */ + LANGUAGE_LOZ, /**< Lozi */ + LANGUAGE_LTZ, /**< Luxembourgish; Letzeburgesch */ + LANGUAGE_LUA, /**< Luba-Lulua */ + LANGUAGE_LUB, /**< Luba-Katanga */ + LANGUAGE_LUG, /**< Ganda */ + LANGUAGE_LUI, /**< Luiseno */ + LANGUAGE_LUN, /**< Lunda */ + LANGUAGE_LUO, /**< Luo (Kenya and Tanzania) */ + LANGUAGE_LUS, /**< Lushai */ + LANGUAGE_MKD, /**< Macedonian */ + LANGUAGE_MAD, /**< Madurese */ + LANGUAGE_MAG, /**< Magahi */ + LANGUAGE_MAH, /**< Marshallese */ + LANGUAGE_MAI, /**< Maithili */ + LANGUAGE_MAK, /**< Makasar */ + LANGUAGE_MAL, /**< Malayalam */ + LANGUAGE_MAN, /**< Mandingo */ + LANGUAGE_MRI, /**< Maori */ + LANGUAGE_MAP, /**< Austronesian languages */ + LANGUAGE_MAR, /**< Marathi */ + LANGUAGE_MAS, /**< Masai */ + LANGUAGE_MSA, /**< Malay */ + LANGUAGE_MDF, /**< Moksha */ + LANGUAGE_MDR, /**< Mandar */ + LANGUAGE_MEN, /**< Mende */ + LANGUAGE_MGA, /**< Irish, Middle (900-1200) */ + LANGUAGE_MIC, /**< Mi'kmaq; Micmac */ + LANGUAGE_MIN, /**< Minangkabau */ + LANGUAGE_MIS, /**< Uncoded languages */ + LANGUAGE_MKH, /**< Mon-Khmer languages */ + LANGUAGE_MLG, /**< Malagasy */ + LANGUAGE_MLT, /**< Maltese */ + LANGUAGE_MNC, /**< Manchu */ + LANGUAGE_MNI, /**< Manipuri */ + LANGUAGE_MNO, /**< Manobo languages */ + LANGUAGE_MOH, /**< Mohawk */ + LANGUAGE_MON, /**< Mongolian */ + LANGUAGE_MOS, /**< Mossi */ + LANGUAGE_MUL, /**< Multiple languages */ + LANGUAGE_MUN, /**< Munda languages */ + LANGUAGE_MUS, /**< Creek */ + LANGUAGE_MWL, /**< Mirandese */ + LANGUAGE_MWR, /**< Marwari */ + LANGUAGE_MYN, /**< Mayan languages */ + LANGUAGE_MYV, /**< Erzya */ + LANGUAGE_NAH, /**< Nahuatl languages */ + LANGUAGE_NAI, /**< North American Indian languages */ + LANGUAGE_NAP, /**< Neapolitan */ + LANGUAGE_NAU, /**< Nauru */ + LANGUAGE_NAV, /**< Navajo; Navaho */ + LANGUAGE_NBL, /**< Ndebele, South; South Ndebele */ + LANGUAGE_NDE, /**< Ndebele, North; North Ndebele */ + LANGUAGE_NDO, /**< Ndonga */ + LANGUAGE_NDS, /**< Low German; Low Saxon; German, Low; Saxon, Low */ + LANGUAGE_NEP, /**< Nepali */ + LANGUAGE_NEW, /**< Nepal Bhasa; Newari */ + LANGUAGE_NIA, /**< Nias */ + LANGUAGE_NIC, /**< Niger-Kordofanian languages */ + LANGUAGE_NIU, /**< Niuean */ + LANGUAGE_NNO, /**< Norwegian Nynorsk; Nynorsk, Norwegian */ + LANGUAGE_NOB, /**< Bokmal, Norwegian; Norwegian Bokmal */ + LANGUAGE_NOG, /**< Nogai */ + LANGUAGE_NON, /**< Norse, Old */ + LANGUAGE_NOR, /**< Norwegian */ + LANGUAGE_NQO, /**< N'Ko */ + LANGUAGE_NSO, /**< Pedi; Sepedi; Northern Sotho */ + LANGUAGE_NUB, /**< Nubian languages */ + LANGUAGE_NWC, /**< Classical Newari; Old Newari; Classical Nepal Bhasa */ + LANGUAGE_NYA, /**< Chichewa; Chewa; Nyanja */ + LANGUAGE_NYM, /**< Nyamwezi */ + LANGUAGE_NYN, /**< Nyankole */ + LANGUAGE_NYO, /**< Nyoro */ + LANGUAGE_NZI, /**< Nzima */ + LANGUAGE_OCI, /**< Occitan (post 1500); Provencal */ + LANGUAGE_OJI, /**< Ojibwa */ + LANGUAGE_ORI, /**< Oriya */ + LANGUAGE_ORM, /**< Oromo */ + LANGUAGE_OSA, /**< Osage */ + LANGUAGE_OSS, /**< Ossetian; Ossetic */ + LANGUAGE_OTA, /**< Turkish, Ottoman (1500-1928) */ + LANGUAGE_OTO, /**< Otomian languages */ + LANGUAGE_PAA, /**< Papuan languages */ + LANGUAGE_PAG, /**< Pangasinan */ + LANGUAGE_PAL, /**< Pahlavi */ + LANGUAGE_PAM, /**< Pampanga; Kapampangan */ + LANGUAGE_PAN, /**< Panjabi; Punjabi */ + LANGUAGE_PAN_ARAB, /**< Panjabi; Punjabi (Arabic) */ + LANGUAGE_PAN_GURU, /**< Panjabi; Punjabi (Gurmukhi) */ + LANGUAGE_PAP, /**< Papiamento */ + LANGUAGE_PAU, /**< Palauan */ + LANGUAGE_PEO, /**< Persian, Old (ca.600-400 B.C.) */ + LANGUAGE_FAS, /**< Persian */ + LANGUAGE_PHI, /**< Philippine languages */ + LANGUAGE_PHN, /**< Phoenician */ + LANGUAGE_PLI, /**< Pali */ + LANGUAGE_POL, /**< Polish */ + LANGUAGE_PON, /**< Pohnpeian */ + LANGUAGE_POR, /**< Portuguese */ + LANGUAGE_PRA, /**< Prakrit languages */ + LANGUAGE_PRO, /**< Provencal, Old (to 1500) */ + LANGUAGE_PUS, /**< Pushto; Pashto */ + LANGUAGE_QAA_QTZ, /**< Reserved for local use */ + LANGUAGE_QUE, /**< Quechua */ + LANGUAGE_RAJ, /**< Rajasthani */ + LANGUAGE_RAP, /**< Rapanui */ + LANGUAGE_RAR, /**< Rarotongan; Cook Islands Maori */ + LANGUAGE_ROA, /**< Romance languages */ + LANGUAGE_ROH, /**< Romansh */ + LANGUAGE_ROM, /**< Romany */ + LANGUAGE_RON, /**< Romanian; Moldavian; Moldovan */ + LANGUAGE_RUN, /**< Rundi */ + LANGUAGE_RUP, /**< Aromanian; Arumanian; Macedo-Romanian */ + LANGUAGE_RUS, /**< Russian */ + LANGUAGE_SAD, /**< Sandawe */ + LANGUAGE_SAG, /**< Sango */ + LANGUAGE_SAH, /**< Yakut */ + LANGUAGE_SAI, /**< South American Indian (Other) */ + LANGUAGE_SAL, /**< Salishan languages */ + LANGUAGE_SAM, /**< Samaritan Aramaic */ + LANGUAGE_SAN, /**< Sanskrit */ + LANGUAGE_SAS, /**< Sasak */ + LANGUAGE_SAT, /**< Santali */ + LANGUAGE_SCN, /**< Sicilian */ + LANGUAGE_SCO, /**< Scots */ + LANGUAGE_SEL, /**< Selkup */ + LANGUAGE_SEM, /**< Semitic languages */ + LANGUAGE_SGA, /**< Irish, Old (to 900) */ + LANGUAGE_SGN, /**< Sign Languages */ + LANGUAGE_SHN, /**< Shan */ + LANGUAGE_SID, /**< Sidamo */ + LANGUAGE_SIN, /**< Sinhala; Sinhalese */ + LANGUAGE_SIO, /**< Siouan languages */ + LANGUAGE_SIT, /**< Sino-Tibetan languages */ + LANGUAGE_SLA, /**< Slavic languages */ + LANGUAGE_SLK, /**< Slovak */ + LANGUAGE_SLV, /**< Slovenian */ + LANGUAGE_SMA, /**< Southern Sami */ + LANGUAGE_SME, /**< Northern Sami */ + LANGUAGE_SMI, /**< Sami languages */ + LANGUAGE_SMJ, /**< Lule Sami */ + LANGUAGE_SMN, /**< Inari Sami */ + LANGUAGE_SMO, /**< Samoan */ + LANGUAGE_SMS, /**< Skolt Sami */ + LANGUAGE_SNA, /**< Shona */ + LANGUAGE_SND, /**< Sindhi */ + LANGUAGE_SNK, /**< Soninke */ + LANGUAGE_SOG, /**< Sogdian */ + LANGUAGE_SOM, /**< Somali */ + LANGUAGE_SON, /**< Songhai languages */ + LANGUAGE_SOT, /**< Sotho, Southern */ + LANGUAGE_SPA, /**< Spanish; Castilian */ + LANGUAGE_SRD, /**< Sardinian */ + LANGUAGE_SRN, /**< Sranan Tongo */ + LANGUAGE_SRP, /**< Serbian */ + LANGUAGE_SRP_CYRL, /**< Serbian (Cyrillic) */ + LANGUAGE_SRP_LATIN, /**< Serbian (Latin) */ + LANGUAGE_SRR, /**< Serer */ + LANGUAGE_SSA, /**< Nilo-Saharan languages */ + LANGUAGE_SSW, /**< Swati */ + LANGUAGE_SUK, /**< Sukuma */ + LANGUAGE_SUN, /**< Sundanese */ + LANGUAGE_SUS, /**< Susu */ + LANGUAGE_SUX, /**< Sumerian */ + LANGUAGE_SWA, /**< Swahili */ + LANGUAGE_SWE, /**< Swedish */ + LANGUAGE_SYC, /**< Classical Syriac */ + LANGUAGE_SYR, /**< Syriac */ + LANGUAGE_TAH, /**< Tahitian */ + LANGUAGE_TAI, /**< Tai languages */ + LANGUAGE_TAM, /**< Tamil */ + LANGUAGE_TAT, /**< Tatar */ + LANGUAGE_TEL, /**< Telugu */ + LANGUAGE_TEM, /**< Timne */ + LANGUAGE_TER, /**< Tereno */ + LANGUAGE_TET, /**< Tetum */ + LANGUAGE_TGK, /**< Tajik */ + LANGUAGE_TGL, /**< Tagalog */ + LANGUAGE_THA, /**< Thai */ + LANGUAGE_BOD, /**< Tibetan */ + LANGUAGE_TIG, /**< Tigre */ + LANGUAGE_TIR, /**< Tigrinya */ + LANGUAGE_TIV, /**< Tiv */ + LANGUAGE_TKL, /**< Tokelau */ + LANGUAGE_TLH, /**< Klingon; tlhIngan-Hol */ + LANGUAGE_TLI, /**< Tlingit */ + LANGUAGE_TMH, /**< Tamashek */ + LANGUAGE_TOG, /**< Tonga (Nyasa) */ + LANGUAGE_TON, /**< Tonga (Tonga Islands) */ + LANGUAGE_TPI, /**< Tok Pisin */ + LANGUAGE_TSI, /**< Tsimshian */ + LANGUAGE_TSN, /**< Tswana */ + LANGUAGE_TSO, /**< Tsonga */ + LANGUAGE_TUK, /**< Turkmen */ + LANGUAGE_TUK_CYRL, /**< Turkmen (Cyrillic) */ + LANGUAGE_TUK_LATIN, /**< Turkmen (Latin) */ + LANGUAGE_TUM, /**< Tumbuka */ + LANGUAGE_TUP, /**< Tupi languages */ + LANGUAGE_TUR, /**< Turkish */ + LANGUAGE_TUT, /**< Altaic languages */ + LANGUAGE_TVL, /**< Tuvalu */ + LANGUAGE_TWI, /**< Twi */ + LANGUAGE_TYV, /**< Tuvinian */ + LANGUAGE_UDM, /**< Udmurt */ + LANGUAGE_UGA, /**< Ugaritic */ + LANGUAGE_UIG, /**< Uighur; Uyghur */ + LANGUAGE_UKR, /**< Ukrainian */ + LANGUAGE_UMB, /**< Umbundu */ + LANGUAGE_UND, /**< Undetermined */ + LANGUAGE_URD, /**< Urdu */ + LANGUAGE_UZB, /**< Uzbek */ + LANGUAGE_UZB_ARAB, /**< Uzbek (Arabic) */ + LANGUAGE_UZB_CYRL, /**< Uzbek (Cyrillic) */ + LANGUAGE_UZB_LATIN, /**< Uzbek (Latin) */ + LANGUAGE_VAI, /**< Vai */ + LANGUAGE_VEN, /**< Venda */ + LANGUAGE_VIE, /**< Vietnamese */ + LANGUAGE_VLS, /**< Vlaams; Flemish" */ + LANGUAGE_VOL, /**< Volapuk */ + LANGUAGE_VOT, /**< Votic */ + LANGUAGE_WAK, /**< Wakashan languages */ + LANGUAGE_WAL, /**< Walamo */ + LANGUAGE_WAR, /**< Waray */ + LANGUAGE_WAS, /**< Washo */ + LANGUAGE_CYM, /**< Welsh */ + LANGUAGE_WEN, /**< Sorbian languages */ + LANGUAGE_WLN, /**< Walloon */ + LANGUAGE_WOL, /**< Wolof */ + LANGUAGE_XAL, /**< Kalmyk; Oirat */ + LANGUAGE_XHO, /**< Xhosa */ + LANGUAGE_YAO, /**< Yao */ + LANGUAGE_YAP, /**< Yapese */ + LANGUAGE_YID, /**< Yiddish */ + LANGUAGE_YOR, /**< Yoruba */ + LANGUAGE_YPK, /**< Yupik languages */ + LANGUAGE_ZAP, /**< Zapotec */ + LANGUAGE_ZBL, /**< Blissymbols; Blissymbolics; Bliss */ + LANGUAGE_ZEN, /**< Zenaga */ + LANGUAGE_ZHA, /**< Zhuang; Chuang */ + LANGUAGE_ZND, /**< Zande languages */ + LANGUAGE_ZUL, /**< Zulu */ + LANGUAGE_ZUN, /**< Zuni */ + LANGUAGE_ZXX, /**< No linguistic content; Not applicable */ + LANGUAGE_ZZA, /**< Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki */ + LANGUAGE_MAX, // Language max count + LANGUAGE_INVALID /**< An invalid language code */ +}; // LanguageCode + + +/** + * @enum CountryCode + * + * Defines the ISO 3166-1 alpha-2 country code. @n + * The CountryCode enumerator represents the ISO 3166-1 alpha-2 country codes. + * + * @since 2.0 + */ +enum CountryCode +{ + COUNTRY_AF, /**< AFGHANISTAN */ + COUNTRY_AX, /**< ALAND ISLANDS */ + COUNTRY_AL, /**< ALBANIA */ + COUNTRY_DZ, /**< ALGERIA */ + COUNTRY_AS, /**< AMERICAN SAMOA */ + COUNTRY_AD, /**< ANDORRA */ + COUNTRY_AO, /**< ANGOLA */ + COUNTRY_AI, /**< ANGUILLA */ + COUNTRY_AQ, /**< ANTARCTICA */ + COUNTRY_AG, /**< ANTIGUA AND BARBUDA */ + COUNTRY_AR, /**< ARGENTINA */ + COUNTRY_AM, /**< ARMENIA */ + COUNTRY_AW, /**< ARUBA */ + COUNTRY_AU, /**< AUSTRALIA */ + COUNTRY_AT, /**< AUSTRIA */ + COUNTRY_AZ, /**< AZERBAIJAN */ + COUNTRY_BS, /**< BAHAMAS */ + COUNTRY_BH, /**< BAHRAIN */ + COUNTRY_BD, /**< BANGLADESH */ + COUNTRY_BB, /**< BARBADOS */ + COUNTRY_BY, /**< BELARUS */ + COUNTRY_BE, /**< BELGIUM */ + COUNTRY_BZ, /**< BELIZE */ + COUNTRY_BJ, /**< BENIN */ + COUNTRY_BM, /**< BERMUDA */ + COUNTRY_BT, /**< BHUTAN */ + COUNTRY_BO, /**< BOLIVIA */ + COUNTRY_BA, /**< BOSNIA AND HERZEGOVINA */ + COUNTRY_BW, /**< BOTSWANA */ + COUNTRY_BV, /**< BOUVET ISLAND */ + COUNTRY_BR, /**< BRAZIL */ + COUNTRY_IO, /**< BRITISH INDIAN OCEAN TERRITORY */ + COUNTRY_BN, /**< BRUNEI DARUSSALAM */ + COUNTRY_BG, /**< BULGARIA */ + COUNTRY_BF, /**< BURKINA FASO */ + COUNTRY_BI, /**< BURUNDI */ + COUNTRY_KH, /**< CAMBODIA */ + COUNTRY_CM, /**< CAMEROON */ + COUNTRY_CA, /**< CANADA */ + COUNTRY_CV, /**< CAPE VERDE */ + COUNTRY_KY, /**< CAYMAN ISLANDS */ + COUNTRY_CF, /**< CENTRAL AFRICAN REPUBLIC */ + COUNTRY_TD, /**< CHAD */ + COUNTRY_CL, /**< CHILE */ + COUNTRY_CN, /**< CHINA */ + COUNTRY_CX, /**< CHRISTMAS ISLAND */ + COUNTRY_CC, /**< COCOS (KEELING) ISLANDS */ + COUNTRY_CO, /**< COLOMBIA */ + COUNTRY_KM, /**< COMOROS */ + COUNTRY_CG, /**< CONGO */ + COUNTRY_CD, /**< CONGO, THE DEMOCRATIC REPUBLIC OF THE */ + COUNTRY_CK, /**< COOK ISLANDS */ + COUNTRY_CR, /**< COSTA RICA */ + COUNTRY_CI, /**< COTE D'IVOIRE */ + COUNTRY_HR, /**< CROATIA */ + COUNTRY_CU, /**< CUBA */ + COUNTRY_CY, /**< CYPRUS */ + COUNTRY_CZ, /**< CZECH REPUBLIC */ + COUNTRY_DK, /**< DENMARK */ + COUNTRY_DJ, /**< DJIBOUTI */ + COUNTRY_DM, /**< DOMINICA */ + COUNTRY_DO, /**< DOMINICAN REPUBLIC */ + COUNTRY_EC, /**< ECUADOR */ + COUNTRY_EG, /**< EGYPT */ + COUNTRY_SV, /**< EL SALVADOR */ + COUNTRY_GQ, /**< EQUATORIAL GUINEA */ + COUNTRY_ER, /**< ERITREA */ + COUNTRY_EE, /**< ESTONIA */ + COUNTRY_ET, /**< ETHIOPIA */ + COUNTRY_FK, /**< FALKLAND ISLANDS (MALVINAS) */ + COUNTRY_FO, /**< FAROE ISLANDS */ + COUNTRY_FJ, /**< FIJI */ + COUNTRY_FI, /**< FINLAND */ + COUNTRY_FR, /**< FRANCE */ + COUNTRY_GF, /**< FRENCH GUIANA */ + COUNTRY_PF, /**< FRENCH POLYNESIA */ + COUNTRY_TF, /**< FRENCH SOUTHERN TERRITORIES */ + COUNTRY_GA, /**< GABON */ + COUNTRY_GM, /**< GAMBIA */ + COUNTRY_GE, /**< GEORGIA */ + COUNTRY_DE, /**< GERMANY */ + COUNTRY_GH, /**< GHANA */ + COUNTRY_GI, /**< GIBRALTAR */ + COUNTRY_GR, /**< GREECE */ + COUNTRY_GL, /**< GREENLAND */ + COUNTRY_GD, /**< GRENADA */ + COUNTRY_GP, /**< GUADELOUPE */ + COUNTRY_GU, /**< GUAM */ + COUNTRY_GT, /**< GUATEMALA */ + COUNTRY_GN, /**< GUINEA */ + COUNTRY_GW, /**< GUINEA-BISSAU */ + COUNTRY_GY, /**< GUYANA */ + COUNTRY_HT, /**< HAITI */ + COUNTRY_HM, /**< HEARD ISLAND AND MCDONALD ISLANDS */ + COUNTRY_VA, /**< HOLY SEE (VATICAN CITY STATE) */ + COUNTRY_HN, /**< HONDURAS */ + COUNTRY_HK, /**< HONG KONG */ + COUNTRY_HU, /**< HUNGARY */ + COUNTRY_IS, /**< ICELAND */ + COUNTRY_IN, /**< INDIA */ + COUNTRY_ID, /**< INDONESIA */ + COUNTRY_IR, /**< IRAN, ISLAMIC REPUBLIC OF */ + COUNTRY_IQ, /**< IRAQ */ + COUNTRY_IE, /**< IRELAND */ + COUNTRY_IL, /**< ISRAEL */ + COUNTRY_IT, /**< ITALY */ + COUNTRY_JM, /**< JAMAICA */ + COUNTRY_JP, /**< JAPAN */ + COUNTRY_JO, /**< JORDAN */ + COUNTRY_KZ, /**< KAZAKHSTAN */ + COUNTRY_KE, /**< KENYA */ + COUNTRY_KI, /**< KIRIBATI */ + COUNTRY_KP, /**< KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF */ + COUNTRY_KR, /**< KOREA, REPUBLIC OF */ + COUNTRY_KW, /**< KUWAIT */ + COUNTRY_KG, /**< KYRGYZSTAN */ + COUNTRY_LA, /**< LAO PEOPLE'S DEMOCRATIC REPUBLIC */ + COUNTRY_LV, /**< LATVIA */ + COUNTRY_LB, /**< LEBANON */ + COUNTRY_LS, /**< LESOTHO */ + COUNTRY_LR, /**< LIBERIA */ + COUNTRY_LY, /**< LIBYAN ARAB JAMAHIRIYA */ + COUNTRY_LI, /**< LIECHTENSTEIN */ + COUNTRY_LT, /**< LITHUANIA */ + COUNTRY_LU, /**< LUXEMBOURG */ + COUNTRY_MO, /**< MACAO */ + COUNTRY_MK, /**< MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF */ + COUNTRY_MG, /**< MADAGASCAR */ + COUNTRY_MW, /**< MALAWI */ + COUNTRY_MY, /**< MALAYSIA */ + COUNTRY_MV, /**< MALDIVES */ + COUNTRY_ML, /**< MALI */ + COUNTRY_MT, /**< MALTA */ + COUNTRY_MH, /**< MARSHALL ISLANDS */ + COUNTRY_MQ, /**< MARTINIQUE */ + COUNTRY_MR, /**< MAURITANIA */ + COUNTRY_MU, /**< MAURITIUS */ + COUNTRY_YT, /**< MAYOTTE */ + COUNTRY_MX, /**< MEXICO */ + COUNTRY_FM, /**< MICRONESIA, FEDERATED STATES OF */ + COUNTRY_MD, /**< MOLDOVA, REPUBLIC OF */ + COUNTRY_MC, /**< MONACO */ + COUNTRY_MN, /**< MONGOLIA */ + COUNTRY_MS, /**< MONTSERRAT */ + COUNTRY_MA, /**< MOROCCO */ + COUNTRY_MZ, /**< MOZAMBIQUE */ + COUNTRY_MM, /**< MYANMAR */ + COUNTRY_NA, /**< NAMIBIA */ + COUNTRY_NR, /**< NAURU */ + COUNTRY_NP, /**< NEPAL */ + COUNTRY_NL, /**< NETHERLANDS */ + COUNTRY_AN, /**< NETHERLANDS ANTILLES */ + COUNTRY_NC, /**< NEW CALEDONIA */ + COUNTRY_NZ, /**< NEW ZEALAND */ + COUNTRY_NI, /**< NICARAGUA */ + COUNTRY_NE, /**< NIGER */ + COUNTRY_NG, /**< NIGERIA */ + COUNTRY_NU, /**< NIUE */ + COUNTRY_NF, /**< NORFOLK ISLAND */ + COUNTRY_MP, /**< NORTHERN MARIANA ISLANDS */ + COUNTRY_NO, /**< NORWAY */ + COUNTRY_OM, /**< OMAN */ + COUNTRY_PK, /**< PAKISTAN */ + COUNTRY_PW, /**< PALAU */ + COUNTRY_PS, /**< PALESTINIAN TERRITORY, OCCUPIED */ + COUNTRY_PA, /**< PANAMA */ + COUNTRY_PG, /**< PAPUA NEW GUINEA */ + COUNTRY_PY, /**< PARAGUAY */ + COUNTRY_PE, /**< PERU */ + COUNTRY_PH, /**< PHILIPPINES */ + COUNTRY_PN, /**< PITCAIRN */ + COUNTRY_PL, /**< POLAND */ + COUNTRY_PT, /**< PORTUGAL */ + COUNTRY_PR, /**< PUERTO RICO */ + COUNTRY_QA, /**< QATAR */ + COUNTRY_RE, /**< REUNION */ + COUNTRY_RO, /**< ROMANIA */ + COUNTRY_RU, /**< RUSSIAN FEDERATION */ + COUNTRY_RW, /**< RWANDA */ + COUNTRY_SH, /**< SAINT HELENA */ + COUNTRY_KN, /**< SAINT KITTS AND NEVIS */ + COUNTRY_LC, /**< SAINT LUCIA */ + COUNTRY_PM, /**< SAINT PIERRE AND MIQUELON */ + COUNTRY_VC, /**< SAINT VINCENT AND THE GRENADINES */ + COUNTRY_WS, /**< SAMOA */ + COUNTRY_SM, /**< SAN MARINO */ + COUNTRY_ST, /**< SAO TOME AND PRINCIPE */ + COUNTRY_SA, /**< SAUDI ARABIA */ + COUNTRY_SN, /**< SENEGAL */ + COUNTRY_SC, /**< SEYCHELLES */ + COUNTRY_SL, /**< SIERRA LEONE */ + COUNTRY_SG, /**< SINGAPORE */ + COUNTRY_SK, /**< SLOVAKIA */ + COUNTRY_SI, /**< SLOVENIA */ + COUNTRY_SB, /**< SOLOMON ISLANDS */ + COUNTRY_SO, /**< SOMALIA */ + COUNTRY_ZA, /**< SOUTH AFRICA */ + COUNTRY_GS, /**< SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS */ + COUNTRY_ES, /**< SPAIN */ + COUNTRY_LK, /**< SRI LANKA */ + COUNTRY_SD, /**< SUDAN */ + COUNTRY_SR, /**< SURINAME */ + COUNTRY_SJ, /**< SVALBARD AND JAN MAYEN */ + COUNTRY_SZ, /**< SWAZILAND */ + COUNTRY_SE, /**< SWEDEN */ + COUNTRY_CH, /**< SWITZERLAND */ + COUNTRY_SY, /**< SYRIAN ARAB REPUBLIC */ + COUNTRY_TW, /**< TAIWAN, PROVINCE OF CHINA */ + COUNTRY_TJ, /**< TAJIKISTAN */ + COUNTRY_TZ, /**< TANZANIA, UNITED REPUBLIC OF */ + COUNTRY_TH, /**< THAILAND */ + COUNTRY_TL, /**< TIMOR-LESTE */ + COUNTRY_TG, /**< TOGO */ + COUNTRY_TK, /**< TOKELAU */ + COUNTRY_TO, /**< TONGA */ + COUNTRY_TT, /**< TRINIDAD AND TOBAGO */ + COUNTRY_TN, /**< TUNISIA */ + COUNTRY_TR, /**< TURKEY */ + COUNTRY_TM, /**< TURKMENISTAN */ + COUNTRY_TC, /**< TURKS AND CAICOS ISLANDS */ + COUNTRY_TV, /**< TUVALU */ + COUNTRY_UG, /**< UGANDA */ + COUNTRY_UA, /**< UKRAINE */ + COUNTRY_AE, /**< UNITED ARAB EMIRATES */ + COUNTRY_GB, /**< UNITED KINGDOM */ + COUNTRY_US, /**< UNITED STATES */ + COUNTRY_UM, /**< UNITED STATES MINOR OUTLYING ISLANDS */ + COUNTRY_UY, /**< URUGUAY */ + COUNTRY_UZ, /**< UZBEKISTAN */ + COUNTRY_VU, /**< VANUATU */ + COUNTRY_VE, /**< VENEZUELA */ + COUNTRY_VN, /**< VIET NAM */ + COUNTRY_VG, /**< VIRGIN ISLANDS, BRITISH */ + COUNTRY_VI, /**< VIRGIN ISLANDS, U.S. */ + COUNTRY_WF, /**< WALLIS AND FUTUNA */ + COUNTRY_EH, /**< WESTERN SAHARA */ + COUNTRY_YE, /**< YEMEN */ + COUNTRY_ZM, /**< ZAMBIA */ + COUNTRY_ZW, /**< ZIMBABWE */ + COUNTRY_RS, /**< SERBIA */ + COUNTRY_ME, /**< MONTENEGRO */ + COUNTRY_MAX, //< Country max count + COUNTRY_INVALID, //< invalid country code +}; + + +/** + * @class Locale + * @brief This class is for the locale identification. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * @remarks For more information on the example codes for %Locale class, see LocaleManager. + * + * The %Locale class represents a specific geographical, political, or cultural region. @n + * A %Locale object has three attributes: + * - Language Code + * - Country Code + * - Variant Code + * + * For more information on the class features, see Retrieving Language and Country Codes. + * + * @see LanguageCode + * @see CountryCode + * @see LocaleManager + */ + +class _OSP_EXPORT_ Locale + : public Tizen::Base::Object +{ +public: + /** + * Initializes an instance of %Locale with the values of the specified locale. @n + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] otherLocale An instance of %Locale + */ + Locale(const Locale& otherLocale); + + /** + * Initializes an instance of %Locale with the specified language, country, and variant code. + * + * @since 2.0 + * + * @param[in] languageCode The language code + * @param[in] countryCode The country code + * @param[in] pVariantCodeString A pointer to the variant code string @n + * It is converted to a uppercase letter if it is written in a lowercase letter. + */ + Locale(LanguageCode languageCode, CountryCode countryCode, const Tizen::Base::String* pVariantCodeString = null); + + /** + * Assigns the value of the specified instance to the current instance of %Locale. @n + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return A reference to the current instance of %Locale + * @param[in] otherLocale An instance of %Locale + */ + Locale& operator =(const Locale& otherLocale); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Locale(void); + + /** + * Compares the current instance of %Locale with the specified instance of %Locale. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance is equal to the value of the current instance, @n + * else @c false + * @param[in] otherLocale An instance of %Locale + */ + bool operator ==(const Locale& otherLocale) const; + + /** + * Compares the current instance of %Locale with the specified instance of %Locale. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance is not equal to the value of the current instance, @n + * else @c false + * @param[in] otherLocale An instance of %Locale + */ + bool operator !=(const Locale& otherLocale) const; + + /** + * Converts the operand @c obj to an object of the %Locale type and then compares it with the current instance of %Locale. + * + * @since 2.0 + * + * @return @c true if the value of the current instance is equal to the value of the specified Tizen::Base::Object, @n + * else @c false + * @param[in] obj The object to compare with the current instance + * @see Tizen::Base::Object::Equals() + */ + virtual bool Equals(const Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Gets the language code (ISO 639-2 code) of the current instance of %Locale. + * + * @since 2.0 + * + * @return The language code enum value of the instance + */ + LanguageCode GetLanguageCode(void) const; + + /** + * Gets the country code (ISO 3166-1 alpha-2 code) or the area code (ISO 3166-1 numeric-3 code) of the current instance of %Locale. + * + * @since 2.0 + * + * @return The country code enum value of the instance + */ + CountryCode GetCountryCode(void) const; + + /** + * Gets the language code (ISO 639-2 code) string of the current instance of %Locale. + * + * @since 2.0 + * + * @return The language code + */ + Tizen::Base::String GetLanguageCodeString(void) const; + + /** + * Gets the country code (ISO 3166-1 alpha-2 code) or the area code (ISO 3166-1 numeric-3 code) string of the current instance of %Locale. + * + * @since 2.0 + * + * @return The country code @n + * else the area code if the country code represents Latin America. + */ + Tizen::Base::String GetCountryCodeString(void) const; + + /** + * Gets the variant code string of the current instance of %Locale. + * + * @since 2.0 + * + * @return The variant code string written in a uppercase letter even if it was set to a lowercase letter, @n + * else an empty string if the variant is not specified + * @see SetVariantCodeString() + */ + Tizen::Base::String GetVariantCodeString(void) const; + + + /** + * Gets the string representing the current instance of %Locale. @n + * The string consists of the values returned by GetLanguageCodeString(), GetCountryCodeString(), and GetVariantCodeString() assembled into a string. + * + * @since 2.0 + * + * @return A concatenated string with the language code string, country code string, and variant string @n + * For example, if the language code is LANGUAGE_ENG, country code is COUNTRY_US, and variant string is empty, @n + * the locale code string is "eng_US". + * @see GetLanguageCodeString() + * @see GetCountryCodeString() + * @see GetVariantCodeString() + */ + Tizen::Base::String GetLocaleCodeString(void) const; + + /** + * Gets the country name of the current instance of %Locale that is appropriate for display to the user. @n + * The name is localized for this locale. For example, if this locale is eng_US, the name is "United States". + * + * @since 2.0 + * + * @return An error code + * @param[out] countryName The country name of the locale + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_OPERATION The current @c locale does not have country name entry in the database. + */ + result GetCountryName(Tizen::Base::String& countryName) const; + + /** + * Gets the country name of the current instance of %Locale that is appropriate for display to the user in the specified %Locale. @n + * The country name is localized for the specified locale(@c otherLocale). For example, if + * the current instance of %Locale is fra_FR and the @c otherLocale is eng_US, the name is "France"; + * if the current instance is eng_US and the @c otherLocale is fra_FR, the name returned is "Etats-Unis". + * + * @since 2.0 + * + * @return An error code + * @param[in] otherLocale An instance of %Locale according to which the country name of the specified %Locale is displayed + * @param[out] countryName The country name of the locale + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_OPERATION The specified @c locale is not supported, or the current @c locale does not have country name entry in the database. + */ + result GetCountryName(const Locale& otherLocale, Tizen::Base::String& countryName) const; + + /** + * Gets the language name of the current instance of %Locale that is appropriate for display to the user. @n + * The name is localized for the locale. For example, if this locale is + * eng_US, the name is "English". + * + * @since 2.0 + * + * @return An error code + * @param[out] languageName The language name of the locale + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_OPERATION The current @c locale does not have country name entry in the database. + */ + result GetLanguageName(Tizen::Base::String& languageName) const; + + /** + * Gets the language name of the current instance of %Locale that is appropriate for display to the user in the specified %Locale. @n + * The name is localized for the specified locale (@c otherLocale). For example, if + * the current instance is fra_FR and the @c otherLocale is eng_US, the name is "French"; + * if the current instance is engUS and the @c otherLocale is fra_FR, the name returned is "anglais". + * + * @since 2.0 + * + * @return An error code + * @param[in] otherLocale An instance of %Locale according to which the language name of the specified %Locale is displayed + * @param[out] languageName The language name of the locale + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_OPERATION The specified @c locale is not supported, or the current @c locale does not have country name entry in the database. + */ + result GetLanguageName(const Locale& otherLocale, Tizen::Base::String& languageName) const; + + /** + * Sets the variant code with the specified variant code string. @n + * The variant code string is converted to a uppercase letter even if it is set to a lowercase letter. + * + * @since 2.0 + * + * @param[in] pVariantCode A pointer to the variant code + */ + void SetVariantCodeString(const Tizen::Base::String* pVariantCode = null); + + /** + * Gets the language code equivalent to the specified language code string. + * + * @since 2.0 + * + * @param[in] languageCodeString The language code + * @return An instance of LanguageCode associated with the @c languageCodeString. + */ + static LanguageCode StringToLanguageCode(const Tizen::Base::String& languageCodeString); + + /** + * Gets the country code equivalent to the specified country code string. + * + * @since 2.0 + * + * @param[in] countryCodeString The country code + * @return An instance of CountryCode associated with the @c countryCodeString. + */ + static CountryCode StringToCountryCode(const Tizen::Base::String& countryCodeString); + + /** + * Gets the language code string equivalent to the specified @c languageCode. + * + * @since 2.0 + * + * @param[in] languageCode The language code + * @return The language code string associated with the @c languageCode, @n + * else an empty string if languageCode is invaild. + */ + static Tizen::Base::String LanguageCodeToString(LanguageCode languageCode); + + /** + * Gets the country code string equivalent to the specified @c countryCode. + * + * @since 2.0 + * + * @param[in] countryCode The country code + * @return The ISO 3166-1 alpha-2 country code string associated with the @c countryCode, @n + * else an empty string if countryCode is invaild. + */ + static Tizen::Base::String CountryCodeToString(CountryCode countryCode); + + /** + * Gets the 2-letter language code string equivalent to the specified @c languageCode. + * + * @since 2.0 + * + * @param[in] languageCode The language code + * @return The ISO 639-2 language code string associated with the @c languageCode, @n + * else an empty string if languageCode is invaild. + */ + static Tizen::Base::String LanguageCodeToTwoLetterLanguageCodeString(LanguageCode languageCode); + + /** + * Gets the language code equivalent to the specified 2-letter language code string. + * + * @since 2.0 + * + * @param[in] languageCodeString The language code string + * @return An instance of LanguageCode associated with the @c languageCodeString. + */ + static LanguageCode TwoLetterLanguageCodeStringToLanguageCode(const Tizen::Base::String& languageCodeString); + + /** + * Gets the 3-letter country code string equivalent to the specified @c countryCode. + * + * @since 2.0 + * + * @param[in] countryCode The country code + * @return The ISO 3166-1 alpha-3 country code string associated with the @c countryCode, @n + * else an empty string if countryCode is invaild + * @see CountryCodeToString() + */ + static Tizen::Base::String CountryCodeToThreeLetterCountryCodeString(CountryCode countryCode); + + /** + * Gets the country code equivalent to the specified 3-letter country code string. + * + * @since 2.0 + * + * @param[in] countryCodeString The country code string + * @return An instance of CountryCode associated with the @c countryCodeString. + * @see StringToCountryCode() + */ + static CountryCode ThreeLetterCountryCodeStringToCountryCode(const Tizen::Base::String& countryCodeString); + +private: + + LanguageCode __languageCode; + CountryCode __countryCode; + + friend class _LocaleImpl; + class _LocaleImpl* __pLocaleImpl; + +}; // Locale + +}} // Tizen::Locales + +#endif //_FLCL_LOCALE_H_ diff --git a/inc/FLclLocaleManager.h b/inc/FLclLocaleManager.h new file mode 100644 index 0000000..43df3c5 --- /dev/null +++ b/inc/FLclLocaleManager.h @@ -0,0 +1,306 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclLocaleManager.h + * @brief This is the header file for the %LocaleManager class. + * + * This header file contains the declarations of the %LocaleManager class. + * + */ +#ifndef _FLCL_LOCALE_MANAGER_H_ +#define _FLCL_LOCALE_MANAGER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Locales +{ + +/** + * @class LocaleManager + * @brief This class is used for the %LocaleManager identification. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %LocaleManager class helps application programmers handle the system locale information of the device. Each device system has at least one installed locale and often has many locales from which the user can choose. + * + * For more information on the class features, see Retrieving Language and Country Codes. + + * @see Locale + * @see NumberFormatter + * @see DateTimeFormatter + * + * The following example demonstrates how to use the %LocaleManager class to get and set system locale information. + * + * @code + +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Locales; + +void +LocaleApp::LocaleExample1(void) +{ + LocaleManager localeManager; + localeManager.Construct(); + + // Gets the system locale information. + Locale systemLocale = localeManager.GetSystemLocale(); + + String countryCodeString = systemLocale.GetCountryCodeString(); + String languageCodeString = systemLocale.GetLanguageCodeString(); + String variantCodString = systemLocale.GetVariantCodeString(); + + // Gets the formatted number that is localized. + NumberFormatter* pNumberFormatter = NumberFormatter::CreateNumberFormatterN(systemLocale); + + String formattedString; + long inputNumber = 123456; + pNumberFormatter->Format((long) inputNumber, formattedString); + + // Gets the formatted date/time that is localized. + DateTimeFormatter* pDateTimeFormatter = DateTimeFormatter::CreateDateTimeFormatterN(systemLocale); + DateTime dateTime(2009, 2, 24, 15, 22, 00); + pDateTimeFormatter->Format(dateTime, formattedString); + + // Gets the currency symbol that is localized. + NumberFormatter* pCurrencyFormatter = NumberFormatter::CreateCurrencyFormatterN(systemLocale); + inputNumber = 4000; + pCurrencyFormatter->Format(inputNumber, formattedString); + + + delete pNumberFormatter; + delete pDateTimeFormatter; + delete pCurrencyFormatter; +} + +@endcode + * + * The following example demonstrates how to use the %LocaleManager class to get a list of all the available locales from the system. + * + * @code + +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Locales; + +void +LocaleApp::LocaleExample2(void) +{ + LocaleManager localeManager; + localeManager.Construct(); + + IList* pAvailableLocales = localeManager.GetAvailableLocalesN(); + if (pAvailableLocales) + { + for (int i = 0; i < pAvailableLocales->GetCount(); i++) + { + Locale* pLocale = (Locale*) (pAvailableLocales->GetAt(i)); + + String languageCodeString = pLocale->GetLanguageCodeString(); + String countryCodeString = pLocale->GetCountryCodeString(); + String variantCodString = pLocale->GetVariantCodeString(); + + // ... + } + } +} + +@endcode + + * + */ +class _OSP_EXPORT_ LocaleManager + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. @n + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @see Construct() + * + */ + LocaleManager(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~LocaleManager(void); + + /** + * Initializes this instance of %LocaleManager. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(void); + + + /** + * Gets the system locale of the device. + * + * @since 2.0 + * + * @return An instance of Locale + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * The resulting Locale instance is Locale (LANGUAGE_INVALID, COUNTRY_INVALID). + */ + Locale GetSystemLocale(void) const; + + + /** + * Gets a list of all the available locales. + * + * @since 2.0 + * + * @return A list of Locale instances, @n + * else @c null if the method fails + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The IList returned contains the list of all the locales installed on the system. + * The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetAvailableLocalesN(void) const; + + + /** + * Gets the currently selected language of the device by a user from the user setting menu. + * + * @since 2.0 + * + * @return An instance of Tizen::Base::String (ISO 639-2 code format), @n + * else empty string if the method fails + * @exception E_SUCCESS The method is successful. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::String GetSelectedLanguage(void) const; + + + /** + * Gets a list of all the available languages supported by the device, which can be different according to the target country/region of the device. + * + * @since 2.0 + * + * @return A list of Tizen::Base::String instances (ISO 639-2 code format), @n + * else @c null if the method fails + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetAvailableLanguagesN(void) const; + + + /** + * Gets a list of all the available time zone IDs. + * + * @since 2.0 + * + * @return A list of Tizen::Base::String instances, @n + * else @c null if the method fails + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetAvailableTimeZonesN(void) const; + + + /** + * Gets a list of all the available time zone IDs with the specified Greenwich Mean Time (GMT) offset for this time zone. + * + * @since 2.0 + * + * @return A list of Tizen::Base::String instances, @n + * else @c null if the method fails + * @param[in] rawOffset The specified GMT offset for this time zone (Daylight Saving Time (DST) is not considered) @n + * The value of @c rawOffset is in minutes. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * If there are no time zones for the specified GMT offset, an empty list is returned. + */ + Tizen::Base::Collection::IList* GetAvailableTimeZonesN(int rawOffset) const; + + + /** + * Gets the default system time zone. + * + * @since 2.0 + * + * @return The default system time zone, @n + * else the time zone name is an empty string and the offset is @c -1 if the method fails + * @exception E_SUCCESS The method is successful. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + TimeZone GetSystemTimeZone(void) const; + + + /** + * Checks whether the specified instance of Locale is supported. + * + * @since 2.0 + * + * @return An error code + * @param[in] locale An instance of Locale + * @param[out] isSupportedLocale The flag for checking the supported locale + * @exception E_SUCCESS The method is successful. + */ + result IsSupportedLocale(const Locale& locale, bool& isSupportedLocale); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + LocaleManager(const LocaleManager& localeManager); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + LocaleManager& operator =(const LocaleManager& localeManager); + + friend class _LocaleManagerImpl; + class _LocaleManagerImpl* __pLocaleManagerImpl; +}; // Locale + +}} // Tizen::Locales + +#endif //_FLCL_LOCALE_MANAGER_H_ diff --git a/inc/FLclNumberFormatter.h b/inc/FLclNumberFormatter.h new file mode 100644 index 0000000..8f2a19f --- /dev/null +++ b/inc/FLclNumberFormatter.h @@ -0,0 +1,683 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclNumberFormatter.h + * @brief This is the header file for the %NumberFormatter class. + * + * This header file contains the declarations of the %NumberFormatter class. + * + */ +#ifndef _FLCL_NUMBER_FORMATTER_H_ +#define _FLCL_NUMBER_FORMATTER_H_ + +#include +#include + +namespace Tizen { namespace Locales +{ + +/** + * @class NumberFormatter + * @brief This class provides methods for formatting numbers. + * + * @since 2.0 + * + * The %NumberFormatter class is used to format all number formats, including decimal and real numbers, currency, and percentage for any locale. It also provides methods to determine the locales that have number formats and their names. You can write codes completely independent of the locale conventions for decimal points, thousand separators as well as of the specific decimal digits used or whether the number format is a decimal. A normal decimal number can also be displayed as a currency or as a percentage. + * + * For more information on the class features, see Number Formatters. + * + * The following example demonstrates how to use the %NumberFormatter class. + * + * @code + +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Locales; + +void +LocaleApp::NumberFormatterExample(void) +{ + // Construct locale + Locale koreaLoc(LANGUAGE_KOR, COUNTRY_KR); + + // Get number formatter + NumberFormatter* pNumberFormatter = NumberFormatter::CreateNumberFormatterN(koreaLoc); + + String formattedString; + + // Format number with number formatter + double num = 345987.246; + pNumberFormatter->Format(num, formattedString); + + // Get currency formatter + NumberFormatter* pCurrencyFormatter = NumberFormatter::CreateCurrencyFormatterN(koreaLoc); + + // Format number with currency formatter + num = 100321; + pCurrencyFormatter->Format(num, formattedString); + + // Get percent formatter + NumberFormatter* pPercentFormatter = NumberFormatter::CreatePercentFormatterN(koreaLoc); + + // Format number with percent formatter + num = 0.5; + pPercentFormatter->Format(num, formattedString); + + delete pNumberFormatter; + delete pCurrencyFormatter; + delete pPercentFormatter; +} +@endcode + * + */ + +class _OSP_EXPORT_ NumberFormatter + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~NumberFormatter(void); + + + /** + * Creates a number formatter for the system locale. + * + * @since 2.0 + * + * @return A pointer to the general number formatter for the default locale, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_OPERATION The system locale is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static NumberFormatter* CreateNumberFormatterN(void); + + + /** + * Creates a number formatter for the specified locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompNumberFormatterCreateNumberFormatterNPage "here". + * @endif + * + * @return A pointer to a general number formatter for the specified @c locale, @n + * else @c null if an error occurs + * @param[in] locale An instance of Locale + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static NumberFormatter* CreateNumberFormatterN(const Locale& locale); + + /** + * @if OSPCOMPAT + * @page CompNumberFormatterCreateNumberFormatterNPage Compatibility for CreateNumberFormatterN() + * @section CompNumberFormatterCreateNumberFormatterNIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the @c locale is invalid. + * + * @section CompNumberFormatterCreateNumberFormatterNSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the @c locale is invalid. + * @endif + */ + + /** + * Creates a currency formatter for the default locale. + * + * @since 2.0 + * + * @return A pointer to a currency formatter for the default locale, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_OPERATION The system locale is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static NumberFormatter* CreateCurrencyFormatterN(void); + + + /** + * Creates a currency formatter for the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompNumberFormatterCreateCurrencyFormatterNPage "here". + * @endif + * + * @return A pointer to a currency formatter for the specified @c locale, @n + * else @c null if an error occurs + * @param[in] locale An instance of Locale + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static NumberFormatter* CreateCurrencyFormatterN(const Locale& locale); + + /** + * @if OSPCOMPAT + * @page CompNumberFormatterCreateCurrencyFormatterNPage Compatibility for CreateCurrencyFormatterN() + * @section CompNumberFormatterCreateCurrencyFormatterNIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the @c locale is invalid. + * + * @section CompNumberFormatterCreateCurrencyFormatterNSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the @c locale is invalid. + * @endif + */ + + /** + * Creates a percentage formatter for the system locale. + * + * @since 2.0 + * + * @return A pointer to a percentage formatter for the default locale, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_OPERATION The system locale is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static NumberFormatter* CreatePercentFormatterN(void); + + + /** + * Creates a percentage formatter for the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompNumberFormatterCreatePercentFormatterNPage "here". + * @endif + * + * @return A pointer to a percentage formatter for the specified @c locale, @n + * else @c null if an error occurs + * @param[in] locale An instance of Locale + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is invalid. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static NumberFormatter* CreatePercentFormatterN(const Locale& locale); + + /** + * @if OSPCOMPAT + * @page CompNumberFormatterCreatePercentFormatterNPage Compatibility for CreatePercentFormatterN() + * @section CompNumberFormatterCreatePercentFormatterNIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the @c locale is invalid. + * + * @section CompNumberFormatterCreatePercentFormatterNSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the @c locale is invalid. + * @endif + */ + + + + /** + * Formats a number of type Tizen::Base::Long to type Tizen::Base::String and appends the resulting string to a buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] number The number of type Tizen::Base::Long to format + * @param[out] str The string to append to the resultant string + * @exception E_SUCCESS The method is successful. + */ + virtual result Format(long number, Tizen::Base::String& str) const; + + + /** + * Formats a number of type Tizen::Base::Double to type Tizen::Base::String and appends the resulting string to a buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] number The number of type Tizen::Base::Double to format + * @param[out] str The string to append to the resultant string + * @exception E_SUCCESS The method is successful. + */ + virtual result Format(double number, Tizen::Base::String& str) const; + + + /** + * Gets the currency used by the current number format when formatting currency values. + * + * @since 2.0 + * + * @return A pointer to an instance of Currency + * @remarks The initial value is derived in a locale dependent way. @n + * The returned value may be @c null if no valid currency is determined + * or no currency has been set using the SetCurrency() method. + * @see SetCurrency() + */ + virtual const Currency* GetCurrency(void) const; + + + /** + * Sets the currency used by the current number format when formatting currency values. + * + * @since 2.0 + * + * @param[in] currency The new currency to use by the current number format + * @remarks This does not update the minimum or maximum number of fractional digits used by the number format. + * @see GetCurrency() + */ + virtual void SetCurrency(const Currency& currency); + + + /** + * Gets the maximum number of digits allowed in the integer portion of a number. + * + * @since 2.0 + * + * @return An integer value representing the maximum number of digits allowed in the integer portion of a number + * @see SetMaxIntegerDigits() + */ + virtual int GetMaxIntegerDigits(void) const; + + + /** + * Sets the maximum number of digits allowed in the integer portion of a number. + * + * @since 2.0 + * + * @param[in] newValue The maximum number of integer digits allowed in the integer portion of a number, @n + * If less than zero, @c 0 is used. + * @remarks The maximum integer digits must be greater than or equal to the minimum integer digits. + * If the new value for the maximum integer digits is less than the current value of the minimum integer digits, + * the minimum integer digits are also set to the new value. + * @see GetMaxIntegerDigits() + */ + virtual void SetMaxIntegerDigits(int newValue); + + + /** + * Gets the minimum number of digits allowed in the integer portion of a number. + * + * @since 2.0 + * + * @return An integer value representing the minimum number of digits allowed in the integer portion of a number + * @see SetMinIntegerDigits() + */ + virtual int GetMinIntegerDigits(void) const; + + + /** + * Sets the minimum number of digits allowed in the integer portion of a number. + * + * @since 2.0 + * + * @param[in] newValue The minimum number of integer digits allowed in the integer portion of a number @n + * If less than zero, @c 0 is used. + * @remarks The minimum integer digits must be less than or equal to the maximum integer digits. + * If the new value for the minimum integer digits exceeds the current value of the maximum integer digits, + * the maximum integer digits are also set to the new value. + * @see GetMinIntegerDigits() + */ + virtual void SetMinIntegerDigits(int newValue); + + + /** + * Gets the maximum number of digits allowed in the fractional portion of a number. + * + * @since 2.0 + * + * @return An integer value representing the maximum number of digits allowed in the fractional portion of a number + * @see SetMaxFractionDigits() + */ + virtual int GetMaxFractionDigits(void) const; + + + /** + * Sets the maximum number of digits allowed in the fractional portion of a number. + * + * @since 2.0 + * + * @param[in] newValue The maximum number of fractional digits allowed in the fractional portion of a number @n + * If less than zero, @c 0 is used. + * @remarks The maximum fractional digits must be greater than or equal to the minimum fractional digits. + * If the new value for the maximum fractional digits is less than the current value of the minimum fractional digits, + * the minimum fractional digits are also set to the new value. + * @see GetMaxFractionDigits() + */ + virtual void SetMaxFractionDigits(int newValue); + + + /** + * Gets the minimum number of digits allowed in the fractional portion of a number. + * + * @since 2.0 + * + * @return An integer value representing the minimum number of digits allowed in the fractional portion of a number + * @see SetMinFractionDigits() + */ + virtual int GetMinFractionDigits(void) const; + + + /** + * Sets the minimum number of digits allowed in the fractional portion of a number. + * + * @since 2.0 + * + * @param[in] newValue The minimum number of fractional digits allowed in the fractional portion of a number @n + * If less than zero, @c 0 is used. + * @remarks The minimum fractional digits must be less than or equal to the maximum fractional digits. + * If the new value for the minimum fractional digits exceeds the current value of the maximum fraction digits, + * the maximum fraction digits are also set to the new value. + * @see GetMinFractionDigits() + */ + virtual void SetMinFractionDigits(int newValue); + + + /** + * Checks whether the grouping is used in the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @return @c true if grouping is used in the current instance of %NumberFormatter, @n + * else @c false + * @remarks For example, in the English locale, with grouping on, the number 1234567 + * might be formatted as "1,234,567". + * The grouping separator as well as the size of each group is locale dependent + * and is determined by subclasses of %NumberFormatter. + * @see SetGroupingUsed() + */ + virtual bool IsGroupingUsed(void) const; + + + /** + * Sets the current instance of %NumberFormatter to use or not to use grouping. + * + * @since 2.0 + * + * @param[in] newValue Set to @c true if grouping is used in the current formatter, @n + * else @c false + * @see IsGroupingUsed() + */ + virtual void SetGroupingUsed(bool newValue); + + + /** + * Applies the specified pattern to the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @return An error code + * @param[in] pattern The new pattern + * @param[in] localized The localization On/Off flag @n + * Set to @c true if the pattern is applied with the localized symbols, @n + * else @c false. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c pattern is invalid or its length is @c 0. + */ + result ApplyPattern(const Tizen::Base::String& pattern, bool localized); + + + /** + * Gets the positive prefix of the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @return The positive prefix of the current %NumberFormatter instance + * @remarks For example: +123, $123, sFr123. + * @see SetPositivePrefix() + */ + Tizen::Base::String GetPositivePrefix(void) const; + + + /** + * Sets a new value for the positive prefix of the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @param[in] newValue The new positive prefix + * @see GetPositivePrefix() + */ + void SetPositivePrefix(const Tizen::Base::String& newValue); + + + /** + * Gets the negative prefix of the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @return The negative prefix of the current %NumberFormatter instance + * @remarks For example: -123, $123 (with negative prefix), sFr-123 + * @see SetNegativePrefix() + */ + Tizen::Base::String GetNegativePrefix(void) const; + + + /** + * Sets a new value for the negative prefix of the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @param[in] newValue The new negative prefix + * @see GetNegativePrefix() + */ + void SetNegativePrefix(const Tizen::Base::String& newValue); + + + /** + * Gets the positive suffix of the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @return The positive suffix of the current %NumberFormatter instance + * @remarks For example: 123% + * @see SetPositiveSuffix() + */ + Tizen::Base::String GetPositiveSuffix(void) const; + + + /** + * Sets a new value for the positive suffix of the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @param[in] newValue The new positive suffix + * @see GetPositiveSuffix() + */ + void SetPositiveSuffix(const Tizen::Base::String& newValue); + + + /** + * Gets the negative suffix of the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @return The negative suffix of the current %NumberFormatter instance + * @remarks For example: -123%, $123 (with negative suffix) + * @see SetNegativeSuffix() + */ + Tizen::Base::String GetNegativeSuffix(void) const; + + + /** + * Sets a new value for the negative suffix of the current instance of %NumberFormatter. + * + * @since 2.0 + * + * @param[in] newValue The new negative suffix + * @see GetNegativeSuffix() + */ + void SetNegativeSuffix(const Tizen::Base::String& newValue); + + + /** + * Gets the multiplier for use in percent, per mill, and so on. + * + * @since 2.0 + * + * @return An integer value representing the multiplier + * @remarks For example: with 100, 1.23 -> "123", and "123" -> 1.23 + * @see SetMultiplier() + */ + int GetMultiplier(void) const; + + + /** + * Sets a new value for the multiplier for use in percent, per mill, and so on. + * + * @since 2.0 + * + * @param[in] newValue The new value for the multiplier + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @remarks For example, in percentage, set the suffixes to have "%" and the multiplier to be 100. + * @see GetMultiplier() + */ + result SetMultiplier(int newValue); + + + /** + * Gets the grouping size. + * + * @since 2.0 + * + * @return An integer value representing the grouping size + * @remarks Grouping size is the number of digits between grouping separators in the integer portion of a number. @n + * For example, in the number "123,456.78", the grouping size is 3. + * @see SetGroupingSize() + * @see IsGroupingUsed() + */ + int GetGroupingSize(void) const; + + + /** + * Sets a new value for the grouping size. + * + * @since 2.0 + * + * @param[in] newValue The new value for the grouping size + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @see GetGroupingSize() + * @see SetGroupingUsed() + */ + result SetGroupingSize(int newValue); + + + /** + * Checks whether the decimal separator is always shown. + * + * @since 2.0 + * + * @return @c true if the decimal separator is always shown, @n + * else @c false + * @remarks For example: ON: 12345 -> 12345.; OFF: 12345 -> 12345 + * @see SetDecimalSeparatorAlwaysShown() + */ + bool IsDecimalSeparatorAlwaysShown(void) const; + + + /** + * Sets the behavior of the decimal separator. @n + * The decimal separator can be set to always appear using this method. + * + * @since 2.0 + * + * @param[in] newValue Set to @c true if the decimal separator is always shown, @n + * else @c false + * @see IsDecimalSeparatorAlwaysShown() + */ + void SetDecimalSeparatorAlwaysShown(bool newValue); + + + /** + * Checks whether the positive sign is always shown. + * + * @since 2.0 + * + * @return @c true if the positive sign is always shown, @n + * else @c false + * @remarks For example: ON: 12345 -> +12345.; OFF: 12345 -> 12345. + * @see SetPositiveSignAlwaysShown() + */ + bool IsPositiveSignAlwaysShown(void) const; + + + /** + * Sets the behavior of the plus sign. @n + * The plus sign can be set to always appear using this method. + * + * @since 2.0 + * + * @param[in] newValue Set to @c true if the plus sign is always shown, @n + * else @c false + * @see IsPositiveSignAlwaysShown() + */ + void SetPositiveSignAlwaysShown(bool newValue); + + +private: + /** + * This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + NumberFormatter(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + NumberFormatter(const NumberFormatter& numberFormatter); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + NumberFormatter& operator =(const NumberFormatter& numberFormatter); + + friend class _NumberFormatterImpl; + class _NumberFormatterImpl* __pNumberFormatterImpl; + +}; // NumberFormatter + +}} // Tizen::Locales + +#endif //_FLCL_NUMBER_FORMATTER_H_ + diff --git a/inc/FLclNumberSymbols.h b/inc/FLclNumberSymbols.h new file mode 100644 index 0000000..c18f8cc --- /dev/null +++ b/inc/FLclNumberSymbols.h @@ -0,0 +1,192 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclNumberSymbols.h + * @brief This is the header file for the %NumberSymbols class. + * + * This header file contains the declarations of the %NumberSymbols class. + * + */ +#ifndef _FLCL_NUMBER_SYMBOLS_H_ +#define _FLCL_NUMBER_SYMBOLS_H_ + +#include + + +namespace Tizen { namespace Locales +{ + +// Enums and Constants +/** + * @enum NumberSymbol + * + * Defines the possible formats for number symbols. @n + * + * This enum represents the possible symbols for NumberFormatter. + * + * @since 2.0 + */ +enum NumberSymbol +{ + NUMBER_SYMBOL_DECIMAL_SEPARATOR, /**< The decimal separator */ + NUMBER_SYMBOL_GROUPING_SEPARATOR, /**< The grouping separator */ + NUMBER_SYMBOL_PATTERN_SEPARATOR, /**< The pattern separator */ + NUMBER_SYMBOL_PERCENT, /**< The percent symbol */ + NUMBER_SYMBOL_ZERO_DIGIT, /**< The zero symbol*/ + NUMBER_SYMBOL_DIGIT, /**< The character representing a digit in the pattern */ + NUMBER_SYMBOL_CURRENCY, /**< The currency symbol */ + NUMBER_SYMBOL_INTL_CURRENCY, /**< The international currency symbol */ + NUMBER_SYMBOL_MONETARY_SEPARATOR, /**< The monetary separator */ + NUMBER_SYMBOL_PER_MILL, /**< The per mil symbol */ + NUMBER_SYMBOL_EXPONENTIAL, /**< The exponential symbol */ + NUMBER_SYMBOL_PLUS_SIGN, /**< The plus sign */ + NUMBER_SYMBOL_MINUS_SIGN, /**< The minus sign */ + NUMBER_SYMBOL_COUNT /**< The number of symbol */ +}; + + +/** + * @class NumberSymbols + * @brief This class provides methods that help in providing number symbols. + * + * @since 2.0 + * + * The %NumberSymbols class represents the set of symbols (such as the decimal separator and the grouping separator) needed by NumberFormatter to format numbers. + * %NumberFormatter creates its own instance of %NumberSymbols from its locale data. %NumberSymbols can be adopted by a %NumberFormatter instance, or it can be specified when a %NumberFormatter is created. If you need to change any of these symbols, you can get the %NumberSymbols instance from your %NumberFormatter and then modify it. + * + * For more information on the class features, see Number Symbols and Currencies. + */ +class _OSP_EXPORT_ NumberSymbols + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. @n + * The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + * + * @see Construct() + */ + NumberSymbols(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~NumberSymbols(void); + + + /** + * Initializes this instance of %NumberSymbols with the specified @c locale. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompNumberSymbolsConstructPage "here". + * @endif + * + * @return An error code + * @param[in] locale An instance of Locale + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c locale is invalid. + */ + result Construct(const Locale& locale); + + /** + * @if OSPCOMPAT + * @page CompNumberSymbolsConstructPage Compatibility for Construct() + * @section CompNumberSymbolsConstructIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the @c locale is invalid. + * + * @section CompNumberSymbolsConstructSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the @c locale is invalid. + * @endif + */ + + /** + * Gets the character used for number format. + * + * @since 2.0 + * + * @return The character used for number format, @n + * else an empty string if the @c symbol is invalid + * @param[in] symbol The number format symbol instance + * @see SetNumberSymbol() + */ + Tizen::Base::String GetNumberSymbol(NumberSymbol symbol) const; + + + /** + * Sets the character used for number format. + * + * @since 2.0 + * + * @return An error code + * @param[in] symbol A symbol to set + * @param[in] str The new string for symbol + * @exception E_SUCCESS The method is successful. + * @see GetNumberSymbol() + */ + result SetNumberSymbol(NumberSymbol symbol, const Tizen::Base::String& str); + + + /** + * Gets the current locale. + * + * @since 2.0 + * + * @return A pointer to the current instance of Locale, @n + * else @c null if this method fails + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + const Locale* GetLocale(void) const; + + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + NumberSymbols(const NumberSymbols& numberSymbols); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + NumberSymbols& operator =(const NumberSymbols& numberSymbols); + + + friend class _NumberSymbolsImpl; + class _NumberSymbolsImpl* __pNumberSymbolsImpl; + +}; // NumberSymbols + +}} // Tizen::Locales + +#endif //_FLCL_NUMBER_SYMBOLS_H_ + diff --git a/inc/FLclTimeRule.h b/inc/FLclTimeRule.h new file mode 100644 index 0000000..f51c020 --- /dev/null +++ b/inc/FLclTimeRule.h @@ -0,0 +1,335 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclTimeRule.h + * @brief This is the header file for the %TimeRule class. + * + * This header file contains declarations of the %TimeRule class. + */ +#ifndef _FLCL_TIME_RULE_H_ +#define _FLCL_TIME_RULE_H_ + +#include +#include + +namespace Tizen { namespace Locales +{ + +/** + * @class TimeRule + * @brief This class is for setting and getting the time rule. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %TimeRule class defines the time rule and provides methods for setting and getting it. + * This class does not execute any operation with its value and is mainly used when periodically repeated time rules are defined. + * For example, the daylight saving time rule. + * + * For more information on the class features, see Time Rules. + * + * @see Tizen::Locales::TimeZone + */ + +/** +* @enum Month +* +* Defines the months. @n +* The indexing is 1-based. +* +* @since 2.0 +*/ +enum Month +{ + JANUARY = 1, /**< January */ + FEBRUARY, /**< February */ + MARCH, /**< March */ + APRIL, /**< April */ + MAY, /**< May */ + JUNE, /**< June */ + JULY, /**< July */ + AUGUST, /**< August */ + SEPTEMBER, /**< September */ + OCTOBER, /**< October */ + NOVEMBER, /**< November */ + DECEMBER, /**< December */ + MONTH_UNDEFINED = -1 // Undefined +}; + + +/** +* @enum DayOfWeek +* +* Defines the days of the week. @n +* The indexing is 1-based. +* +* @since 2.0 +*/ +enum DayOfWeek +{ + SUNDAY = 1, /**< Sunday */ + MONDAY, /**< Monday */ + TUESDAY, /**< Tuesday */ + WEDNESDAY, /**< Wednesday */ + THURSDAY, /**< Thursday */ + FRIDAY, /**< Friday */ + SATURDAY, /**< Saturday */ + DAY_OF_WEEK_UNDEFINED = -1 //*< Undefined */ +}; + +/** + * @enum Week + * + * Defines the week. + * + * @since 2.0 + */ +enum Week +{ + FIRST_WEEK = 1, /**< The first week */ + SECOND_WEEK = 2, /**< The second week */ + THIRD_WEEK = 3, /**< The third week */ + FOURTH_WEEK = 4, /**< The fourth week */ + FIFTH_WEEK = 5, /**< The fifth week */ + SIXTH_WEEK = 6, /**< The sixth week */ + LAST_WEEK = -2, /**< The last week */ + WEEK_UNDEFINED = -1 //*< Undefined */ +}; + +class _OSP_EXPORT_ TimeRule + : public Tizen::Base::Object +{ +public: + /** + * Initializes the current instance of %TimeRule with the values of the specified %TimeRule instance. @n + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] timeRule An instance of %TimeRule + */ + TimeRule(const TimeRule& timeRule); + + /** + * Assigns the value of the specified instance to the current instance of %TimeRule. @n + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @param[in] timeRule An instance of %TimeRule + */ + TimeRule& operator =(const TimeRule& timeRule); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~TimeRule(void); + + /** + * Initializes the current instance of %TimeRule with the specified @c month, @c day, @c hour, + * @c minute, and @c timeMode. + * + * @since 2.0 + * + * @param[in] month The month + * @param[in] day The day + * @param[in] hour The hour + * @param[in] minute The minute + * @param[in] timeMode The time mode - TIME_MODE_UTC, TIME_MODE_STANDARD, or TIME_MODE_WALL + */ + TimeRule(Month month, int day, int hour = 0, int minute = 0, Tizen::System::TimeMode timeMode = Tizen::System::TIME_MODE_WALL); + + /** + * Initializes the current instance of %TimeRule with the specified @c month, @c week, + * @c dayOfWeek, @c hour, @c minute, and @c timeMode. + * + * @since 2.0 + * + * @param[in] month The month + * @param[in] week The week + * @param[in] dayOfWeek The day of the week + * @param[in] hour The hour + * @param[in] minute The minute + * @param[in] timeMode The time mode - TIME_MODE_UTC, TIME_MODE_STANDARD, or TIME_MODE_WALL + */ + TimeRule(Month month, Week week, DayOfWeek dayOfWeek, + int hour = 0, int minute = 0, Tizen::System::TimeMode timeMode = Tizen::System::TIME_MODE_WALL); + + /** + * Initializes the current instance of %TimeRule with the specified @c month, @c day, + * @c dayOfWeek, @c onOrAfterDay setting, @c hour, @c minute, and @c timeMode. + * + * @since 2.0 + * + * @param[in] month The month + * @param[in] day The day + * @param[in] dayOfWeek The day of the week + * @param[in] onOrAfterDay Set to @c true to select the first @c dayOfWeek + * @b on @b or @b after @c day, @n + * else @c false to select the last @c dayOfWeek + * @b on @b or @b before @c day + * @param[in] hour The hour + * @param[in] minute The minute + * @param[in] timeMode The time mode - TIME_MODE_UTC, TIME_MODE_STANDARD, or TIME_MODE_WALL + */ + TimeRule(Month month, int day, DayOfWeek dayOfWeek, + bool onOrAfterDay, int hour = 0, int minute = 0, Tizen::System::TimeMode timeMode = Tizen::System::TIME_MODE_WALL); + + /** + * Gets the month. + * + * @since 2.0 + * + * @return The month + */ + Month GetMonth(void) const; + + /** + * Gets the day. + * + * @since 2.0 + * + * @return An integer value indicating the day, @n + * else @c -1 if the value of day is undefined + */ + int GetDay(void) const; + + /** + * Gets the week. + * + * @since 2.0 + * + * @return The week, @n + * else @c -1 if the value of week is undefined + */ + Week GetWeek(void) const; + + /** + * Gets the day of the week. + * + * @since 2.0 + * + * @return The day of the week, @n + * else @c -1 if the value of day of the week is undefined + */ + DayOfWeek GetDayOfWeek(void) const; + + /** + * Gets the hour. + * + * @since 2.0 + * + * @return An integer value indicating the hour + */ + int GetHour(void) const; + + /** + * Gets the minute. + * + * @since 2.0 + * + * @return An integer value indicating the minute + */ + int GetMinute(void) const; + + /** + * Gets the time mode. + * + * @since 2.0 + * + * @return An instance of Tizen::System::TimeMode + */ + Tizen::System::TimeMode GetTimeMode(void) const; + + /** + * Gets the value of the @c onOrAfterDay field. + * + * @since 2.0 + * + * @return A @c boolean value of the @c onOrAfterDay field + */ + bool IsOnOrAfterDay(void) const; + + /** + * Checks whether the value of the specified instance is equal to that of the current instance. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance is equal to that of the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + +private: + /** + * Initializes a %TimeRule instance with given values. + * + * @return An error code + * @param[in] month The month + * @param[in] day The day + * @param[in] week The week + * @param[in] dayOfWeek The day of week + * @param[in] beforeAfter If @c after is ON_OR_AFTER_DAY, this rule selects the first @c dayOfWeek + * @b on @b or @b after @c day. + * If @c after is ON_OR_BEFORE_DAY, this rule selects the last @c dayOfWeek + * @b on @b or @b before @c day. + * @param[in] hour The hour + * @param[in] minute The minute + * @param[in] timeMode The time mode - TIME_MODE_UTC, TIME_MODE_STANDARD, TIME_MODE_WALL + */ + void SetValue(Month month, int day, Week week, + DayOfWeek dayOfWeek, bool onOrAfterDay, int hour, + int minute, Tizen::System::TimeMode timeMode); + + int GetRuleMode(void) const; + + static const int DAY_UNDEFINED = -1; + + Month __month; + int __day; + Week __week; + DayOfWeek __dayOfWeek; + int __hour; + int __minute; + Tizen::System::TimeMode __timeMode; + bool __onOrAfterDay; + + + friend class _TimeRuleImpl; + class _TimeRuleImpl* __pTimeRuleImpl; + + friend class _TimeZoneImpl; + friend class _LocaleData; +}; // TimeRule + +}} // Tizen::Locales +#endif // _FLCL_TIME_RULE_H_ diff --git a/inc/FLclTimeZone.h b/inc/FLclTimeZone.h new file mode 100644 index 0000000..be6043e --- /dev/null +++ b/inc/FLclTimeZone.h @@ -0,0 +1,567 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclTimeZone.h + * @brief This is the header file for the %TimeZone class. + * @see Tizen::Locales::Locale + * + * This header file contains the declarations of the %TimeZone class. + */ + +#ifndef _FLCL_TIME_ZONE_H_ +#define _FLCL_TIME_ZONE_H_ + +#include +#include +#include + +namespace Tizen { namespace Locales +{ + +/** + * @class TimeZone + * @brief This class represents the time zones. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %TimeZone class represents a time zone offset and figures out Daylight Saving Time (DST). + * + * The form of time zone ID is "Area/Location". However, the specialized time zone IDs have the different form.@n + * + * The IDs are defined in Time Zone Database. @n + * + * The supported time zone list depends on the device. Therefore, it must be checked by using LocaleManager::GetAvailableTimeZonesN(). + * + * For more information on the class features, see Time Zones. + * + * The following example demonstrates how to use the %TimeZone class. + * +@code + +#include + +using namespace Tizen::Locales; + +void +MyClass::MyTimeZone(void) +{ + // Gets the system time zone. + LocaleManager localeManager; + localeManager.Construct(); + + TimeZone timeZone = localeManager.GetSystemTimeZone(); + + String timeZoneId = timeZone.GetId(); + int rawOffset = timeZone.GetRawOffset(); + int dstSavings = timeZone.GetDstSavings(); + + // Gets the special time zone. + TimeZone timeZone2; + Tizen::Locales::TimeZone::GetTimeZone(L"Europe/Zurich", timeZone2); +} +@endcode + * + */ + +class _OSP_EXPORT_ TimeZone + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + TimeZone(void); + + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~TimeZone(void); + + + /** + * This is the copy constructor for the %TimeZone class. @n + * It initializes an instance of %TimeZone with the values of the specified instance of %TimeZone. + * Copying of objects using this copy constructor is allowed. + * + * @since 2.0 + * + * @param[in] otherTimeZone An instance of %TimeZone + */ + TimeZone(const TimeZone& otherTimeZone); + + /** + * Assigns the value of the specified instance to the current instance of %TimeZone. @n + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.0 + * + * @return A reference value of the current instance + * @param[in] otherTimeZone An instance of %TimeZone + * + */ + TimeZone& operator =(const TimeZone& otherTimeZone); + + /** + * Initializes this instance of %TimeZone with the specified raw GMT offset and the ID of the time zone without including DST. + * + * @since 2.0 + * + * @param[in] rawOffset The base time zone offset to GMT in minutes + * @param[in] id The time zone ID + * @remarks The form of time zone @c id is "Area/Location". @n For more information on IDs, refer here. @n + * However, the supported time zone list depends on the device. Therefore, it must be checked before using this method. + * @see LocaleManager::GetAvailableTimeZonesN() + */ + TimeZone(int rawOffset, const Tizen::Base::String& id); + + /** + * Initializes this instance of %TimeZone with the specified raw GMT offset, + * the ID of the time zone, the rules for starting/ending DST, and the DST offset. + * + * @since 2.0 + * + * @param[in] rawOffset The base time zone offset to GMT in minutes + * @param[in] id The time zone ID + * @param[in] startRule The DST starting rule + * @param[in] endRule The DST end rule + * @param[in] dstOffset The amount of time in minutes saved during DST + * @remarks The form of time zone @c id is "Area/Location". @n For more information on IDs, refer here. @n + * However, the supported time zone list depends on the device. Therefore, it must be checked before using this method. + * @see LocaleManager::GetAvailableTimeZonesN() + */ + TimeZone(int rawOffset, const Tizen::Base::String& id, + const TimeRule& startRule, const TimeRule& endRule, int dstOffset); + + /** + * Checks whether the specified instance of %TimeZone equals the value of the current instance. + * + * @since 2.0 + * + * @return @c true if the two instances are equal, @n + * else @c false + * @param[in] otherTimeZone An instance of %TimeZone + */ + bool operator ==(const TimeZone& otherTimeZone) const; + + /** + * Checks whether the %TimeZone instance is equal to the current instance. + * + * @since 2.0 + * + * @return @c true if the two instances are not equal, @n + * else @c false + * @param[in] otherTimeZone An instance of %TimeZone + */ + bool operator !=(const TimeZone& otherTimeZone) const; + + /** + * Compares the value of the specified instance to that of the current instance. + * + * @since 2.0 + * + * @return @c true if the value of the specified instance is equal to that of the current instance, @n + * else @c false + * @param[in] obj The object to compare with the current instance + */ + virtual bool Equals(const Tizen::Base::Object& obj) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.0 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Sets the DST time. + * + * @since 2.0 + * + * @param[in] dstSavings The amount of time in minutes @n + * The time is advanced with respect to the standard time when the DST rules are in effect. + */ + void SetDstSavings(int dstSavings); + + /** + * Sets the DST starting and end rule. + * + * @since 2.0 + * + * @return An error code + * @param[in] startRule The DST starting rule + * @param[in] endRule The DST end rule + * @param[in] dstSavings The DST offset in minutes + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_RANGE The specified @c dstSavings is less than 24 hours. + */ + result SetDstRules(const TimeRule& startRule, const TimeRule& endRule, int dstSavings = 60); + + /** + * Sets the DST end rule. + * + * @since 2.0 + * + * @param[in] endRule The DST end rule + */ + void SetDstEndingRule(const TimeRule& endRule); + + /** + * Sets the DST starting rule. + * + * @since 2.0 + * + * @param[in] startRule The DST starting rule + */ + void SetDstStartingRule(const TimeRule& startRule); + + /** + * Sets the difference in minutes between the local standard time and GMT, + * without including DST (that is, raw offset). + * + * @since 2.0 + * + * @param[in] rawOffset The difference in minutes between the local standard time and GMT, without including DST + */ + void SetRawOffset(int rawOffset); + + /** + * Sets the DST starting year. + * + * @since 2.0 + * + * @param[in] year The DST starting year + */ + void SetDstStartingYear(int year); + + /** + * Sets the ID of the time zone. + * + * @since 2.0 + * + * @param[in] id The ID of the time zone + */ + void SetId(const Tizen::Base::String& id); + + /** + * Converts the Coordinated Universal Time (UTC) time to the standard time. + * + * @since 2.0 + * + * @return The standard time + * @param[in] utcTime The UTC time + */ + Tizen::Base::DateTime UtcTimeToStandardTime(const Tizen::Base::DateTime& utcTime); + + /** + * Converts the UTC time to the wall time. + * + * @since 2.0 + * + * @return The wall time + * @param[in] utcTime The UTC time + */ + Tizen::Base::DateTime UtcTimeToWallTime(const Tizen::Base::DateTime& utcTime); + + /** + * Converts the standard time to the UTC time. + * + * @since 2.0 + * + * @return The UTC time + * @param[in] standardTime The standard time + */ + Tizen::Base::DateTime StandardTimeToUtcTime(const Tizen::Base::DateTime& standardTime); + + /** + * Converts the wall time to the UTC time. + * + * @since 2.0 + * + * @return The UTC time + * @param[in] wallTime The wall time + */ + Tizen::Base::DateTime WallTimeToUtcTime(const Tizen::Base::DateTime& wallTime); + + /** + * Gets the amount of time in minutes to be added to the local standard time to get the local wall time. + * + * @since 2.0 + * + * @return The amount of time in minutes + * + */ + int GetDstSavings(void) const; + + /** + * Gets the starting year of the DST. + * + * @since 2.0 + * + * @return The starting year of the DST set by the SetDstStartingYear() method, @n + * else @c 0 if the starting year of the DST is undefined + * @see SetDstStartingYear() + */ + int GetDstStartingYear(void) const; + + /** + * Gets the raw and GMT offset for the specified instance of Tizen::Base::DateTime in the current time zone. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompTimeZoneGetOffsetPage "here". + * @endif + * + * @return An error code + * @param[in] date An instance of Tizen::Base::DateTime + * @param[in] local Set to @c true if the date is in local wall time @n + * else @c false if it is in GMT time + * @param[out] rawOffset The time zone's raw offset in minutes + * @param[out] dstOffset The offset to add to @c rawOffset to obtain the total offset between the local and GMT time @n + * If DST is not in effect, it is zero. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c date is invalid. + * @remarks Local millisecond = GMT milliseconds + rawOffset(in milliseconds) + dstOffset(in milliseconds). + * All computations are performed in Gregorian calendar. + */ + result GetOffset(const Tizen::Base::DateTime& date, bool local, int& rawOffset, int& dstOffset) const; + + /** + * Gets the difference in minutes between the local standard time and GMT, taking into consideration both the raw offset and the effect of DST. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompTimeZoneGetOffsetPage "here". + * @endif + * + * @return An error code + * @param[in] ticks The time ticks value @n + * The value can be either GMT time or local wall time. + * @param[out] offset The offset between the local standard time and GMT, taking into consideration DST + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c ticks is invalid. + */ + result GetOffset(long long ticks, int& offset) const; + + /** + * @if OSPCOMPAT + * @page CompTimeZoneGetOffsetPage Compatibility for GetOffset() + * @section CompTimeZoneGetOffsetIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_OUT_OF_RANGE if an argument is invalid. + * + * @section CompTimeZoneGetOffsetSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if an argument is invalid. + * @endif + */ + + /** + * Gets the difference in minutes between the local standard time and GMT, without including DST (that is, raw offset). + * + * @since 2.0 + * + * @return The raw offset + * + */ + int GetRawOffset(void) const; + + /** + * Gets the ID of the time zone. + * + * @since 2.0 + * + * @return The ID of the time zone + */ + Tizen::Base::String GetId(void) const; + + /** + * Gets the DST starting rule. + * + * @since 2.0 + * + * @return A pointer to the DST start rule, @n + * else a @c null pointer if the DST start rule is undefined + */ + const TimeRule* GetDstStartingRule(void) const; + + /** + * Gets the DST end rule. + * + * @since 2.0 + * + * @return A pointer to the DST end rule, @n + * else a @c null pointer if the DST end rule is undefined + */ + const TimeRule* GetDstEndingRule(void) const; + + /** + * Checks whether the current instance of %TimeZone uses DST. + * + * @since 2.0 + * + * @return @c true if the current instance uses DST, @n + * else @c false + */ + bool IsDstUsed(void) const; + + /** + * Gets the GMT time zone. @n + * The GMT time zone has a raw offset of @c 0 and does not use DST. + * + * @since 2.0 + * + * @return The GMT time zone + */ + static TimeZone GetGmtTimeZone(void); + + /** + * Gets the time zone instance from the given ID. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompTimeZoneGetTimeZonePage "here". + * @endif + * + * @return An error code + * @param[in] id The time zone ID + * @param[out] timeZone The time zone for the given ID + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c id is invalid. + * @remarks The %TimeZone instance for the specified @c id does not contain the DST information. + * The supported time zone list depends on the device. Therefore, it should be checked before using this method. + * @see LocaleManager::GetAvailableTimeZonesN() + */ + static result GetTimeZone(const Tizen::Base::String& id, Tizen::Locales::TimeZone& timeZone); + + /** + * Gets the %TimeZone instance from the specified ID and UTC time. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with OSP compatibile applications. @n + * For more information, see @ref CompTimeZoneGetTimeZonePage "here". + * @endif + * + * @return An error code + * @param[in] id The time zone ID + * @param[in] utcTime The UTC time + * @param[out] timeZone The time zone for the specified ID and UTC time + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c id is invalid. + * @remarks The %TimeZone instance for the specified ID and UTC time contains the DST information. + * The supported time zone list depends on the device. Therefore, it should be checked before using this method. + * @see LocaleManager::GetAvailableTimeZonesN() + */ + static result GetTimeZone(const Tizen::Base::String& id, const Tizen::Base::DateTime& utcTime, Tizen::Locales::TimeZone& timeZone); + + /** + * @if OSPCOMPAT + * @page CompTimeZoneGetTimeZonePage Compatibility for GetTimeZone() + * @section CompTimeZoneGetTimeZoneIssueSection Issues + * Implementation of this method in OSP compatible applications has the following issue: @n + * -# The method returns E_UNSUPPORTED_OPERATION if the time zone ID is invalid. + * + * @section CompTimeZoneGetTimeZoneSolutionSection Resolutions + * This issue has been resolved in Tizen. + * @par When working in Tizen: + * -# The method returns E_INVALID_ARG if the time zone ID is invalid. + * @endif + */ + + /** + * Converts the UTC time to the standard time. + * + * @since 2.0 + * + * @return The standard time + * @param[in] utcTime The UTC time + * @param[in] rawOffset The time zone's raw offset in minutes + */ + static Tizen::Base::DateTime UtcTimeToStandardTime(const Tizen::Base::DateTime& utcTime, int rawOffset); + + /** + * Converts the standard time to the UTC time. + * + * @since 2.0 + * + * @return The UTC time + * @param[in] standardTime The standard time + * @param[in] rawOffset The time zone's raw offset in minutes + */ + static Tizen::Base::DateTime StandardTimeToUtcTime(const Tizen::Base::DateTime& standardTime, int rawOffset); + + /** + * Converts the UTC time to the wall time. + * + * @since 2.0 + * + * @return The wall time + * @param[in] utcTime The UTC time + * @param[in] rawOffset The time zone's raw offset in minutes + * @param[in] dstOffset The amount of time in minutes saved during DST + */ + static Tizen::Base::DateTime UtcTimeToWallTime(const Tizen::Base::DateTime& utcTime, int rawOffset, int dstOffset); + + /** + * Converts the wall time to the UTC time. + * + * @since 2.0 + * + * @return The UTC time + * @param[in] wallTime The wall time + * @param[in] rawOffset The time zone's raw offset in minutes + * @param[in] dstOffset The amount of time in minutes saved during DST + */ + static Tizen::Base::DateTime WallTimeToUtcTime(const Tizen::Base::DateTime& wallTime, int rawOffset, int dstOffset); + +private: + + friend class _TimeZoneImpl; + class _TimeZoneImpl* __pTimeZoneImpl; + + friend class _LocaleData; +}; // TimeZone + +}} // Tizen::Locales +#endif // _FLCL_TIME_ZONE_H_ diff --git a/inc/FLocales.h b/inc/FLocales.h new file mode 100644 index 0000000..a9d627d --- /dev/null +++ b/inc/FLocales.h @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLocales.h + * @brief This is the header file for the %Locales namespace. + * + * This header file contains the declarations of the %Locales namespace. + */ + +#ifndef _FLOCALES_H_ +#define _FLOCALES_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/** + * @namespace Tizen::Locales + * @brief This namespace contains classes that define culture-related information. + * + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library: @b osp-appfw + * + * + * The %Locales namespace contains classes representing a specific cultural region (locale) and the classes for manipulating and formatting locale-sensitive information, such as dates, times, numbers, and time zones. + * + * For more information on the %Locales namespace features, see Locales Guide. + * + * The following diagram illustrates the relationships between the classes belonging to the %Locales namespace. + * + * @image html locales_using_the_apis_classdiagram.png + */ + +namespace Tizen { namespace Locales +{ + +}} // Tizen::Locales + +#endif //_FLOCALES_H_ diff --git a/inc/FOspCompat.h b/inc/FOspCompat.h new file mode 100644 index 0000000..6b6d3a2 --- /dev/null +++ b/inc/FOspCompat.h @@ -0,0 +1,259 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + + + +#ifndef _FOSP_COMPAT_H_ +#define _FOSP_COMPAT_H_ + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef int (*funread)(void* _cookie, char* _buf, int _n); +typedef int (*funwrite)(void* _cookie, const char* _buf, int _n); +#ifdef __LARGE64_FILES +typedef _fpos64_t (*funseek)(void* _cookie, _fpos64_t _off, int _whence); +#else +typedef fpos_t (*funseek)(void* _cookie, fpos_t _off, int _whence); +#endif +typedef int (*funclose)(void* _cookie); + +// String functions NewlibCompatString.cpp +_OSP_EXPORT_ char* strlwr(char* pcStr); +_OSP_EXPORT_ char* strupr(char* pcStr); +_OSP_EXPORT_ size_t wcslcat(wchar_t * wcDst, const wchar_t * wcSrc, size_t siz); +_OSP_EXPORT_ size_t wcslcpy( wchar_t* wcDst, const wchar_t* wcSrc, size_t siz); + +// String functions NewlibCompatStdlib.cpp +_OSP_EXPORT_ float atoff(const char* pstr); +_OSP_EXPORT_ char* ecvtf(float fval, int ndigit, int* decpt, int* sign); +_OSP_EXPORT_ char* ecvtbuf(double invalue, int ndigit, int* decpt, int* sign, char* ecvt_buf); +_OSP_EXPORT_ char* fcvtf( float fval, int ndigit, int* decpt, int* sign); +_OSP_EXPORT_ char* fcvtbuf(double invalue, int ndigit, int* decpt, int* sign, char* fcvt_buf); +_OSP_EXPORT_ char* gcvtf( float fval, int ndigit, char* buf); +_OSP_EXPORT_ void* reallocf (void* pstr, unsigned int size); + +// String functions NewlibCompatStdio.cpp +_OSP_EXPORT_ char* asnprintf(char* buf, size_t* lenp, const char* format, ...); +_OSP_EXPORT_ char* vasnprintf(char *buf, size_t *lenp, const char *format, va_list ap); +_OSP_EXPORT_ int asiprintf(char **strp,const char *fmt0, ...); +_OSP_EXPORT_ char * asniprintf(char *buf, size_t *lenp, const char *fmt0, ... ); +_OSP_EXPORT_ int iprintf(const char *fmt0, ...); +_OSP_EXPORT_ int fiprintf(FILE * fp, const char *fmt0, ...); +_OSP_EXPORT_ int siprintf(char *str, const char *fmt0, ...); +_OSP_EXPORT_ int sniprintf(char *str, size_t size, const char *fmt0, ...); +_OSP_EXPORT_ int vasiprintf(char **strp, const char *fmt0, va_list ap); +_OSP_EXPORT_ char* vasniprintf(char *buf, size_t *lenp, const char *fmt0, va_list ap); +_OSP_EXPORT_ int vfiprintf(FILE * fp, const char *fmt0, va_list ap); +_OSP_EXPORT_ int viprintf(const char *fmt0, va_list ap); +_OSP_EXPORT_ int vsiprintf(char *str, const char *fmt0, va_list ap); +_OSP_EXPORT_ int vsniprintf(char *str, size_t size, const char *fmt0, va_list ap); +_OSP_EXPORT_ int diprintf(int fd, const char *fmt0, ...); +_OSP_EXPORT_ int siscanf( const char* str, const char* fmt0, ...); +_OSP_EXPORT_ int vdiprintf(int fd, const char *fmt0, va_list ap); +_OSP_EXPORT_ int vfiscanf(FILE *fp, const char *fmt0, va_list ap); +_OSP_EXPORT_ int vsiscanf(const char *str, const char *fmt0, va_list ap); +_OSP_EXPORT_ int fiscanf(FILE *fp, const char *fmt0, ...); +_OSP_EXPORT_ FILE* funopen(const void* cookie, funread readfn, funwrite writefn, funseek seekfn, funclose closefn); +_OSP_EXPORT_ FILE* fropen(const void* cookie , funread readfn); +_OSP_EXPORT_ FILE* fwopen(const void* cookie,funwrite writefn); + +// Miscellaneous functions NewlibCompatMisc.cpp +#define unctrllen(ch) __unctrllen[(ch) & 0xff] +_OSP_EXPORT_ extern const char __unctrllen[256]; + +#ifdef __cplusplus +}; //extern "C" +#endif + +typedef wchar_t mchar; + +namespace Tizen { +// Add constant which has compatible issue on Tizen + +namespace Ads { +// Add constant which has compatible issue on Tizen::Ads + +}; // Tizen::Ads + +namespace App +{ +// Add constant which has compatible issue on Tizen::App + +}; // Tizen::App + +namespace Base +{ +// Add constant which has compatible issue on Tizen::Base + +template class Buffer; + +typedef Buffer McharBuffer; + +}; // Tizen::Base + +namespace Commerce +{ +// Add constant which has compatible issue on Tizen::Commerce + +}; // Tizen::Commerce + +namespace Content +{ +// Add constant which has compatible issue on Tizen::Content + +}; // Tizen::Content + +namespace Graphics +{ +// Add constant which has compatible issue on Tizen::Graphics + +}; // Tizen::Graphics + +namespace Io +{ +// Add constant which has compatible issue on Tizen::Io + +}; // Tizen::Io + +namespace Locales +{ +// Add constant which has compatible issue on Tizen::Locales + +}; // Tizen::Locales + +namespace Locations +{ +// Add constant which has compatible issue on Tizen::Locations + +}; // Tizen::Locations + +namespace Media +{ +// Add constant which has compatible issue on Tizen::Media + +}; // Tizen::Media + +namespace Messaging +{ +// Add constant which has compatible issue on Tizen::Messaging + +}; // Tizen::Messaging + +namespace Net +{ +// Add constant which has compatible issue on Tizen::Net + +namespace Sockets +{ + +static const int NET_SOCKET_INADDR_ANY = 0; + +}; // Tizen::Net::Sockets + +namespace Wifi +{ + +static const int WIFI_DIRECT_MAX_CONNECTED_CLIENTS = 8; +static const int WIFI_DIRECT_MAX_GROUP_OWNER_INTENT = 15; + +}; // Tizen::Net::Wifi + +}; // Tizen::Net + +namespace Security +{ +// Add constant which has compatible issue on Tizen::Security + +}; // Tizen::Security + +namespace Social +{ +// Add constant which has compatible issue on Tizen::Social + +}; // Tizen::Social + +namespace System +{ +// Add constant which has compatible issue on Tizen::System + +}; // Tizen::System + +namespace Telephony +{ +// Add constant which has compatible issue on Tizen::Telephony + +}; // Tizen::Telephony + +namespace Test +{ +// Add constant which has compatible issue on Tizen::Test + +}; // Tizen::Test + +namespace Text +{ +// Add constant which has compatible issue on Tizen::Text + +}; // Tizen::Text + +namespace Ui +{ +// Add constant which has compatible issue on Tizen::Ui + +namespace Animations +{ +// Add constant which has compatible issue on Tizen::Ui::Animations +} + +namespace Controls +{ +#define MIN_FLASH_VOLUME 0 +#define MAX_FLASH_VOLUME 100 +#define DEFAULT_FLASH_VOLUME 50 +} + +}; // Tizen::Ui + +namespace Uix +{ +// Add constant which has compatible issue on Tizen::Uix + +}; // Tizen::Uix + +namespace Web +{ +// Add constant which has compatible issue on Tizen::Web + +}; // Tizen::Web +}; // Tizen + +#endif // _FOSP_COMPAT_H_ diff --git a/inc/FOspConfig.h b/inc/FOspConfig.h new file mode 100644 index 0000000..97795f4 --- /dev/null +++ b/inc/FOspConfig.h @@ -0,0 +1,34 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#ifndef _FOSP_CONFIG_H_ +#define _FOSP_CONFIG_H_ + +#if defined(__GNUG__) // GCC +#define _OSP_EXPORT_ __attribute__((visibility("default"))) +#define _OSP_LOCAL_ __attribute__((visibility("hidden"))) + +#else +#define _OSP_EXPORT_ +#define _OSP_LOCAL_ + +#endif + +// _EXPORT_ define is for application +#define _EXPORT_ _OSP_EXPORT_ + +#endif // _FOSP_CONFIG_H_ diff --git a/inc/FSecAccessController.h b/inc/FSecAccessController.h new file mode 100644 index 0000000..7d526c3 --- /dev/null +++ b/inc/FSecAccessController.h @@ -0,0 +1,96 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @if VISPARTNER + * @file FSecAccessController.h + * @brief This is the header file for the %AccessController class. + * + * This header file contains the declarations of the %AccessController class. + * @endif + */ + +#ifndef _FSEC_ACCESS_CONTROLLER_H_ +#define _FSEC_ACCESS_CONTROLLER_H_ + +#include + +namespace Tizen { namespace Security +{ + +/** + * @if VISPARTNER + * @class AccessController + * @brief This class provides a way to check the privilege and visibility of privileged API. + * @since 2.0 + * @visibility partner + * + * The %AccessController class provides a way to check the privilege and visibility of privileged API. + * @endif + */ +class _OSP_EXPORT_ AccessController +{ + +public: + + /** + * @if VISPARTNER + * + * Checks whether the application has a privilege and a visibility to invoke the privileged API. + * + * @since 2.0 + * @visibility partner + * @return An error code + * @param[in] privilege A value of enumerator of the specified @c privilege + * @exception E_SUCCESS The method is successful and the request is granted. + * @exception E_DATA_NOT_FOUND The privilege information does not exist. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM An unexpected system error has occurred. + * @endif + */ + static result CheckPrivilege(int privilege); + +private: + + /** + * This default constructor is intentionally declared as private because this class cannot be constructed. + */ + AccessController(void); + + /** + * This destructor is intentionally declared as private because this class cannot be constructed. + */ + ~AccessController(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + AccessController(const AccessController& rhs); + + /** + * The implementation of this copy assignment operator is intentionally blank and delcared as private to prohibit copying of objects. + */ + AccessController& operator =(const AccessController& rhs); + + static void Initialize(void); + +}; // AccessController + +}} // Tizen::Security + +#endif // _FSEC_ACCESS_CONTROLLER_H_ diff --git a/inc/FSecAesSecureRandom.h b/inc/FSecAesSecureRandom.h new file mode 100644 index 0000000..cbd8070 --- /dev/null +++ b/inc/FSecAesSecureRandom.h @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecAesSecureRandom.h + * @brief This is the header file for the %AesSecureRandom class. + * + * This header file contains the declarations of the %AesSecureRandom class. + */ +#ifndef _FSEC_AES_SECURE_RANDOM_H_ +#define _FSEC_AES_SECURE_RANDOM_H_ + +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class AesSecureRandom + * @brief This class generates a secure random object with the Advanced Encryption Standard (AES) method. + * + * @since 2.0 + * + * The %AesSecureRandom class generates a secure random object for seeding cryptographic algorithms. + * The Advanced Encryption Standard (AES) method generates a user-defined number of random bytes. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see ISecureRandom + * @see DesSecureRandom + * @see DesEdeSecureRandom + */ +class _OSP_EXPORT_ AesSecureRandom + : public virtual ISecureRandom + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + AesSecureRandom(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~AesSecureRandom(void); + + /** + * Generates a user-defined number of random bytes. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class, @n + * else @c null if an error occurs + * @param[in] numBytes The number of random bytes to generate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c numBytes is @c 0 or negative. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GenerateRandomBytesN(int numBytes); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + AesSecureRandom(const AesSecureRandom& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + AesSecureRandom& operator =(const AesSecureRandom& rhs); + +private: + class _AesSecureRandomImpl* __pAesSecureRandomImpl; + friend class _AesSecureRandomImpl; + +}; //AesSecureRandom + +} } //Tizen::Security + +#endif //_FSEC_AES_SECURE_RANDOM_H_ diff --git a/inc/FSecCert.h b/inc/FSecCert.h new file mode 100644 index 0000000..a7f68db --- /dev/null +++ b/inc/FSecCert.h @@ -0,0 +1,58 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert.h + * @brief This is the header file for the %Cert namespace. + * + * This header file contains the declarations and descriptions of the %Cert namespace. + */ +#ifndef _FSEC_CERT_H_ +#define _FSEC_CERT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + + +/** + * @namespace Tizen::Security::Cert + * @brief This namespace contains classes and interfaces for managing the X.509 digital certificate. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %Cert namespace contains classes and interfaces for managing certificates, by getting information from security certificates and validating their paths. @n + * + * For more information on the %Cert namespace features, see Cert Guide. + * + * The following diagram illustrates the relationships between the classes belonging to the %Cert namespace. + * @image html security_cert_classdiagram.png + * + */ +namespace Tizen { namespace Security { namespace Cert +{ + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_H_ diff --git a/inc/FSecCertICertificate.h b/inc/FSecCertICertificate.h new file mode 100644 index 0000000..9135c47 --- /dev/null +++ b/inc/FSecCertICertificate.h @@ -0,0 +1,440 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertICertificate.h + * @brief This is the header file for the %ICertificate interface. + * + * This header file contains the declarations of the %ICertificate interface. + */ +#ifndef _FSEC_CERT_ICERTIFICATE_H_ +#define _FSEC_CERT_ICERTIFICATE_H_ + +#include +#include +#include + +namespace Tizen { namespace Security { namespace Cert +{ + +/** + * @enum CertificateType + * + * Defines the type of certificate. + * + * @since 2.0 + */ +enum CertificateType +{ + ROOT_CA, /**< The Factory-supplied certificates for SSL: ROOT CA */ + OPERATOR_DOMAIN, /**< The Operator Domain */ + TRUSTED_THIRD_PARTY_DOMAIN, /**< The Trusted Third Party Domain */ + USER_CERT, /**< The User Certificates */ + UNKNOWN_TYPE = 10, /**< The unknown type */ +}; //CertificateType + +/** + * @enum ValidityPeriod + * + * Defines the validity period. + * + * @since 2.0 + */ +enum ValidityPeriod +{ + VALIDITY_PERIOD_VALID, /**< The validity period */ + VALIDITY_PERIOD_EXPIRED, /**< The expiry period */ + VALIDITY_PERIOD_NOT_YET_VALID, /**< The period that is not yet valid */ +}; //ValidityPeriod + +/** + * @interface ICertificate + * @brief This interface manages a variety of identity certificates. + * + * @since 2.0 + * + * The %ICertificate interface is an abstraction for certificates having different formats. For example, different types of certificates, such as X.509 and PGP, share + * general functionalities, namely encoding and verifying, and some type of information like public keys. Despite containing different sets of information and having different ways for storing, and retrieving them, + * the X.509, X.968, and WTLS certificates can all be implemented by using the %ICertificate interface. + * + * An identity certificate is a binding of a principal to a public key, which is vouched for by another principal. + * A principal represents an entity, such as an individual user, a group, or a corporation. @n + * + * For more information on the class features, see Certificates. + * + * The following example demonstrates how to use the %ICertificate interface. + * + * + * @code + * + * void + * MyCertificate::Sample(void) + * { + * X509Certificate *pCertificate = null; + * String serialNumber; + * String algorithm; + * String start; + * String end; + * String subjectName; + * String issuerName; + * ByteBuffer *pSignature = null; + * ByteBuffer *pFingerprint = null; + * ByteBuffer input; + * result r = E_FAILURE; + * + * String fileName(Tizen::App::App::GetInstance()->GetAppRootPath() + L"data/UTsSecurity/Security/Domain3Certs/TestCert1-1.der"); + * File file; + * FileAttributes attribute; + * + * r = file.Construct(fileName, L"r"); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = file.GetAttributes(fileName, attribute); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = input.Construct((int)attribute.GetFileSize()); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = file.Read(input); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * input.Flip(); + * + * pCertificate = new X509Certificate; + * pCertificate->Construct(input); + * + * serialNumber = pCertificate->GetSerialNumber(); + * algorithm = pCertificate->GetSignatureAlgorithm(); + * start = pCertificate->GetNotBefore(); + * end = pCertificate->GetNotAfter(); + * subjectName = pCertificate->GetSubject(); + * issuerName = pCertificate->GetIssuer(); + * + * pSignature = pCertificate->GetSignatureN(); + * if (pSignature == null) + * { + * goto CATCH; + * } + * + * pFingerprint = pCertificate->GetFingerprintN(); + * if (pFingerprint == null) + * { + * goto CATCH; + * } + * + * r = E_SUCCESS; + * + * CATCH: + * if (pCertificate) + * { + * delete pCertificate; + * } + * if (pSignature) + * { + * delete pSignature; + * } + * if (pFingerprint) + * { + * delete pFingerprint; + * } + * } + * + * @endcode + * + */ + +class _OSP_EXPORT_ ICertificate +{ + +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~ICertificate(void) {} + + /** + * Gets the format name for this certificate. + * + * @since 2.0 + * + * @return The format of this certificate + */ + virtual Tizen::Base::String GetFormat(void) const = 0; + + /** + * Gets the certificate type. + * + * @since 2.0 + * + * @return The type of this certificate + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual CertificateType GetType(void) const = 0; + + /** + * Gets the encoded form of the certificate. @n + * It is assumed that each certificate type has a single form of encoding. For example, X.509 certificates can be encoded as ASN.1 DER. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation or the + * Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedDataN(void) const = 0; + + /** + * Gets the fingerprint of the certificate. @n + * It is the hashed value of the encoding of the certificate. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate parsing operation or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetFingerprintN(void) const = 0; + + /** + * Verifies whether the certificate is signed using the private key corresponding to the specified public key. + * + * @since 2.0 + * + * @return @c true if the certificate is signed using the private key corresponding to the specified public key, @n + * else @c false + * @param[in] publicKey A reference to IPublicKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c publicKey is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate parsing operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual bool Verify(const Tizen::Security::IPublicKey& publicKey) = 0; + + /** + * Gets the public key of this certificate. + * + * @since 2.0 + * + * @return A pointer to the IPublicKey interface, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::IPublicKey* GetPublicKeyN(void) const = 0; + + /** + * Gets the @c serialNumber value from the certificate. @n + * The serial number is an integer assigned by the Certification Authority (CA) to each certificate. It is unique for each certificate issued by a + * given CA (that is, the issuer name and serial number must identify a unique certificate). @n + * + * The ASN.1 definition for this is as follows: + * + * @code + * serialNumber CertificateSerialNumber. + * + * CertificateSerialNumber ::= INTEGER + * @endcode + * + * Since the serial number can be greater than the system's maximum value for @c int, the output parameter type is @c ByteBuffer, instead of @c int. + * + * @since 2.0 + * + * @return The serial number of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate serial number information. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetSerialNumber(void) const = 0; + + /** + * Checks whether the certificate is currently valid. @n + * It is valid if the current date and time are within the validity period given in the certificate. @n + * The validity period consists of two date and time values: the initial date and time, and the final date and time until the validity of the certificate. @n + * + * It is defined in ASN.1 as: + * + * @code + * validity Validity + * + * Validity ::= SEQUENCE { + * notBefore CertificateValidityDate, + * notAfter CertificateValidityDate } + * + * CertificateValidityDate ::= CHOICE { + * utcTime UTCTime, + * generalTime GeneralizedTime } + * @endcode + * + * @since 2.0 + * + * @return The validity period of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual ValidityPeriod CheckValidityPeriod(void) = 0; + + + /** + * Gets the notBefore value of Tizen::Base::String type from the validity period of the certificate. @n + * This value represents the date and time before which the certificate is not valid. + * + * @since 2.0 + * + * @return A string representing the date and time value before which the certificate is not valid + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate validity information. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Security::Cert::X509Certificate::CheckValidityPeriod() for relevant ASN.1 definitions + */ + virtual Tizen::Base::String GetNotBefore(void) const = 0; + + + /** + * Gets the notAfter value of Tizen::Base::String type from the validity period of the certificate. @n + * This value represents the date and time after which the certificate is not valid. + * + * @since 2.0 + * + * @return A string representing the date and time value after which the certificate is not valid + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate validity information. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Tizen::Security::Cert::X509Certificate::CheckValidityPeriod() for relevant ASN.1 definitions + */ + virtual Tizen::Base::String GetNotAfter(void) const = 0; + + /** + * Gets the name of the issuer of the certificate. + * + * @since 2.0 + * + * @return The name of the issuer of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate issuer information. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetIssuer(void) const = 0; + + /** + * Gets the subject name of the certificate. + * + * @since 2.0 + * + * @return The subject name of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate issuer information. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetSubject(void) const = 0; + + /** + * Gets the signature of the certificate. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetSignatureN(void) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificate_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificate_Reserved2(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificate_Reserved3(void) {} + +}; //ICertificate + +} } } //Tizen::Security::Cert + +#endif //_FSEC_CERT_ICERTIFICATE_H_ diff --git a/inc/FSecCertICertificatePath.h b/inc/FSecCertICertificatePath.h new file mode 100644 index 0000000..881c656 --- /dev/null +++ b/inc/FSecCertICertificatePath.h @@ -0,0 +1,343 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertICertificatePath.h + * @brief This is the header file for the %ICertificatePath interface. + * + * This header file contains the declarations of the %ICertificatePath interface. + */ +#ifndef _FSEC_CERT_ICERTIFICATE_PATH_H_ +#define _FSEC_CERT_ICERTIFICATE_PATH_H_ + +#include +#include +#include + +namespace Tizen { namespace Security { namespace Cert +{ + +class ICertificatePathValidationResult; +/** + * @interface ICertificatePath + * @brief This interface validates the certificate path and gets more information about it. + * + * @since 2.0 + * + * The %ICertificatePath interface validates the certificate path and gets more information about it. @n + * + * For more information on the class features, see Certificates. @n + * + * The following example demonstrates how to use the %ICertificatePath interface. + * + * @code + * + * void + * MyCertificatePath::Sample(void) + * { + * X509Certificate *pCertificate1 = null; + * X509Certificate *pCertificate2 = null; + * + * ICertificate *pTrustCa = null; + * ByteBuffer input1, input2; + * int depth = 0; + * ValidationResult valResult; + * result r = E_FAILURE; + * + * ICertificatePath *pCertPath = null; + * + * String fileName1(Tizen::App::App::GetInstance()->GetAppRootPath() + L"data/UTsSecurity/Security/Domain3Certs/TestCert1-1.der"); + * String fileName2(Tizen::App::App::GetInstance()->GetAppRootPath() + L"data/UTsSecurity/Security/Domain3Certs/TestCert1-2.der"); + * File file1, file2; + * FileAttributes attribute1, attribute2; + * + * r = file1.Construct(fileName1, L"r"); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = file1.GetAttributes(fileName1, attribute1); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = input1.Construct((int)attribute1.GetFileSize()); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = file1.Read(input1); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * input1.Flip(); + * + * r = file2.Construct(fileName2, L"r"); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = file2.GetAttributes(fileName2, attribute2); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = input2.Construct((int)attribute2.GetFileSize()); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = file2.Read(input2); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * input2.Flip(); + * + * // Certificate1 + * pCertificate1 = new X509Certificate; + * pCertificate1->Construct(input1); + * + * // Certificate2 + * pCertificate2 = new X509Certificate; + * pCertificate2->Construct(input2); + * + * // Certificate Path + * pCertPath = new X509CertificatePath(); + * if (pCertPath == null) + * { + * goto CATCH; + * } + * + * r = pCertPath->AddCertificate(*pCertificate1); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = pCertPath->AddCertificate(*pCertificate2); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * + * // Certificate Path Validation Result + * valResult = pCertPath->Validate(); + * if (valResult != VALIDATION_SUCCESS) + * { + * goto CATCH; + * } + * + * depth = pCertPath->GetLength(); + * if (depth == 0) + * { + * goto CATCH; + * } + * + * for (int i = 0; i < depth; i++) + * { + * ICertificate *pOutCert = pCertPath->GetCertificateN(i); + * + * if (pOutCert) + * { + * String subjectName; + * subjectName = pOutCert->GetSubject(); + * } + * + * delete pOutCert; + * } + * + * pTrustCa = pCertPath->GetTrustAnchorN(); + * if (pTrustCa) + * { + * String subjectName; + * subjectName = pTrustCa->GetSubject(); + * } + * + * delete pTrustCa; + * + * r = E_SUCCESS; + * + * CATCH: + * delete pCertificate1; + * delete pCertificate2; + * delete pCertPath; + * } + * + * @endcode + * + */ + +class _OSP_EXPORT_ ICertificatePath +{ + +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~ICertificatePath(void) {} + + /** + * Gets the format of the certificate path. + * + * @since 2.0 + * + * @return The format of the certificate + */ + virtual Tizen::Base::String GetFormat(void) const = 0; + + /** + * Adds a certificate to the certificate chain. + * + * @since 2.0 + * + * @return An error code + * @param[in] certificate A reference to a certificate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + */ + virtual result AddCertificate(const Tizen::Security::Cert::ICertificate& certificate) = 0; + + /** + * Validates the specified certificate path. + * + * @since 2.0 + * + * @return The result of the certificate path validation + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ValidationResult Validate(void) = 0; + + /** + * Validates the specified certificate path. + * + * @since 2.0 + * + * @return The result of the certificate path validation + * @param[in] trustAnchor The most trusted Certificate Authority (CA) + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ValidationResult Validate(const Tizen::Security::Cert::ICertificate& trustAnchor) = 0; + + /** + * Gets the trust anchor for the certificate path. + * + * @since 2.0 + * + * @return The root certificate, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ICertificate* GetTrustAnchorN(void) const = 0; + + /** + * Gets the length of the certificate path. + * + * @since 2.0 + * + * @return The length of the certificate path, @n + * else @c -1 if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate list is empty. + */ + virtual int GetLength(void) const = 0; + + /** + * Gets the list of certificates in this certificate path. + * + * @since 2.0 + * + * @return A pointer to the ICertificate interface, @n + * else @c null if an error occurs + * @param[in] nth The nth certificate in the certificate path (starts from @c 0) + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The value of the specified @c nth is out of the valid range. @n + * It must be less than GetLength(). + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate list is empty. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ICertificate* GetCertificateN(int nth) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificatePath_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificatePath_Reserved2(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificatePath_Reserved3(void) {} + +}; //ICertificatePath + +} } } //Tizen::Security::Cert + +#endif //_FSEC_CERT_ICERTIFICATE_PATH_H_ diff --git a/inc/FSecCertICertificateSelector.h b/inc/FSecCertICertificateSelector.h new file mode 100644 index 0000000..ce67118 --- /dev/null +++ b/inc/FSecCertICertificateSelector.h @@ -0,0 +1,109 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertICertificateSelector.h + * @brief This is the header file for the %ICertificateSelector interface. + * + * This header file contains the declarations of the %ICertificateSelector interface. + */ +#ifndef _FSEC_CERT_ICERTIFICATE_SELECTOR_H_ +#define _FSEC_CERT_ICERTIFICATE_SELECTOR_H_ + +#include + + +namespace Tizen { namespace Security { namespace Cert +{ + +/** + * @interface ICertificateSelector + * @brief This interface is a selector that defines a set of criterion for selecting certificates. + * + * @since 2.0 + * + * The %ICertificateSelector interface is a selector that defines a set of criterion for selecting certificates. + * The classes that implement this interface are used to specify the certificates, which must be retrieved from a certificate store. @n + * + * For more information on the class features, see Certificates. + * + */ +class _OSP_EXPORT_ ICertificateSelector +{ + +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~ICertificateSelector(void) {} + + /** + * Gets the certificate type. + * + * @since 2.0 + * + * @return The certificate type + */ + virtual CertificateType GetType(void) const = 0; + + /** + * Sets the certificate type. + * + * @since 2.0 + * + * @param[in] certificateType The certificate type + */ + virtual void SetType(const CertificateType certificateType) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificateSelector_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificateSelector_Reserved2(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificateSelector_Reserved3(void) {} + +}; // ICertificateSelector + +} } } // Tizen::Security::Cert + +#endif // _FSEC_CERT_ICERTIFICATE_SELECTOR_H_ diff --git a/inc/FSecCertICertificateStore.h b/inc/FSecCertICertificateStore.h new file mode 100644 index 0000000..45a74cf --- /dev/null +++ b/inc/FSecCertICertificateStore.h @@ -0,0 +1,211 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @if VISPARTNER + * @file FSecCertICertificateStore.h + * @brief This is the header file for the %ICertificateStore interface. + * + * This header file contains the declarations of the %ICertificateStore interface. + * + * @endif + */ +#ifndef _FSEC_CERT_ICERTIFICATE_STORE_H_ +#define _FSEC_CERT_ICERTIFICATE_STORE_H_ + +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Security { namespace Cert +{ + +/** + * @if VISPARTNER + * @interface ICertificateStore + * @brief This is the interface for retrieving and managing the certificates from a repository. + * + * @since 2.0 + * + * @visibility partner + * + * The %ICertificateStore interface is used for retrieving and managing the certificates from a repository. + * @endif + */ +class _OSP_EXPORT_ ICertificateStore +{ + +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~ICertificateStore(void) {} + + /** + * Gets the @c name of the certificate store. + * + * @since 2.0 + * + * @return An error code + * @param[out] name The name of the certificate store + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + virtual result GetName(Tizen::Base::String& name) const = 0; + + /** + * Sets a list of certificates that match the specified selector. + * + * @since 2.0 + * + * @return An error code + * @param[in] selector A selector that defines a set of criterion for selecting certificates + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The IPC operation has failed. + * @exception E_INVALID_ARG The specified @c selector is invalid. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + virtual result SetCertificateSelector(const Tizen::Security::Cert::ICertificateSelector& selector) = 0; + + /** + * Gets the count of certificates that match the specified selector. + * + * @since 2.0 + * + * @return An error code + * @param[out] count The count of certificates + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + virtual result GetCertificateCount(int& count) const = 0; + + /** + * Gets each certificate that matches the specified selector. + * + * @since 2.0 + * + * @return The certificates that match the specified selector + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The Tizen::Base::ByteBuffer operation has failed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ICertificate* GetNextCertificateN(void) const = 0; + + /** + * Inserts the certificate into the certificate store. + * + * @since 2.0 + * + * @return An error code + * @param[in] certificateType The type of the Certificate (that is, ROOT_CA, OPERATOR_DOMAIN, or TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] certificate A reference to the certificate to insert + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, or + * the specified @c certificateType is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * Either the IPC operation or the file operation or the DB operation has failed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + virtual result Insert(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate) = 0; + + /** + * Updates the certificate in the certificate store. + * + * @since 2.0 + * + * @return An error code + * @param[in] certificateType The type of the Certificate (that is, ROOT_CA, OPERATOR_DOMAIN, or TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] oldCert A reference to the old certificate + * @param[in] newCert A reference to the new certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, or + * the specified @c certificateType is invalid. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * Either the IPC operation or the file operation or the DB operation has failed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + virtual result Update(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& oldCert, const Tizen::Security::Cert::ICertificate& newCert) = 0; + + /** + * Removes the certificate from the certificate store. + * + * @since 2.0 + * + * @return An error code + * @param[in] certificateType The type of the Certificate (that is, ROOT_CA, OPERATOR_DOMAIN, or TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] certificate A reference to the certificate to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, or + * the specified @c certificateType is invalid. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * Either the IPC operation or the file operation or the DB operation has failed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + */ + virtual result Remove(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificateStore_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificateStore_Reserved2(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ICertificateStore_Reserved3(void) {} + +}; //ICertificateStore + +} } } //Tizen::Security::Cert + +#endif //_FSEC_CERT_ICERTIFICATE_STORE_H_ diff --git a/inc/FSecCertTypes.h b/inc/FSecCertTypes.h new file mode 100644 index 0000000..dc0b0c4 --- /dev/null +++ b/inc/FSecCertTypes.h @@ -0,0 +1,50 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertTypes.h + * @brief This is the header file for the %CertTypes definitions. + * + * This header file contains the %CertTypes definitions. + */ +#ifndef _FSEC_CERT_TYPES_H_ +#define _FSEC_CERT_TYPES_H_ + +namespace Tizen { namespace Security { namespace Cert +{ + +/** + * @enum ValidationResult + * + * Defines the validation result. + * + * @since 2.0 + */ +enum ValidationResult +{ + VALIDATION_SUCCESS = 0, /**< Success */ + VALIDATION_ERROR_INVALID_PATH, /**< The certificate path does not validate */ + VALIDATION_ERROR_NO_ROOT, /**< The root certificate is not found */ + VALIDATION_ERROR_CERT_EXPIRED, /**< The certificate date falls outside the validity period */ + VALIDATION_ERROR_CERT_REVOKED, /**< The certificate has been revoked */ + VALIDATION_ERROR_INVALID_SIGNATURE, /**< The signature is not valid */ + +}; //ValidationResult + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_TYPES_H_ diff --git a/inc/FSecCertX509Certificate.h b/inc/FSecCertX509Certificate.h new file mode 100644 index 0000000..15fb6a2 --- /dev/null +++ b/inc/FSecCertX509Certificate.h @@ -0,0 +1,355 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertX509Certificate.h + * @brief This is the header file for the %X509Certificate class. + * + * This header file contains the declarations of the %X509Certificate class. + */ +#ifndef _FSEC_CERT_X509_CERTIFICATE_H_ +#define _FSEC_CERT_X509_CERTIFICATE_H_ + +#include +#include + +namespace Tizen { namespace Security { namespace Cert +{ + +/** + * @class X509Certificate + * @brief This class is used for managing a variety of identity certificates. + * + * @since 2.0 + * + * The %X509Certificate class is used for managing a variety of identity certificates. @n + * + * For more information on the class features, see Certificates. + * + * @see ICertificate + */ +class _OSP_EXPORT_ X509Certificate + : public virtual ICertificate + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + X509Certificate(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~X509Certificate(void); + + /** + * Initializes this instance of %X509Certificate with the specified input buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The Tizen::Base::ByteBuffer operation has failed. + */ + result Construct(const Tizen::Base::ByteBuffer& input); + + /** + * Gets the format name for this certificate. + * + * @since 2.0 + * + * @return The format of this certificate + */ + virtual Tizen::Base::String GetFormat(void) const; + + /** + * Gets the certificate type. + * + * @since 2.0 + * + * @return The certificate type + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual CertificateType GetType(void) const; + + /** + * Gets the encoded form of the certificate. @n + * It is assumed that each certificate type will have only a single form of encoding. For example, X.509 certificates will be encoded as ASN.1 DER. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedDataN(void) const; + + /** + * Gets the fingerprint of the certificate. @n + * It is the hashed value of the encoding of the certificate. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate parsing operation or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetFingerprintN(void) const; + + /** + * Verifies whether the certificate is signed using the private key that corresponds to the specified public key. + * + * @since 2.0 + * + * @return @c true if the certificate is signed using the private key that corresponds to the specified public key, @n + * else @c false + * @param[in] publicKey A reference to IPublicKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c publicKey is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate parsing operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual bool Verify(const Tizen::Security::IPublicKey& publicKey); + + /** + * Gets the public key of this certificate. + * + * @since 2.0 + * + * @return A pointer to IPublicKey, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::IPublicKey* GetPublicKeyN(void) const; + + // (X.509 only, that is, not inherited from the ICertificate interface) + /** + * Gets the specification version value (version number) from the certificate. @n + * + * The ASN.1 definition for this is as follows: + * + * @code + * version [0] EXPLICIT Version DEFAULT v1 + * Version ::= INTEGER { v1(0), v2(1), v3(2) } + * @endcode + * + * @since 2.0 + * + * @return The version number of the X.509 certificate (that is, 1, 2, or 3) + */ + int GetSpecVersion(void) const; + + /** + * Gets the serial number value from the certificate. @n + * The serial number is an integer assigned by the Certification Authority (CA) to each certificate. It is unique for each certificate issued by a given + * CA (that is, the issuer name and serial number must identify a unique certificate). @n + * + * The ASN.1 definition for this is as follows: + * + * @code + * serialNumber CertificateSerialNumber + * + * CertificateSerialNumber ::= INTEGER + * @endcode + * + * This serial number can be greater than the system's maximum defined value for @c int, the output parameter type is @c ByteBuffer, instead of @c int. + * + * @since 2.0 + * + * @return The serial number of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetSerialNumber(void) const; + + /** + * Checks whether the certificate is currently valid. @n + * It is valid if the current date and time are within the validity period given in the certificate. The validity period consists of two date and time + * values: the initial date and time, and the final date and time until the validity of the certificate. @n + * + * It is defined in ASN.1 as: + * + * @code + * validity Validity + * + * Validity ::= SEQUENCE { + * notBefore CertificateValidityDate, + * notAfter CertificateValidityDate } + * + * CertificateValidityDate ::= CHOICE { + * utcTime UTCTime, + * generalTime GeneralizedTime } + * @endcode + * + * @since 2.0 + * + * @return The validity period of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual ValidityPeriod CheckValidityPeriod(void); + + /** + * Gets the notBefore value of @c String type from the validity period of the certificate. @n + * This value represents the date and time before which the certificate is not valid. + * + * @since 2.0 + * + * @return A string representing the date and time value before which the certificate is not valid + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate validity information. + * @see Tizen::Security::Cert::X509Certificate::CheckValidityPeriod(void) for relevant ASN.1 definitions. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetNotBefore(void) const; + + + /** + * Gets the notAfter value of @c String type from the validity period of the certificate. @n + * This value represents the date and time after which the certificate is not valid. + * + * @since 2.0 + * + * @return A string representing the date and time value after which the certificate is not valid + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate validity information. + * @see Tizen::Security::Cert::X509Certificate::CheckValidityPeriod(void) for relevant ASN.1 definitions. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetNotAfter(void) const; + + /** + * Gets the name of the issuer of the certificate. + * + * @since 2.0 + * + * @return The name of the issuer of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate issuer information. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetIssuer(void) const; + + /** + * Gets the subject name of the certificate. + * + * @since 2.0 + * + * @return The subject name of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to get the certificate issuer information. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetSubject(void) const; + + /** + * Gets the signature algorithm identifier from the given certificate. @n + * For example, the string "SHA-1/DSA". @n + * + * The ASN.1 definition for this is as follows: + * + * @code + * signatureAlgorithm AlgorithmIdentifier + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL } + * @endcode + * + * The algorithm name is determined from the algorithm OID string. + * + * @since 2.0 + * + * @return The signature algorithm of the certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::String GetSignatureAlgorithm(void) const; + + /** + * Gets the signature of the certificate. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetSignatureN(void) const; + +private: + X509Certificate(const X509Certificate& rhs); + X509Certificate& operator =(const X509Certificate& rhs); + +private: + void* __certHandle; + Tizen::Base::String __certFormat; + class _X509CertificateImpl* __pX509CertificateImpl; + friend class _X509CertificateImpl; + +}; //X509Certificate + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_X509_CERTIFICATE_H_ diff --git a/inc/FSecCertX509CertificatePath.h b/inc/FSecCertX509CertificatePath.h new file mode 100644 index 0000000..0820f08 --- /dev/null +++ b/inc/FSecCertX509CertificatePath.h @@ -0,0 +1,185 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertX509CertificatePath.h + * @brief This is the header file for the %X509CertificatePath class. + * + * This header file contains the declarations of the %X509CertificatePath class. + */ +#ifndef _FSEC_CERT_X509_CERTIFICATE_PATH_H_ +#define _FSEC_CERT_X509_CERTIFICATE_PATH_H_ + +#include +#include +#include + + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertMgrSvcProxy; + +/** + * @class X509CertificatePath + * @brief This class provides the certificate path. + * + * @since 2.0 + * + * The %X509CertificatePath class provides the certificate path. @n + * + * For more information on the class features, see Certificates. + */ +class _OSP_EXPORT_ X509CertificatePath + : public virtual ICertificatePath + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + X509CertificatePath(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~X509CertificatePath(void); + + /** + * Gets the format name for the certificate path. + * + * @since 2.0 + * + * @return The format of the certificate + */ + virtual Tizen::Base::String GetFormat(void) const; + + /** + * Adds a certificate to the certificate chain. + * + * @since 2.0 + * + * @return An error code + * @param[in] certificate A reference to a certificate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + */ + virtual result AddCertificate(const Tizen::Security::Cert::ICertificate& certificate); + + /** + * Validates the specified certificate path. + * + * @since 2.0 + * + * @return The result of the certificate path validation + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ValidationResult Validate(void); + + /** + * Validates the specified certificate path. + * + * @since 2.0 + * + * @return The result of the certificate path validation + * @param[in] trustAnchor The most trusted Certificate Authority (CA) + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ValidationResult Validate(const Tizen::Security::Cert::ICertificate& trustAnchor); + + /** + * Gets the length of the certificate path. + * + * @since 2.0 + * + * @return The length of the certificate path, @n + * else @c -1 if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + */ + virtual int GetLength(void) const; + + /** + * Gets the list of the certificates in this certificate path. + * + * @since 2.0 + * + * @return A pointer to the ICertificate interface, @n + * else @c null if an error occurs + * @param[in] nth The nth certificate in the certificate path (starts from @c 0) + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The value of the specified @c nth is out of the valid range. @n + * It must be less than GetLength(). + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ICertificate* GetCertificateN(int nth) const; + + /** + * Gets the trust anchor for the certificate path. + * + * @since 2.0 + * + * @return The root certificate, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The certificate link list operation or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::Cert::ICertificate* GetTrustAnchorN(void) const; + +private: + X509CertificatePath(const X509CertificatePath& rhs); + X509CertificatePath& operator =(const X509CertificatePath& rhs); + +private: + void* __certCtx; + int __depth; + int __trustAnchorIndex; + + class _X509CertificatePathImpl* __pX509CertificatePathImpl; + friend class _X509CertificatePathImpl; + +}; //X509CertificatePath + +} } } //Tizen::Security::Cert + +#endif //_FSEC_CERT_X509_CERTIFICATE_PATH_H_ diff --git a/inc/FSecCertX509CertificateSelector.h b/inc/FSecCertX509CertificateSelector.h new file mode 100644 index 0000000..7b02597 --- /dev/null +++ b/inc/FSecCertX509CertificateSelector.h @@ -0,0 +1,98 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertX509CertificateSelector.h + * @brief This is the header file for the %X509CertificateSelector class. + * + * This header file contains the declarations of the %X509CertificateSelector class. + */ +#ifndef _FSEC_CERT_X509_CERTIFICATE_SELECTOR_H_ +#define _FSEC_CERT_X509_CERTIFICATE_SELECTOR_H_ + +#include + + +namespace Tizen { namespace Security { namespace Cert +{ + +/** + * @class X509CertificateSelector + * @brief This class is used for managing a variety of identity certificates. + * + * @since 2.0 + * + * The %X509CertificateSelector class is a selector that defines a set of criterion for selecting certificates. @n + * + * For more information on the class features, see Certificates. + * + * @see ICertificate + * @see Tizen::Security::Cert::ICertificateSelector + */ +class _OSP_EXPORT_ X509CertificateSelector + : public virtual ICertificateSelector + , public Tizen::Base::Object +{ + +public: + /** + * This is the constructor for this class. + * + * @since 2.0 + */ + X509CertificateSelector(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~X509CertificateSelector(void); + + /** + * Gets the certificate type. + * + * @since 2.0 + * + * @return The certificate type + */ + virtual CertificateType GetType(void) const; + + /** + * Sets the certificate type. + * + * @since 2.0 + * + * @param[in] certificateType The certificate type + */ + virtual void SetType(const CertificateType certificateType); + +private: + X509CertificateSelector(const X509CertificateSelector& rhs); + X509CertificateSelector& operator =(const X509CertificateSelector& rhs); + +private: + CertificateType __certType; + + class _X509CertificateSelectorImpl* __pX509CertificateSelectorImpl; + friend class _X509CertificateSelectorImpl; + +}; // X509CertificateSelector + +} } } // Tizen::Security::Cert + +#endif // _FSEC_CERT_X509_CERTIFICATE_SELECTOR_H_ diff --git a/inc/FSecCertX509CertificateStore.h b/inc/FSecCertX509CertificateStore.h new file mode 100755 index 0000000..15c1139 --- /dev/null +++ b/inc/FSecCertX509CertificateStore.h @@ -0,0 +1,252 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @if VISPARTNER + * @file FSecCertX509CertificateStore.h + * @brief This is the header file for the %X509CertificateStore class. + * + * This header file contains the declarations of the %X509CertificateStore class. + * + * @endif + */ +#ifndef _FSEC_CERT_X509_CERTIFICATE_STORE_H_ +#define _FSEC_CERT_X509_CERTIFICATE_STORE_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertMgrSvcProxy; + +/** + * @if VISPARTNER + * @class X509CertificateStore + * @brief This class is used for retrieving and managing certificates from a repository. + * + * @since 2.0 + * + * @visibility partner + * + * The %X509CertificateStore class is used for retrieving and managing certificates from a repository. + * @endif + */ +class _OSP_EXPORT_ X509CertificateStore + : public virtual ICertificateStore + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + X509CertificateStore(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~X509CertificateStore(void); + + /** + * @if VISPARTNER + * Gets the name of the current certificate store. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/certificate.read + * + * @return An error code + * @param[out] name The name of the certificate store + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + virtual result GetName(Tizen::Base::String& name) const; + + /** + * @if VISPARTNER + * Sets a list of certificates that match the specified @c selector. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/certificate.read + * + * @return An error code + * @param[in] selector A selector that defines a set of criterion for selecting certificates + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The IPC operation has failed. + * @exception E_INVALID_ARG The specified @c selector is invalid. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + virtual result SetCertificateSelector(const Tizen::Security::Cert::ICertificateSelector& selector); + + /** + * @if VISPARTNER + * Gets a count of certificates that match the specified selector. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/certificate.read + * + * @return An error code + * @param[out] count The count of certificates + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + virtual result GetCertificateCount(int& count) const; + + /** + * @if VISPARTNER + * Gets each certificate that matches the specified selector. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/certificate.read + * + * @return The certificates that matches the specified selector + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The Tizen::Base::ByteBuffer operation has failed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + virtual Tizen::Security::Cert::ICertificate* GetNextCertificateN(void) const; + + /** + * @if VISPARTNER + * Inserts the certificate into the certificate store. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/certificate.write + * + * @return An error code + * @param[in] certificateType The type of the Certificate (ROOT_CA, OPERATOR_DOMAIN, or TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] certificate A reference to the certificate to insert + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, or + * the specified @c certificateType is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * Either the IPC operation or the file operation or the DB operation has failed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + virtual result Insert(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate); + + /** + * @if VISPARTNER + * Updates the certificate in the certificate store. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/certificate.write + * + * @return An error code + * @param[in] certificateType The type of the Certificate (ROOT_CA, OPERATOR_DOMAIN, or TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] oldCert A reference to the old certificate + * @param[in] newCert A reference to the new certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, or + * the specified @c certificateType is invalid. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * Either the IPC operation or the file operation or the DB operation has failed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + virtual result Update(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& oldCert, const Tizen::Security::Cert::ICertificate& newCert); + + /** + * @if VISPARTNER + * Removes the certificate from the certificate store. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/certificate.write + * + * @return An error code + * @param[in] certificateType The type of the Certificate (ROOT_CA, OPERATOR_DOMAIN, TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] certificate A reference to the certificate to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, or + * the specified @c certificateType is invalid. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. @n + * Either the IPC operation or the file operation or the DB operation has failed. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + virtual result Remove(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate); + + /** + * @if VISPARTNER + * Inserts the user certificate of PKCS 12 format into the certificate store. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/certificate.write + * + * @return An error code + * @param[in] filePath The file path of PKCS 12 certificate to insert + * @param[in] password The password string to decrypt PKCS 12 certificate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @endif + */ + result InsertPkcs12(const Tizen::Base::String& filePath, const Tizen::Base::String& password); + +private: + X509CertificateStore(const X509CertificateStore& rhs); + X509CertificateStore& operator =(const X509CertificateStore& rhs); + +private: + class _X509CertificateStoreImpl* __pX509CertificateStoreImpl; + friend class _X509CertificateStoreImpl; + +}; //X509CertificateStore + +} } } //Tizen::Security::Cert + +#endif //_FSEC_CERT_X509_CERTIFICATE_STORE_H_ diff --git a/inc/FSecCrypto.h b/inc/FSecCrypto.h new file mode 100644 index 0000000..d8f2f19 --- /dev/null +++ b/inc/FSecCrypto.h @@ -0,0 +1,75 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto.h + * @brief This is the header file for the %Crypto namespace. + * + * This header file contains the declarations and descriptions of the %Crypto namespace. + */ +#ifndef _FSEC_CRYPTO_H_ +#define _FSEC_CRYPTO_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/** + * @namespace Tizen::Security::Crypto + * @brief This namespace contains classes and interfaces for the cryptographic primitives. + * + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %Crypto namespace provides classes and methods to handle encryption and decryption using hashing, symmetric and asymmetric ciphers. It also provides a mechanism for sending messages over an insecure channel using a key pair (public and private keys). @n + * + * For more information on the %Crypto namespace features, see Crypto Guide. @n + * + * The following diagram illustrates the relationships between the classes belonging to the %Crypto namespace. + * @image html security_crypto_classdiagram.png + * + */ +namespace Tizen { namespace Security { namespace Crypto +{ + +} } } // Tizen::Security::Crypto + +#endif // _FSEC_CRYPTO_H_ diff --git a/inc/FSecCryptoAesCipher.h b/inc/FSecCryptoAesCipher.h new file mode 100644 index 0000000..93b3248 --- /dev/null +++ b/inc/FSecCryptoAesCipher.h @@ -0,0 +1,281 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoAesCipher.h + * @brief This is the header file for the %AesCipher class. + * + * This header file contains the declarations of the %AesCipher class. + */ +#ifndef _FSEC_CRYPTO_AES_CIPHER_H_ +#define _FSEC_CRYPTO_AES_CIPHER_H_ + +#include + +struct evp_cipher_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SymmetricCipher; +/** + * @class AesCipher + * @brief This class provides methods for encryption and decryption using the Advanced Encryption Standard (AES) method. + * + * @since 2.0 + * + * The %AesCipher class provides a symmetric cipher using the Advanced Encryption Standard (AES) method. + * Set appropriate values for the requested mode/key bit/padding scheme and cipher operation mode (CIPHER_ENCRYPT, CIPHER_DECRYPT, CIPHER_WRAP, or CIPHER_UNWRAP) parameters. @n + * + * For more information on the class features, see Ciphers. + * + * @see ISymmetricCipher + * @see DesCipher + * @see DesEdeCipher + */ +class _OSP_EXPORT_ AesCipher + : public virtual ISymmetricCipher + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + AesCipher(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~AesCipher(void); + + /** + * Initializes this instance of %AesCipher with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] transformation The name of the requested mode/key bit/padding scheme @n + * For example, "CBC/128/NOPADDING" or "CBC/192/NOPADDING". + * @param[in] opMode The cipher operation mode @n + * For example, @c CIPHER_ENCRYPT, @c CIPHER_DECRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c opMode does not contain a valid value for the cipher operation. + * @remarks If @c opMode is not matching the actual operation, the result of the operation is @c null and an exception is returned. @n + * For example, if @c opMode is set to @c CIPHER_ENCRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP and the DecryptN() method is used, then the result obtained is @c null and an exception is returned. + */ + virtual result Construct(const Tizen::Base::String& transformation, enum CipherOperation opMode); + + /** + * Sets a symmetric key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Sets the initial vector. + * + * @since 2.0 + * + * @return An error code + * @param[in] initialVector The initial vector + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector); + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Initializes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + + /** + * Wraps a key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] secretKey The secret key to wrap + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_UNSUPPORTED_ALGORITHM The specified cipher algorithm for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A key is set using SetKey() before calling this method. + */ + virtual Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey); + + /** + * Unwraps a previously wrapped key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] wrappedKey The wrapped key to unwrap + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_UNSUPPORTED_ALGORITHM The specified cipher algorithm for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A key is set using SetKey() before calling this method. + */ + virtual Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + AesCipher(const AesCipher& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + AesCipher& operator =(const AesCipher& rhs); + +private: + _SymmetricCipher* __pSymmetricCipher; + const evp_cipher_st* __pCipherAlgorithm; + Tizen::Base::String __cipherAlgorithm; + + class _AesCipherImpl* __pAesCipherImpl; + friend class _AesCipherImpl; + +}; //AesCipher + +} } } //Tizen::Security:Crypto + +#endif //_FSEC_CRYPTO_AES_CIPHER_H_ diff --git a/inc/FSecCryptoCastCipher.h b/inc/FSecCryptoCastCipher.h new file mode 100644 index 0000000..977333b --- /dev/null +++ b/inc/FSecCryptoCastCipher.h @@ -0,0 +1,269 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoCastCipher.h + * @brief This is the header file for the %CastCipher class. + * + * This header file contains the declarations of the %CastCipher class. + */ +#ifndef _FSEC_CRYPTO_CAST_CIPHER_H_ +#define _FSEC_CRYPTO_CAST_CIPHER_H_ + +#include + +struct evp_cipher_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SymmetricCipher; +/** + * @class CastCipher + * @brief This class provides methods for encryption and decryption using the CAST-128 algorithm. + * + * @since 2.0 + * + * The %CastCipher class provides a symmetric cipher using the CAST-128 algorithm. + * Set appropriate values for the requested mode/key bit/padding scheme and cipher operation mode (CIPHER_ENCRYPT + * or CIPHER_DECRYPT) parameters. @n + * + * For more information on the class features, see Ciphers. + * + * @see ISymmetricCipher + * @see AesCipher + * @see DesCipher + */ +class _OSP_EXPORT_ CastCipher + : public virtual ISymmetricCipher + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + CastCipher(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~CastCipher(void); + + /** + * Initializes this instance of %CastCipher with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] transformation The name of the requested key bit/padding scheme @n + * The valid values for %CastCipher are "128/PKCS7PADDING" and "128/NOPADDING". + * @param[in] opMode The cipher operation mode @n + * The valid values for %CastCipher are @c CIPHER_ENCRYPT and @c CIPHER_DECRYPT. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c opMode does not contain a valid value for the cipher operation. + * @remarks If @c opMode is not matching the actual operation, the result of the operation is @c null and an exception is returned. @n + * For example, if @c opMode is set to @c CIPHER_ENCRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP and the DecryptN() method is used, then the result obtained is @c null and an exception is returned. + */ + virtual result Construct(const Tizen::Base::String& transformation, enum CipherOperation opMode); + + /** + * Sets a symmetric key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Sets the initial vector. + * + * @since 2.0 + * + * @return An error code + * @param[in] initialVector The initial vector + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector); + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Initializes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + + /** + * Wraps a key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] secretKey The secret key to wrap + * @remarks This operation is not supported in the %CastCipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned if the GetLastResult() method is called. + */ + virtual Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey); + + /** + * Unwraps a previously wrapped key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] wrappedKey The wrapped key to unwrap + * @remarks This operation is not supported in the %CastCipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned if the GetLastResult() method is called. + */ + virtual Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + CastCipher(const CastCipher& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + CastCipher& operator =(const CastCipher& rhs); + +private: + _SymmetricCipher* __pSymmetricCipher; + const evp_cipher_st* __pCipherAlgorithm; + Tizen::Base::String __cipherAlgorithm; + + class _CastCipherImpl* __pCastCipherImpl; + friend class _CastCipherImpl; + +}; //CastCipher + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_CAST_CIPHER_H_ diff --git a/inc/FSecCryptoDesCipher.h b/inc/FSecCryptoDesCipher.h new file mode 100644 index 0000000..b6f174b --- /dev/null +++ b/inc/FSecCryptoDesCipher.h @@ -0,0 +1,269 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoDesCipher.h + * @brief This is the header file for the %DesCipher class. + * + * This header file contains the declarations of the %DesCipher class. + */ +#ifndef _FSEC_CRYPTO_DES_CIPHER_H_ +#define _FSEC_CRYPTO_DES_CIPHER_H_ + +#include + +struct evp_cipher_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SymmetricCipher; +/** + * @class DesCipher + * @brief This class provides methods for encryption and decryption using the Data Encryption Standard (DES) method. + * + * @since 2.0 + * + * The %DesCipher class provides a symmetric cipher using the Data Encryption Standard (DES) method. + * Sets appropriate values for the requested mode/key bit/padding scheme and cipher operation mode + * (CIPHER_ENCRYPT or CIPHER_DECRYPT) parameters. @n + * + * For more information on the class features, see Ciphers. + * + * @see ISymmetricCipher + * @see AesCipher + * @see DesEdeCipher + */ +class _OSP_EXPORT_ DesCipher + : public virtual ISymmetricCipher + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + DesCipher(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DesCipher(void); + + /** + * Initializes this instance of %DesCipher with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] transformation The name of the requested mode/key bit/padding scheme @n + * For example, "CBC/NOPADDING" or "CBC/PKCS7PADDING". + * @param[in] opMode The cipher operation mode @n + * The valid values for %DesCipher are @c CIPHER_ENCRYPT and @c CIPHER_DECRYPT. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c opMode does not contain a valid value for the cipher operation. + * @remarks If @c opMode is not matching the actual operation, the result of the operation is @c null and an exception is returned. @n + * For example, if @c opMode is set to @c CIPHER_ENCRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP and the DecryptN() method is used, then the result obtained is @c null and an exception is returned. + */ + virtual result Construct(const Tizen::Base::String& transformation, enum CipherOperation opMode); + + /** + * Sets a symmetric key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Sets the initial vector. + * + * @since 2.0 + * + * @return An error code + * @param[in] initialVector The initial vector + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector); + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Initializes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + + /** + * Wraps a key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] secretKey The secret key to wrap + * @remarks This operation is not supported in the %DesCipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey); + + /** + * Unwraps a previously wrapped key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] wrappedKey The wrapped key to unwrap + * @remarks This operation is not supported in the %DesCipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DesCipher(const DesCipher& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DesCipher& operator =(const DesCipher& rhs); + +private: + _SymmetricCipher* __pSymmetricCipher; + const evp_cipher_st* __pCipherAlgorithm; + Tizen::Base::String __cipherAlgorithm; + + class _DesCipherImpl* __pDesCipherImpl; + friend class _DesCipherImpl; + +}; //DesCipher + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_DES_CIPHER_H_ diff --git a/inc/FSecCryptoDesEdeCipher.h b/inc/FSecCryptoDesEdeCipher.h new file mode 100644 index 0000000..cbea9f4 --- /dev/null +++ b/inc/FSecCryptoDesEdeCipher.h @@ -0,0 +1,267 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoDesEdeCipher.h + * @brief This is the header file for the %DesEdeCipher class. + * + * This header file contains the declarations of the %DesEdeCipher class. + */ +#ifndef _FSEC_CRYPTO_DES_EDE_CIPHER_H_ +#define _FSEC_CRYPTO_DES_EDE_CIPHER_H_ + +#include + +struct evp_cipher_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SymmetricCipher; +/** + * @class DesEdeCipher + * @brief This class provides methods for encryption and decryption using the Data Encryption Standard in the Encrypt-Decrypt-Encrypt (DES-EDE) mode. + * + * @since 2.0 + * + * The %DesEdeCipher class provides symmetric cipher using the Data Encryption Standard in the Encrypt-Decrypt-Encrypt (DES-EDE) mode. + * Sets appropriate values for the requested mode/key bit/padding scheme and cipher operation (CIPHER_ENCRYPT or CIPHER_DECRYPT) parameters. @n + * + * For more information on the class features, see Ciphers. + * + * @see ISymmetricCipher + * @see DesCipher + * @see AesCipher + */ +class _OSP_EXPORT_ DesEdeCipher + : public virtual ISymmetricCipher + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + DesEdeCipher(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DesEdeCipher(void); + + /** + * Initializes this instance of %DesEdeCipher with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] transformation The name of the requested mode/key bit/padding scheme @n + * For example, "CBC/NOPADDING" or "CBC/PKCS7PADDING". + * @param[in] opMode The cipher operation mode @n + * The valid values for %DesEdeCipher are @c CIPHER_ENCRYPT and @c CIPHER_DECRYPT. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c opMode does not contain a valid value for the cipher operation. + * @remarks If @c opMode is not matching the actual operation, the result of the operation is @c null and an exception is returned. @n + * For example, if @c opMode is set to @c CIPHER_ENCRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP and the DecryptN() method is used, then the result obtained is @c null and an exception is returned. + */ + virtual result Construct(const Tizen::Base::String& transformation, enum CipherOperation opMode); + /** + * Sets a symmetric key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Sets the initial vector. + * + * @since 2.0 + * + * @return An error code + * @param[in] initialVector The initial vector + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector); + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Initializes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + + /** + * Wraps a key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] secretKey The secret key to wrap + * @remarks This operation is not supported in the %DesEdeCipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey); + + /** + * Unwraps a previously wrapped key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] wrappedKey The wrapped key to unwrap + * @remarks This operation is not supported in the %DesEdeCipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DesEdeCipher(const DesEdeCipher& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DesEdeCipher& operator =(const DesEdeCipher& rhs); + +private: + _SymmetricCipher* __pSymmetricCipher; + const evp_cipher_st* __pCipherAlgorithm; + Tizen::Base::String __cipherAlgorithm; + + class _DesEdeCipherImpl* __pDesEdeCipherImpl; + friend class _DesEdeCipherImpl; + +}; //DesEdeCipher + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_DES_EDE_CIPHER_H_ diff --git a/inc/FSecCryptoDhKeyExchange.h b/inc/FSecCryptoDhKeyExchange.h new file mode 100644 index 0000000..152aa0c --- /dev/null +++ b/inc/FSecCryptoDhKeyExchange.h @@ -0,0 +1,271 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoDhKeyExchange.h + * @brief This is the header file for the %DhKeyExchange class. + * + * This header file contains the declarations of the %DhKeyExchange class. + */ +#ifndef _FSEC_CRYPTO_DH_KEYEXCHANGE_H_ +#define _FSEC_CRYPTO_DH_KEYEXCHANGE_H_ + +#include + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class DhKeyExchange + * @brief This class provides methods for a key exchange mechanism using the Diffie-Hellman (DH) algorithm. + * + * @since 2.0 + * + * The %DhKeyExchange class provides a DH key exchange between two communicating users. @n + * + * For more information on the class features, see Key exchanging. + * + * @see IKeyExchange + * @see KeyPairGenerator + * + * The following example demonstrates how to use the %DhKeyExchange class. + * @code + * + * void DhGenerateSecretExample(void) + * { + * result r = E_SUCCESS; + * KeyPair *pKeyPair = null; + * KeyPair *pKeyPair1 = null; + * IPrivateKey *pPriKey = null; + * IPublicKey *pPubKey = null; + * IPrivateKey *pPriKey1 = null; + * IPublicKey *pPubKey1 = null; + * KeyPairGenerator *pKeyPairGen = null; + * IKeyParameters *pKeyParams = null; + * int size = 1024; + * DhKeyExchange *pDhKeyExchangeAlice = null; + * DhKeyExchange *pDhKeyExchangeBob = null; + * ByteBuffer *pBuffer = null; + * ByteBuffer *pBuffer1 = null; + * + * SetLastResult(E_SUCCESS); + * // Generates the key. + * pKeyPairGen = new KeyPairGenerator(); + * if (pKeyPairGen == null) + * { + * goto CATCH; + * } + * + * + * r = pKeyPairGen->Construct(size, "DH"); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pKeyParams = pKeyPairGen->GenerateKeyParametersN(); + * if (pKeyParams == null) + * { + * goto CATCH; + * } + * + * + * pKeyPair = pKeyPairGen->GenerateKeyPairN(pKeyParams); + * if (pKeyPair == null) + * { + * goto CATCH; + * } + * + * pKeyPair1 = pKeyPairGen->GenerateKeyPairN(pKeyParams); + * if (pKeyPair1 == null) + * { + * goto CATCH; + * } + * + * + * pPubKey = pKeyPair->GetPublicKey(); + * if (pPubKey == null) + * { + * goto CATCH; + * } + * + * + * pPriKey = pKeyPair->GetPrivateKey(); + * if (pPriKey == null) + * { + * goto CATCH; + * } + * + * + * pPubKey1 = pKeyPair1->GetPublicKey(); + * if (pPubKey1 == null) + * { + * goto CATCH; + * } + * + * + * pPriKey1 = pKeyPair1->GetPrivateKey(); + * if (pPriKey1 == null) + * { + * goto CATCH; + * } + * + * + * pDhKeyExchangeAlice = new DhKeyExchange (); + * if (pDhKeyExchangeAlice == null) + * { + * goto CATCH; + * } + * + * pDhKeyExchangeBob = new DhKeyExchange (); + * if (pDhKeyExchangeBob == null) + * { + * goto CATCH; + * } + * + * // Calling the Construct API. + * r = pDhKeyExchangeAlice->Construct(*pKeyParams); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = pDhKeyExchangeBob->Construct(*pKeyParams); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pBuffer = pDhKeyExchangeAlice->GenerateSecretN(*pPriKey, *pPubKey1); + * if (pBuffer == null) + * { + * goto CATCH; + * } + * + * pBuffer1 = pDhKeyExchangeBob->GenerateSecretN(*pPriKey1, *pPubKey); + * if (pBuffer1 == null) + * { + * goto CATCH; + * } + * + * if (*pBuffer == *pBuffer1) + * { + * AppLog("The secret is generated SuccessFully"); + * } + * else + * { + * goto CATCH; + * } + * + * CATCH: + * delete pKeyPairGen; + * delete pKeyPair; + * delete pKeyPair1; + * delete pBuffer; + * delete pBuffer1; + * delete pDhKeyExchangeAlice; + * delete pDhKeyExchangeBob; + * delete pKeyParams; + * + * } + * + * @endcode + * + */ + +class _OSP_EXPORT_ DhKeyExchange + : public virtual IKeyExchange + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + DhKeyExchange(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DhKeyExchange(void); + + /** + * Initializes this instance of %DhKeyExchange with the specified key parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyParameters The domain parameters ('p' prime number and 'g' generator) of DH + * algorithm that needs to instantiate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid, or the specified @c keyParameters does not contain a valid value. */ + virtual result Construct(const Tizen::Security::IKeyParameters& keyParameters); + + /** + * Generates the final shared secret between two parties. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the generated secret key, @n + * else @c null if the method fails to generate the secret key + * @param[in] privateKey The private key component of the first party that needs to instantiate + * @param[in] publicKey The public key component of the second party that needs to instantiate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GenerateSecretN(Tizen::Security::IPrivateKey& privateKey, Tizen::Security::IPublicKey& publicKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DhKeyExchange(const DhKeyExchange& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DhKeyExchange& operator =(const DhKeyExchange& rhs); + +private: + Tizen::Base::ByteBuffer* __pParamsP; + Tizen::Base::ByteBuffer* __pParamsG; + + class _DhKeyExchangeImpl* __pDhKeyExchangeImpl; + friend class _DhKeyExchangeImpl; + +}; //DhKeyExchange + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_DH_KEYEXCHANGE_H_ diff --git a/inc/FSecCryptoIAsymmetricCipher.h b/inc/FSecCryptoIAsymmetricCipher.h new file mode 100644 index 0000000..d540f92 --- /dev/null +++ b/inc/FSecCryptoIAsymmetricCipher.h @@ -0,0 +1,245 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoIAsymmetricCipher.h + * @brief This is the header file for the %IAsymmetricCipher interface. + * + * This header file contains the declarations of the %IAsymmetricCipher interface. + */ +#ifndef _FSEC_CRYPTO_IASYMMETRIC_CIPHER_H_ +#define _FSEC_CRYPTO_IASYMMETRIC_CIPHER_H_ + +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @interface IAsymmetricCipher + * @brief This interface provides the functionality of an asymmetric cryptographic cipher for encryption and decryption. + * + * @since 2.0 + * + * The %IAsymmetricCipher interface provides the functionality of an asymmetric cryptographic cipher for encryption and decryption. @n + * + * For more information on the class features, see Ciphers. @n + * + * The following example demonstrates how to use the %IAsymmetricCipher interface. + * + * @code + * + * void + * MyClass::TestAsymmetricCipherSample(void) + * { + * result r = E_FAILURE; + * IAsymmetricCipher *pCipher = null; + * IKeyPairGenerator *pKeyPairGen = null; + * KeyPair *pKeyPair = null; + * IPrivateKey *pPriKey = null; + * IPublicKey *pPubKey = null; + * ByteBuffer input; + * ByteBuffer *pOutput = null; + * ByteBuffer *pDecOutput = null; + * ByteBuffer keyBytes; + * ByteBuffer iv; + * byte pArray[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P'}; + * int size = 1024; + * + * r = input.Construct(16); + * r = input.SetArray(pArray, 0, 16); + * input.Flip(); + * + * pCipher = new RsaCipher(); + * if (pCipher == null) + * { + * goto CATCH; + * } + * + * // Generates the key. + * pKeyPairGen = new KeyPairGenerator(); + * if (pKeyPairGen == null) + * { + * goto CATCH; + * } + * + * r = pKeyPairGen->Construct(size); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pKeyPair = pKeyPairGen->GenerateKeyPairN(); + * if (pKeyPair == null) + * { + * goto CATCH; + * } + * + * pPubKey = pKeyPair->GetPublicKey(); + * if (pPubKey == null) + * { + * goto CATCH; + * } + * + * pPriKey = pKeyPair->GetPrivateKey(); + * if (pPriKey == null) + * { + * goto CATCH; + * } + * + * r = pCipher->SetPublicKey(*pPubKey); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pOutput = pCipher->EncryptN(input); + * if (pOutput == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * r = pCipher->SetPrivateKey(*pPriKey); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pDecOutput = pCipher->DecryptN(*pOutput); + * if (pDecOutput == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * if (memcmp(pDecOutput->GetPointer(), input.GetPointer(), input.GetRemaining()) != 0) + * { + * goto CATCH; + * } + * + * r = E_SUCCESS; + * + * CATCH: + * delete pCipher; + * delete pOutput; + * delete pDecOutput; + * delete pKeyPairGen; + * delete pKeyPair; + * } + * + * @endcode + */ + +class _OSP_EXPORT_ IAsymmetricCipher +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IAsymmetricCipher(void) {} + + /** + * Sets an asymmetric private key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of IKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetPrivateKey(const Tizen::Security::IKey& key) = 0; + + /** + * Sets an asymmetric public key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of IKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetPublicKey(const Tizen::Security::IKey& key) = 0; + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input) = 0; + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IAsymmetricCipher_Reserved1(void) {} + +}; //IAsymmetricCipher + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_IASYMMETRIC_CIPHER_H_ diff --git a/inc/FSecCryptoIHash.h b/inc/FSecCryptoIHash.h new file mode 100644 index 0000000..ebc98f5 --- /dev/null +++ b/inc/FSecCryptoIHash.h @@ -0,0 +1,296 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoIHash.h + * @brief This is the header file for the %IHash interface. + * + * This header file contains the declarations of the %IHash interface. + */ +#ifndef _FSEC_CRYPTO_IHASH_H_ +#define _FSEC_CRYPTO_IHASH_H_ + +#include +#include + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @interface IHash + * @brief This interface provides the functionality of a hash algorithm. + * + * @since 2.0 + * + * The %IHash interface provides the functionality of a hash algorithm. @n + * + * For more information on the class features, see Hashing. @n + * + * The following example demonstrates how to use the %IHash interface. + * @code + * + * result + * MyClass::TestHashSample(void) + * { + * const int messageLen = 49; + * static const byte message[messageLen] = { + * 0xF4, 0xA4, 0xA2, 0x40, 0xB0, 0xAB, 0x73, 0x1B, 0xC8, 0x10, 0xEA, 0x08, 0x9C, 0xD0, 0x78, 0x0D, + * 0x40, 0xB9, 0x94, 0x02, 0x21, 0x79, 0xFD, 0x5A, 0xA3, 0xC9, 0x17, 0x64, 0x9B, 0x27, 0xC5, 0x20, + * 0x03, 0x7B, 0x4D, 0x7C, 0x4D, 0xE6, 0xEE, 0x64, 0x78, 0xA2, 0xBE, 0x2C, 0x22, 0x0A, 0x8E, 0x37, + * 0xB4, + * }; + * + * const int sampleOutputLen = 20; + * static const byte sampleOutput[sampleOutputLen] = { + * 0xC4, 0x10, 0xB8, 0x6E, 0xDA, 0x00, 0xE3, 0x2C, 0x8A, 0xC4, + * 0xE5, 0xDC, 0xB0, 0xE0, 0xE8, 0x2C, 0x21, 0xB6, 0x4E, 0x73 + * }; + * + * const int Sha1Len = 20; + * + * result r = E_FAILURE; + * IHash * pHash = null; + * + * ByteBuffer input; + * ByteBuffer *pOutput = null; + * + * input.Construct(messageLen); + * input.SetArray(message, 0, messageLen); + * input.Flip(); + * + * pHash = new Sha1Hash(); + * if (pHash == null) + * { + * goto CATCH; + * } + * + * pOutput = pHash->GetHashN(input); + * if (pOutput == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * if (memcmp(pOutput->GetPointer(), sampleOutput, Sha1Len) != 0) + * { + * goto CATCH; + * } + * r = E_SUCCESS; + * + * CATCH: + * delete pHash; + * delete pOutput; + * + * return r; + * } + * + * + * result + * MyClass::TestHashSample_Multipart(void) + * { + * const int messageLen = 49; + * static const byte message[messageLen] = { + * 0xF4, 0xA4, 0xA2, 0x40, 0xB0, 0xAB, 0x73, 0x1B, 0xC8, 0x10, 0xEA, 0x08, 0x9C, 0xD0, 0x78, 0x0D, + * 0x40, 0xB9, 0x94, 0x02, 0x21, 0x79, 0xFD, 0x5A, 0xA3, 0xC9, 0x17, 0x64, 0x9B, 0x27, 0xC5, 0x20, + * 0x03, 0x7B, 0x4D, 0x7C, 0x4D, 0xE6, 0xEE, 0x64, 0x78, 0xA2, 0xBE, 0x2C, 0x22, 0x0A, 0x8E, 0x37, + * 0xB4, + * }; + * + * const int sampleOutputLen = 20; + * static const byte sampleOutput[sampleOutputLen] = { + * 0xC4, 0x10, 0xB8, 0x6E, 0xDA, 0x00, 0xE3, 0x2C, 0x8A, 0xC4, + * 0xE5, 0xDC, 0xB0, 0xE0, 0xE8, 0x2C, 0x21, 0xB6, 0x4E, 0x73 + * }; + * + * const int Sha1Len = 20; + * int unitLen = messageLen / 5; + * int dataLen = 0; + * + * result r = E_FAILURE; + * IHash * pHash = null; + * + * ByteBuffer input; + * ByteBuffer *pOutput = null; + * + * input.Construct(messageLen); + * input.SetArray(message, 0, messageLen); + * input.Flip(); + * + * pHash = new Sha1Hash(); + * if (pHash == null) + * { + * goto CATCH; + * } + * + * r = pHash->Initialize(); + * if (r != E_SUCCESS) + * { + * goto CATCH; + * } + * + * for (int i = 0; i * unitLen < messageLen; i++) + * { + * if (messageLen - (i * unitLen) < unitLen) + * { + * dataLen = messageLen - (i * unitLen); + * } + * else + * { + * dataLen = unitLen; + * } + * + * // messageLen == 98 + * input.Construct(dataLen); + * input.SetArray(message + (i * unitLen), 0, dataLen); + * input.Flip(); + * + * r = pHash->Update(input); + * if (r != E_SUCCESS) + * { + * goto CATCH; + * } + * + * input.Clear(); + * } + * + * pOutput = pHash->FinalizeN(); + * if (pOutput == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * if (memcmp(pOutput->GetPointer(), sampleOutput, Sha1Len) != 0) + * { + * goto CATCH; + * } + * + * r = E_SUCCESS; + * + * CATCH: + * delete pHash; + * delete pOutput; + * + * return r; + * } + * + * @endcode + */ + +class _OSP_EXPORT_ IHash +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IHash(void) {} + + /** + * Sets the hash algorithm. @n + * Only supported in Secure Hash Algorithm-2 (SHA-2). + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the hash algorithm @n + * For example, "SHA2/224", "SHA2/256", "SHA2/386", or "SHA2/512". + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + */ + virtual result SetAlgorithm(const Tizen::Base::String& algorithm) = 0; + + /** + * Gets the hashes of the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* GetHashN(const Tizen::Base::ByteBuffer& input) const = 0; + + /** + * Initializes a multiple-part hash operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + */ + virtual result Initialize(void) = 0; + + /** + * Updates a multiple-part hash operation while processing another data part. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual result Update(const Tizen::Base::ByteBuffer& input) = 0; + + /** + * Finalizes a multiple-part hash operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IHash_Reserved1(void) {} + +}; //IHash + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_IHASH_H_ diff --git a/inc/FSecCryptoIHmac.h b/inc/FSecCryptoIHmac.h new file mode 100644 index 0000000..bf4c576 --- /dev/null +++ b/inc/FSecCryptoIHmac.h @@ -0,0 +1,404 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoIHmac.h + * @brief This is the header file for the %IHmac interface. + * + * This header file contains the declarations of the %IHmac interface. + */ +#ifndef _FSEC_CRYPTO_IHMAC_H_ +#define _FSEC_CRYPTO_IHMAC_H_ + +#include +#include +#include + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @interface IHmac + * @brief This interface provides the functionality of a Hash Message Authentication Code (HMAC) algorithm. + * + * @since 2.0 + * + * The %IHmac interface provides the functionality of a Hash Message Authentication Code (HMAC) algorithm. @n + * + * For more information on the class features, see Hashing. @n + * + * The following example demonstrates how to use the %IHmac interface. + * + * @code + * + * result + * MyClass::TestHmacSample(void) + * { + * const int messageLen = 64; + * static const byte message[messageLen] = { + * 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + * 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, + * 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + * 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, + * 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + * 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, + * 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + * 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80 + * }; + * + * const int macKeyLen = 20; + * static const byte macKey[macKeyLen] = { + * 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + * 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, + * 0x20, 0x21, 0x22, 0x23 + * }; + * + * const int sampleOutputLen = 20; + * static const byte sampleOutput[sampleOutputLen] = { + * 0x0f, 0xf4, 0xd8, 0x25, 0x33, 0xe5, 0xd8, 0x22, + * 0x70, 0x8c, 0x8f, 0x76, 0xda, 0x9e, 0x6c, 0xaf, + * 0x71, 0xea, 0x1a, 0x5b + * }; + * + * const int Sha1Len = 20; + * + * result r = E_FAILURE; + * IHmac *pHmac = null; + * ByteBuffer input; + * ByteBuffer *pOutput = null; + * ByteBuffer keyBytes; + * SecretKeyGenerator *pKeyGen = null; + * ISecretKey *pKey = null; + * + * input.Construct(messageLen); + * input.SetArray(message, 0, messageLen); + * input.Flip(); + * + * keyBytes.Construct(macKeyLen); + * keyBytes.SetArray(macKey, 0, macKeyLen); + * keyBytes.Flip(); + * + * // HMAC Creation + * pHmac = new Sha1Hmac(); + * if (pHmac == null) + * { + * goto CATCH; + * } + * + * // Generates the key. + * pKeyGen = new SecretKeyGenerator(); + * if (pKeyGen == null) + * { + * goto CATCH; + * } + * + * r = pKeyGen->Construct(keyBytes); + * if (r != E_SUCCESS) + * { + * goto CATCH; + * } + * + * pKey = pKeyGen->GenerateKeyN(); + * if (pKey == null) + * { + * goto CATCH; + * } + * + * r = pHmac->SetKey(*pKey); + * if (r != E_SUCCESS) + * { + * goto CATCH; + * } + * + * pOutput = pHmac->GetHmacN(input); + * if (pOutput == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * if (memcmp(pOutput->GetPointer(), sampleOutput, Sha1Len) != 0) + * { + * goto CATCH; + * } + * + * r = E_SUCCESS; + * CATCH: + * delete pHmac; + * delete pKeyGen; + * delete pOutput; + * delete pKey; + * + * return r; + * } + * + * result + * MyClass::TestHmacSample_Multipart(void) + * { + * const int messageLen = 64; + * static const byte message[messageLen] = { + * 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + * 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, + * 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + * 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, + * 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + * 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, + * 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + * 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80 + * }; + * + * // This contains the MAC key to be used. + * const int macKeyLen = 20; + * static const byte macKey[macKeyLen] = { + * 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + * 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, + * 0x20, 0x21, 0x22, 0x23 + * }; + * + * const int sampleOutputLen = 20; + * static const byte sampleOutput[sampleOutputLen] = { + * 0x0f, 0xf4, 0xd8, 0x25, 0x33, 0xe5, 0xd8, 0x22, + * 0x70, 0x8c, 0x8f, 0x76, 0xda, 0x9e, 0x6c, 0xaf, + * 0x71, 0xea, 0x1a, 0x5b + * }; + * + * const int Sha1Len = 20; + * int unitLen = messageLen / 5; + * int dataLen = 0; + * + * result r = E_FAILURE; + * IHmac * pHmac = null; + * ByteBuffer input; + * ByteBuffer *pOutput = null; + * ByteBuffer keyBytes; + * SecretKeyGenerator* pKeyGen = null; + * ISecretKey *pKey = null; + * + * input.Construct(messageLen); + * input.SetArray(message, 0, messageLen); + * input.Flip(); + * + * keyBytes.Construct(macKeyLen); + * keyBytes.SetArray(macKey, 0, macKeyLen); + * keyBytes.Flip(); + * + * // HMAC Creation + * pHmac = new Sha1Hmac(); + * if (pHmac == null) + * { + * goto CATCH; + * } + * + * // Generates the key. + * pKeyGen = new SecretKeyGenerator(); + * if (pKeyGen == null) + * { + * goto CATCH; + * } + * + * r = pKeyGen->Construct(keyBytes); + * if (r != E_SUCCESS) + * { + * goto CATCH; + * } + * + * pKey = pKeyGen->GenerateKeyN(); + * if (pKey == null) + * { + * goto CATCH; + * } + * + * r = pHmac->SetKey(*pKey); + * if (r != E_SUCCESS) + * { + * goto CATCH; + * } + * + * r = pHmac->Initialize(); + * if (r != E_SUCCESS) + * { + * goto CATCH; + * } + * + * for (int i = 0; i * unitLen < messageLen; i++) + * { + * if (messageLen - (i * unitLen) < unitLen) + * { + * dataLen = messageLen - (i * unitLen); + * } + * else + * { + * dataLen = unitLen; + * } + * + * // MessageLen == 98 + * input.Construct(dataLen); + * input.SetArray(message + (i * unitLen), 0, dataLen); + * input.Flip(); + * + * r = pHmac->Update(input); + * if (r != E_SUCCESS) + * { + * goto CATCH; + * } + * + * input.Clear(); + * } + * + * pOutput = pHmac->FinalizeN(); + * if (pOutput == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * if (memcmp(pOutput->GetPointer(), sampleOutput, Sha1Len) != 0) + * { + * goto CATCH; + * } + * + * r = E_SUCCESS; + * CATCH: + * delete pHmac; + * delete pKeyGen; + * delete pOutput; + * delete pKey; + * + * return r; + * } + * + * @endcode + */ + +class _OSP_EXPORT_ IHmac +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IHmac(void) {} + + /** + * Sets the HMAC algorithm. + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the HMAC algorithm @n + * For example, "HMACSHA2/224", "HMACSHA2/256", "HMACSHA2/386", or "HMACSHA2/512". + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + */ + virtual result SetAlgorithm(const Tizen::Base::String& algorithm) = 0; + + /** + * Sets the secret key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key) = 0; + + /** + * Gets the HMAC with the given input. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* GetHmacN(const Tizen::Base::ByteBuffer& input) const = 0; + + /** + * Initializes the multiple-part HMAC operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + */ + virtual result Initialize(void) = 0; + + /** + * Updates a multiple-part HMAC operation while processing another data part. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual result Update(const Tizen::Base::ByteBuffer& input) = 0; + + /** + * Finalizes a multiple-part HMAC operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IHmac_Reserved1(void) {} + +}; //IHmac + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_IHMAC_H_ diff --git a/inc/FSecCryptoIKeyExchange.h b/inc/FSecCryptoIKeyExchange.h new file mode 100644 index 0000000..fd976c4 --- /dev/null +++ b/inc/FSecCryptoIKeyExchange.h @@ -0,0 +1,128 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoIKeyExchange.h + * @brief This is the header file for the %IKeyExchange interface. + * + * This header file contains the declarations of the %IKeyExchange interface. + */ +#ifndef _FSEC_CRYPTO_IKEY_EXCHANGE_H_ +#define _FSEC_CRYPTO_IKEY_EXCHANGE_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @interface IKeyExchange + * @brief This interface provides methods for the Key Exchange algorithm. + * + * @since 2.0 + * + * The %IKeyExchange interface provides methods to exchange secure keys between two communicating users. @n + * + * For more information on the class features, see Key exchanging. + * + * @see KeyPairGenerator + */ +class _OSP_EXPORT_ IKeyExchange +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IKeyExchange(void) {} + + /** + * Initializes this instance of %IKeyExchange with the specified key parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyParameters The domain parameters of the key exchange algorithm that needs to instantiate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The key parameters can be @c null depending on the underlying key exchange algorithm. + */ + virtual result Construct(const Tizen::Security::IKeyParameters& keyParameters) = 0; + + /** + * Generates the final version of the shared secret amongst the two parties. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the generated secret key, @n + * else @c null if the method fails to generate the secret key + * @param[in] privateKey The private key component of the first party to instantiate + * @param[in] publicKey The public key component of the second party to instantiate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GenerateSecretN(Tizen::Security::IPrivateKey& privateKey, Tizen::Security::IPublicKey& publicKey) = 0; + + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IKeyExchange_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IKeyExchange_Reserved2(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IKeyExchange_Reserved3(void) {} + +}; //IKeyExchange + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_IKEY_EXCHANGE_H_ diff --git a/inc/FSecCryptoISignature.h b/inc/FSecCryptoISignature.h new file mode 100644 index 0000000..53d0684 --- /dev/null +++ b/inc/FSecCryptoISignature.h @@ -0,0 +1,235 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoISignature.h + * @brief This is the header file for the %ISignature interface. + * + * This header file contains the declarations of the %ISignature interface. + */ +#ifndef _FSEC_CRYPTO_ISIGNATURE_H_ +#define _FSEC_CRYPTO_ISIGNATURE_H_ + +#include +#include +#include + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @interface ISignature + * @brief This interface provides the functionality of a digital signature algorithm. + * + * @since 2.0 + * + * The %ISignature interface provides the functionality of a digital signature algorithm. @n + * + * For more information on the class features, see Ciphers. @n + * + * The following example demonstrates how to use the %ISignature interface. + * + * @code + * + * void + * MyClass::TestSignatureSample(void) + * { + * result r = E_FAILURE; + * ISignature *pSignature = null; + * IKeyPairGenerator *pKeyPairGen = null; + * KeyPair *pKeyPair = null; + * IPrivateKey *pPriKey = null; + * IPublicKey *pPubKey = null; + * ByteBuffer input; + * ByteBuffer *pOutput = null; + * ByteBuffer keyBytes; + * ByteBuffer iv; + * byte pArray[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P'}; + * int size = 1024; + * bool res = false; + * + * r = input.Construct(16); + * r = input.SetArray(pArray, 0, 16); + * input.Flip(); + * + * pSignature = new RsaSignature(); + * if (pSignature == null) + * { + * goto CATCH; + * } + * + * // Generates the key. + * pKeyPairGen = new KeyPairGenerator(); + * if (pKeyPairGen == null) + * { + * goto CATCH; + * } + * + * r = pKeyPairGen->Construct(size); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pKeyPair = pKeyPairGen->GenerateKeyPairN(); + * if (pKeyPair == null) + * { + * goto CATCH; + * } + * + * pPubKey = pKeyPair->GetPublicKey(); + * if (pPubKey == null) + * { + * goto CATCH; + * } + * + * pPriKey = pKeyPair->GetPrivateKey(); + * if (pPriKey == null) + * { + * goto CATCH; + * } + * + * r = pSignature->SetPrivateKey(*pPriKey); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pOutput = pSignature->SignN(input); + * if (pOutput == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * r = pSignature->SetPublicKey(*pPubKey); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * res = pSignature->Verify(input, *pOutput); + * if (res == false) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * r = E_SUCCESS; + * + * CATCH: + * delete pSignature; + * delete pOutput; + * delete pKeyPairGen; + * delete pKeyPair; + * } + * + * @endcode + */ + +class _OSP_EXPORT_ ISignature +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISignature(void) {} + + /** + * Sets an asymmetric private key for signature. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of IKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetPrivateKey(const Tizen::Security::IKey& key) = 0; + + /** + * Sets an asymmetric public key for verification. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of IKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetPublicKey(const Tizen::Security::IKey& key) = 0; + + /** + * Signs the data. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* SignN(const Tizen::Base::ByteBuffer& input) = 0; + + /** + * Verifies the data. @n + * The verification is done by comparing the @c signedData to the signature created by the @c data. + * + * @since 2.0 + * + * @return @c true if the signed data is correct, @n + * else @c false + * @param[in] data An instance of Tizen::Base::ByteBuffer that contains the original data + * @param[in] signedData An instance of Tizen::Base::ByteBuffer that contains the signed data + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual bool Verify(const Tizen::Base::ByteBuffer& data, const Tizen::Base::ByteBuffer& signedData) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISignature_Reserved1(void) {} + +}; //ISignature + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_ISIGNATURE_H_ diff --git a/inc/FSecCryptoISymmetricCipher.h b/inc/FSecCryptoISymmetricCipher.h new file mode 100644 index 0000000..bf03adc --- /dev/null +++ b/inc/FSecCryptoISymmetricCipher.h @@ -0,0 +1,424 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoISymmetricCipher.h + * @brief This is the header file for the %ISymmetricCipher interface. + * + * This header file contains the declarations of the %ISymmetricCipher interface. + */ +#ifndef _FSEC_CRYPTO_ISYMMETRIC_CIPHER_H_ +#define _FSEC_CRYPTO_ISYMMETRIC_CIPHER_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Security { namespace Crypto +{ +/** + * @interface ISymmetricCipher + * @brief This interface provides the functionalities of a symmetric cryptographic cipher for encryption and decryption. + * + * @since 2.0 + * + * The %ISymmetricCipher interface provides the functionalities of a symmetric cryptographic cipher for encryption and decryption. @n + * + * For more information on the class features, see Ciphers. @n + * + * The following example demonstrates how to use the %ISymmetricCipher interface. + * @code + * + * void + * MyClass::TestSymmetricCipherSample(void) + * { + * // #####AES CBC Test Vector(128-bits key)##### + * // PlainText: 48 Bytes + * const int messageLen = 48; + * static const byte message[messageLen] = { + * 0x87, 0x3C, 0x66, 0x1D, 0x2C, 0x0D, 0x49, 0x2D, + * 0x6C, 0x76, 0xBE, 0x44, 0x57, 0x39, 0xB8, 0x28, + * 0x84, 0x5E, 0x2A, 0x15, 0x18, 0x3B, 0x1D, 0x00, + * 0xA7, 0x6E, 0x80, 0x4D, 0x22, 0xF1, 0x2A, 0x6B, + * 0xBA, 0xFE, 0xA8, 0x02, 0x2B, 0xC2, 0x97, 0x01, + * 0x59, 0x0F, 0x3C, 0x2A, 0x67, 0x8B, 0x98, 0x69 + * }; + * + * // CipherText: 48 Bytes + * const int cipherLen = 48; + * static const byte cipher[cipherLen] = { + * 0x10, 0x84, 0x9D, 0x24, 0xEB, 0x22, 0xE0, 0x7F, + * 0xA8, 0x57, 0xE9, 0xA0, 0x4F, 0xE2, 0x3D, 0xE5, + * 0xC1, 0x51, 0x7E, 0xEB, 0xF8, 0xB3, 0x3A, 0xA2, + * 0xDC, 0xF4, 0x8B, 0xDC, 0x14, 0x0A, 0xC7, 0x58, + * 0x85, 0x6B, 0x0D, 0xE9, 0x30, 0x8B, 0xA1, 0x71, + * 0xD5, 0x0B, 0x14, 0x97, 0xEF, 0xAD, 0x22, 0x8D + * }; + * + * // KEY: 16Bytes + * const int secretKeyLen = 16; + * static const byte secretKey[secretKeyLen] = { + * 0x62, 0x5C, 0xC7, 0x7E, 0xEA, 0x7B, 0xA5, 0x4D, + * 0x47, 0xCE, 0xAF, 0x26, 0x9E, 0xB1, 0x6C, 0x2D + * }; + * + * // IV: 16Bytes + * const int ivectorLen = 16; + * static const byte ivector[ivectorLen] = { + * 0x3E, 0xB5, 0x01, 0x45, 0xE4, 0xF8, 0x75, 0x3F, + * 0x08, 0x9D, 0x9F, 0x57, 0x3B, 0x63, 0xEF, 0x4B + * }; + * + * result r = E_FAILURE; + * String transformation; + * ISymmetricCipher *pCipherEnc = null; + * ISymmetricCipher *pCipherDec = null; + * SecretKeyGenerator *pKeyGen = null; + * ISecretKey *pKey = null; + * ByteBuffer input; + * ByteBuffer *pOutput = null; + * ByteBuffer *pOutput2 = null; + * ByteBuffer keyBytes; + * ByteBuffer iv; + * + * // Input + * input.Construct(messageLen); + * input.SetArray(message, 0, messageLen); + * input.Flip(); + * + * // Key + * keyBytes.Construct(secretKeyLen); + * keyBytes.SetArray(secretKey, 0, secretKeyLen); + * keyBytes.Flip(); + * + * // IV setting + * iv.Construct(ivectorLen); + * iv.SetArray(ivector, 0, ivectorLen); + * iv.Flip(); + * + * pCipherEnc = new AesCipher(); + * if (pCipherEnc == null) + * { + * goto CATCH; + * } + * + * transformation = "CBC/128/NOPADDING"; + * + * r = pCipherEnc->Construct(transformation, CIPHER_ENCRYPT); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * // Generates the key. + * pKeyGen = new SecretKeyGenerator(); + * if (pKeyGen == null) + * { + * goto CATCH; + * } + * + * r = pKeyGen->Construct(keyBytes); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pKey = pKeyGen->GenerateKeyN(); + * if (pKey == null) + * { + * goto CATCH; + * } + * + * r = pCipherEnc->SetKey(*pKey); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = pCipherEnc->SetInitialVector(iv); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pOutput = pCipherEnc->EncryptN(input); + * if (pOutput == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * pCipherDec = new AesCipher(); + * if (pCipherDec == null) + * { + * goto CATCH; + * } + * + * r = pCipherDec->Construct(transformation, CIPHER_DECRYPT); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = pCipherDec->SetKey(*pKey); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = pCipherDec->SetInitialVector(iv); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pOutput2 = pCipherDec->DecryptN(*pOutput); + * if (pOutput2 == null) + * { + * r = GetLastResult(); + * goto CATCH; + * } + * + * if (memcmp(pOutput->GetPointer(), cipher, cipherLen) != 0) + * { + * goto CATCH; + * } + * + * if (memcmp(pOutput2->GetPointer(), input.GetPointer(), input.GetRemaining()) != 0) + * { + * goto CATCH; + * } + * + * CATCH: + * delete pCipherEnc; + * delete pCipherDec; + * delete pKeyGen; + * delete pOutput; + * delete pOutput2; + * delete pKey; + * } + * + * @endcode + * + * + */ + +class _OSP_EXPORT_ ISymmetricCipher +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISymmetricCipher(void) {} + + /** + * Initializes this instance of %ISymmetricCipher with the specified operation mode and padding scheme. + * + * @since 2.0 + * + * @return An error code + * @param[in] transformation The name of the requested mode or key bit or padding scheme + * @param[in] opMode The cipher operation mode @n + * For example, @c CIPHER_ENCRYPT, @c CIPHER_DECRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c opMode does not contain a valid value for the cipher operation. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + */ + virtual result Construct(const Tizen::Base::String& transformation, enum CipherOperation opMode = Tizen::Security::Crypto::CIPHER_ENCRYPT) = 0; + + /** + * Sets a symmetric key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key) = 0; + + /** + * Sets the initial vector. + * + * @since 2.0 + * + * @return An error code + * @param[in] initialVector The initial vector + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) = 0; + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input) = 0; + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input) = 0; + + /** + * Initializes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + */ + virtual result Initialize(void) = 0; + + /** + * Updates a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input) = 0; + + /** + * Finalizes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void) = 0; + + /** + * Wraps the specified key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] secretKey The secret key to wrap + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks This operation is only supported in AesCipher. + */ + virtual Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey) = 0; + + /** + * Unwraps a previously wrapped key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] wrappedKey The wrapped key to unwrap + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c wrappedKey Tizen::Base::ByteBuffer is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks This operation is only supported in AesCipher. + */ + virtual Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISymmetricCipher_Reserved1(void) {} + +}; //ISymmetricCipher + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_ISYMMETRIC_CIPHER_H_ diff --git a/inc/FSecCryptoKeaKeyExchange.h b/inc/FSecCryptoKeaKeyExchange.h new file mode 100644 index 0000000..6b936c0 --- /dev/null +++ b/inc/FSecCryptoKeaKeyExchange.h @@ -0,0 +1,349 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoKeaKeyExchange.h + * @brief This is the header file for the %KeaKeyExchange class. + * + * This header file contains the declarations of the %KeaKeyExchange class. + */ +#ifndef _FSEC_CRYPTO_KEA_KEY_EXCHANGE_H_ +#define _FSEC_CRYPTO_KEA_KEY_EXCHANGE_H_ + +#include + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class KeaKeyExchange + * @brief This class provides methods for performing the key exchange mechanism using Key Exchange Algorithm (KEA). + * + * @since 2.0 + * + * The %KeaKeyExchange class provides a KEA key exchange between two communicating users. @n + * + * For more information on the class features, see Key exchanging. + * + * @see IKeyExchange + * @see KeyPairGenerator + * + * The following example demonstrates how to use the %KeaKeyExchange class. + * @code + * + * void KeaGenerateSecretExample(void) + * { + * + * result r = E_SUCCESS; + * KeyPair *pKeyPairAlice1 = null; + * IPrivateKey *pPriKeyAlice1 = null; + * IPrivateKey *pPriKeyAlice2 = null; + * KeyPair *pKeyPairAlice2 = null; + * IPublicKey *pPubKeyAlice1 = null; + * IPublicKey *pPubKeyAlice2 = null; + * + * KeyPair *pKeyPairBob1 = null; + * IPrivateKey *pPriKeyBob1 = null; + * IPrivateKey *pPriKeyBob2 = null; + * KeyPair *pKeyPairBob2 = null; + * IPublicKey *pPubKeyBob1 = null; + * IPublicKey *pPubKeyBob2 = null; + * + * + * KeyPairGenerator *pKeyPairGen = null; + * IKeyParameters *pKeyParams = null; + * + * int size = 1024; + * KeaKeyExchange *pKeaKeyExchangeAlice = null; + * KeaKeyExchange *pKeaKeyExchangeBob = null; + * ByteBuffer *pBuffer = null; + * ByteBuffer *pBuffer1 = null; + * + * + * // Generates the key. + * pKeyPairGen = new KeyPairGenerator(); + * if (pKeyPairGen == null) + * { + * goto CATCH; + * } + * + * + * r = pKeyPairGen->Construct(size, L"KEA"); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * + * pKeyParams = pKeyPairGen->GenerateKeyParametersN(); + * if (pKeyParams == null) + * { + * goto CATCH; + * } + * + * + * pKeyPairAlice1 = pKeyPairGen->GenerateKeyPairN(pKeyParams); + * if (pKeyPairAlice1 == null) + * { + * goto CATCH; + * } + * + * pKeyPairAlice2 = pKeyPairGen->GenerateKeyPairN(pKeyParams); + * if (pKeyPairAlice2 == null) + * { + * goto CATCH; + * } + * + * pPriKeyAlice1 = pKeyPairAlice1->GetPrivateKey(); + * if (pPriKeyAlice1 == null) + * { + * goto CATCH; + * } + * + * pPubKeyAlice1 = pKeyPairAlice1->GetPublicKey(); + * if (pPubKeyAlice1 == null) + * { + * goto CATCH; + * } + * + * pPriKeyAlice2 = pKeyPairAlice2->GetPrivateKey(); + * if (pPriKeyAlice2 == null) + * { + * goto CATCH; + * } + * + * pPubKeyAlice2 = pKeyPairAlice2->GetPublicKey(); + * if (pPubKeyAlice2 == null) + * { + * goto CATCH; + * } + * + * pKeyPairBob1 = pKeyPairGen->GenerateKeyPairN(pKeyParams); + * if (pKeyPairBob1 == null) + * { + * goto CATCH; + * } + * + * pKeyPairBob2 = pKeyPairGen->GenerateKeyPairN(pKeyParams); + * if (pKeyPairBob2 == null) + * { + * goto CATCH; + * } + * + * pPriKeyBob1 = pKeyPairBob1->GetPrivateKey(); + * if (pPriKeyBob1 == null) + * { + * goto CATCH; + * } + * + * pPubKeyBob1 = pKeyPairBob1->GetPublicKey(); + * if (pPubKeyBob1 == null) + * { + * goto CATCH; + * } + * + * pPriKeyBob2 = pKeyPairBob2->GetPrivateKey(); + * if (pPriKeyBob2 == null) + * { + * goto CATCH; + * } + * + * pPubKeyBob2 = pKeyPairBob2->GetPublicKey(); + * if (pPubKeyBob2 == null) + * { + * goto CATCH; + * } + * + * + * pKeaKeyExchangeAlice = new KeaKeyExchange(); + * if (pKeaKeyExchangeAlice == null) + * { + * goto CATCH; + * } + * + * pKeaKeyExchangeBob = new KeaKeyExchange(); + * if (pKeaKeyExchangeBob == null) + * { + * goto CATCH; + * } + * + * r = pKeaKeyExchangeAlice->Construct(*pKeyParams); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = pKeaKeyExchangeAlice->DoPhase(*pPriKeyAlice1, *pPubKeyBob1); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = pKeaKeyExchangeBob->Construct(*pKeyParams); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * r = pKeaKeyExchangeBob->DoPhase(*pPriKeyBob1, *pPubKeyAlice1); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pBuffer = pKeaKeyExchangeAlice->GenerateSecretN(*pPriKeyAlice2, *pPubKeyBob2); + * if (pBuffer == null) + * { + * goto CATCH; + * } + * + * pBuffer1 = pKeaKeyExchangeBob->GenerateSecretN(*pPriKeyBob2, *pPubKeyAlice2); + * if (pBuffer1 == null) + * { + * goto CATCH; + * } + * + * if (*pBuffer == *pBuffer1) + * { + * AppLog("Secret is Generated Successfully"); + * } + * else + * { + * goto CATCH; + * } + * + * CATCH: + * + * delete pKeyPairGen; + * delete pKeyPairAlice1; + * delete pKeyPairAlice2; + * delete pKeyPairBob1; + * delete pKeyPairBob2; + * delete pBuffer; + * delete pBuffer1; + * delete pKeaKeyExchangeAlice; + * delete pKeaKeyExchangeBob; + * delete pKeyParams; + * } + * @endcode + * + */ + +class _OSP_EXPORT_ KeaKeyExchange + : public virtual IKeyExchange + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + KeaKeyExchange(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~KeaKeyExchange(void); + + /** + * Computes the shared secret in a phase-wise manner. @n + * The %DoPhase() method requires the first party's private key(s) and the second party's public key(s) + * to generate the shared secret. + * This method is used in algorithms such as the KEA algorithm and also for a multi-party key exchange. + * + * @since 2.0 + * + * @return An error code + * @param[in] privateKey The private key component of the first party to instantiate + * @param[in] publicKey The public key component of the second party to instantiate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * + */ + virtual result DoPhase(Tizen::Security::IPrivateKey& privateKey, Tizen::Security::IPublicKey& publicKey); + + /** + * Initializes this instance of %IKeyExchange with the specified key parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyParameters The domain parameters of the key exchange algorithm @n + * This parameter needs to be instantiated. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result Construct(const Tizen::Security::IKeyParameters& keyParameters); + + /** + * Generates the final shared secret among two parties. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the generated secret key, @n + * else @c null if the method fails to generate the secret key + * @param[in] privateKey The private key component of the first party to instantiate + * @param[in] publicKey The public key component of the second party to instantiate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GenerateSecretN(Tizen::Security::IPrivateKey& privateKey, Tizen::Security::IPublicKey& publicKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + KeaKeyExchange(const KeaKeyExchange& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + KeaKeyExchange& operator =(const KeaKeyExchange& rhs); + +private: + Tizen::Base::ByteBuffer* __pParamsP; + Tizen::Base::ByteBuffer* __pParamsG; + + Tizen::Base::ByteBuffer* __pPrivateComponent; + Tizen::Base::ByteBuffer* __pPublicComponent; + + class _KeaKeyExchangeImpl* __pKeaKeyExchangeImpl; + friend class _KeaKeyExchangeImpl; + +}; //KeaKeyExchange + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_KEA_KEY_EXCHANGE_H_ diff --git a/inc/FSecCryptoMd5Hash.h b/inc/FSecCryptoMd5Hash.h new file mode 100644 index 0000000..d79ad2e --- /dev/null +++ b/inc/FSecCryptoMd5Hash.h @@ -0,0 +1,174 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoMd5Hash.h + * @brief This is the header file for the %Md5Hash class. + * + * This header file contains the declarations of the %Md5Hash class. + */ +#ifndef _FSEC_CRYPTO_MD5_HASH_H_ +#define _FSEC_CRYPTO_MD5_HASH_H_ + +#include + +struct env_md_ctx_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class Md5Hash + * @brief This class implements the MD5 hash algorithm. + * + * @since 2.0 + * + * The %Md5Hash class implements the basic hash procedure to encrypt messages using the Message-Digest 5 hash algorithm. @n + * + * For more information on the class features, see Hashing. + + * @see IHash + * @see Sha1Hash + * @see Sha2Hash + */ +class _OSP_EXPORT_ Md5Hash + : public virtual IHash + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Md5Hash(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Md5Hash(void); + + /** + * Sets the hash algorithm. @n + * The %SetAlgorithm() method is not supported by this class. Do not call this method. + * If this method is called, it returns @c E_UNSUPPORTED_ALGORITHM. + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the hash algorithm @n + * For example, "SHA2/224", "SHA2/256", "SHA2/386", or "SHA2/512". + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + * @remarks Do not call this method. It is not supported. + */ + virtual result SetAlgorithm(const Tizen::Base::String& algorithm); + + /** + * Gets the hashes of the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetHashN(const Tizen::Base::ByteBuffer& input) const; + + /** + * Initializes a multiple-part hash operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part hash operation while processing another data part. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual result Update(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part hash operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the openssl library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Md5Hash(const Md5Hash& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Md5Hash& operator =(const Md5Hash& rhs); + +private: + env_md_ctx_st* __pEvpMdCtx; + + class _Md5HashImpl* __pMd5HashImpl; + friend class _Md5HashImpl; + +}; //Md5Hash + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_MD5_HASH_H_ diff --git a/inc/FSecCryptoMd5Hmac.h b/inc/FSecCryptoMd5Hmac.h new file mode 100644 index 0000000..81580c3 --- /dev/null +++ b/inc/FSecCryptoMd5Hmac.h @@ -0,0 +1,190 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoMd5Hmac.h + * @brief This is the header file for the %Md5Hmac class. + * + * This header file contains the declarations of the %Md5Hmac class. + */ +#ifndef _FSEC_CRYPTO_MD5_HMAC_H_ +#define _FSEC_CRYPTO_MD5_HMAC_H_ + +#include + +struct hmac_ctx_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class Md5Hmac + * @brief This class implements the MD5 HMAC algorithm. + * + * @since 2.0 + * + * The %Md5Hmac class implements the basic hash procedure to encrypt messages using the Hash Message Authentication Code (HMAC) algorithm, which provides a hash with a secret key. @n + * + * For more information on the class features, see Hashing. + * + * @see IHmac + * @see Sha1Hmac + * @see Sha2Hmac + */ +class _OSP_EXPORT_ Md5Hmac + : public virtual IHmac + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Md5Hmac(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Md5Hmac(void); + + /** + * Sets the HMAC algorithm. @n + * The %SetAlgorithm() method is not supported by this class. Do not call this method. + * If this method is called, it returns @c E_UNSUPPORTED_ALGORITHM. + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the HMAC algorithm @n + * For example, "HMACSHA2/224", "HMACSHA2/256", "HMACSHA2/386", or "HMACSHA2/512". + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + * @remarks Do not call this method. It is not supported. + */ + virtual result SetAlgorithm(const Tizen::Base::String& algorithm); + + /** + * Sets the secret key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Gets the HMAC with the specified input. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetHmacN(const Tizen::Base::ByteBuffer& input) const; + + /** + * Initializes a multiple-part HMAC operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part HMAC operation while processing another data part. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual result Update(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part HMAC operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Md5Hmac(const Md5Hmac& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Md5Hmac& operator =(const Md5Hmac& rhs); + +private: + hmac_ctx_st* __pMd5HmacCtx; + Tizen::Base::ByteBuffer __keyBytes; + + class _Md5HmacImpl* __pMd5HmacImpl; + friend class _Md5HmacImpl; + +}; //Md5Hmac + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_MD5_HMAC_H_ diff --git a/inc/FSecCryptoRc2Cipher.h b/inc/FSecCryptoRc2Cipher.h new file mode 100644 index 0000000..9777402 --- /dev/null +++ b/inc/FSecCryptoRc2Cipher.h @@ -0,0 +1,271 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoRc2Cipher.h + * @brief This is the header file for the %Rc2Cipher class. + * + * This header file contains the declarations of the %Rc2Cipher class. + */ +#ifndef _FSEC_CRYPTO_RC2_CIPHER_H_ +#define _FSEC_CRYPTO_RC2_CIPHER_H_ + +#include + +struct evp_cipher_st; + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SymmetricCipher; +/** + * @class Rc2Cipher + * @brief This class provides methods for encryption and decryption using the RC2 algorithm. + * + * @since 2.0 + * + * The %Rc2Cipher class provides a symmetric cipher using the RC2 algorithm. + * It sets appropriate values for the requested mode/key bit/padding scheme and cipher operation (CIPHER_ENCRYPT or CIPHER_DECRYPT) parameters. @n + * + * For more information on the class features, see Ciphers. + * + * @see ISymmetricCipher + * @see DesCipher + * @see DesEdeCipher + */ +class _OSP_EXPORT_ Rc2Cipher + : public virtual ISymmetricCipher + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + Rc2Cipher(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Rc2Cipher(void); + + /** + * Constructs and initializes this instance of %Rc2Cipher with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] transformation The name of the requested mode/padding scheme @n + * The RC2 support variable length key ranges from 8 bits to 128 bits, in steps of 8 bits. + * The key bits are not required to be mentioned in the transformation. + * There are four valid transformations for RC2, "CBC/NOPADDING", + * "CBC/PKCS7PADDING", "ECB/PKCS7PADDING", and "ECB/NOPADDING". + * @param[in] opMode The cipher operation mode @n + * The valid values for %Rc2Cipher are @c CIPHER_ENCRYPT and @c CIPHER_DECRYPT. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c opMode does not contain a valid value for the cipher operation. + * @remarks If @c opMode is not matching the actual operation, the result of the operation is @c null and an exception is returned. @n + * For example, if @c opMode is set to @c CIPHER_ENCRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP and the DecryptN() method is used, then the result obtained is @c null and an exception is returned. + */ + virtual result Construct(const Tizen::Base::String& transformation, enum CipherOperation opMode); + + /** + * Sets a symmetric key for encryption or decryption. @n + * The variable length key ranges from 8 bits to 128 bits, in steps of 8 bits. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Sets the initial vector. + * + * @since 2.0 + * + * @return An error code + * @param[in] initialVector The initial vector + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector); + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Initializes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + + /** + * Wraps a key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] secretKey The secret key to wrap + * @remarks This operation is not supported in the %Rc2Cipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey); + + /** + * Unwraps a previously wrapped key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] wrappedKey The wrapped key to unwrap + * @remarks This operation is not supported in the %Rc2Cipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Rc2Cipher(const Rc2Cipher& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Rc2Cipher& operator =(const Rc2Cipher& rhs); + +private: + _SymmetricCipher* __pSymmetricCipher; + const evp_cipher_st* __pCipherAlgorithm; + Tizen::Base::String __cipherAlgorithm; + + class _Rc2CipherImpl* __pRc2CipherImpl; + friend class _Rc2CipherImpl; + +}; //Rc2Cipher + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_RC2_CIPHER_H_ diff --git a/inc/FSecCryptoRc4Cipher.h b/inc/FSecCryptoRc4Cipher.h new file mode 100644 index 0000000..5d3d873 --- /dev/null +++ b/inc/FSecCryptoRc4Cipher.h @@ -0,0 +1,269 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoRc4Cipher.h + * @brief This is the header file for the %Rc4Cipher class. + * + * This header file contains the declarations of the %Rc4Cipher class. + */ +#ifndef _FSEC_CRYPTO_RC4_CIPHER_H_ +#define _FSEC_CRYPTO_RC4_CIPHER_H_ + +#include + +struct evp_cipher_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SymmetricCipher; +/** + * @class Rc4Cipher + * @brief This class provides methods for encryption and decryption operations using the RC4 algorithm. + * + * @since 2.0 + * + * The %Rc4Cipher class provides a symmetric cipher using the RC4 algorithm. + * It sets appropriate values for the requested mode/key bit/padding scheme and cipher operation (CIPHER_ENCRYPT or CIPHER_DECRYPT) parameters. @n + * + * For more information on the class features, see Ciphers. + * + * @see ISymmetricCipher + * @see DesCipher + * @see DesEdeCipher + */ +class _OSP_EXPORT_ Rc4Cipher + : public virtual ISymmetricCipher + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + Rc4Cipher(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Rc4Cipher(void); + + /** + * Constructs and initializes an instance of %Rc4Cipher with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] transformation The only valid value for %Rc4Cipher for transformation is "NONE" + * @param[in] opMode The cipher operation mode @n + * The valid values for %Rc4Cipher are @c CIPHER_ENCRYPT and @c CIPHER_DECRYPT. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @remarks If @c opMode is not matching the actual operation, the result of the operation is @c null and an exception is returned. @n + * For example, if @c opMode is set to @c CIPHER_ENCRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP and the DecryptN() method is used, then the result obtained is @c null and an exception is returned. + */ + virtual result Construct(const Tizen::Base::String& transformation, enum CipherOperation opMode); + + /** + * Sets a symmetric key for encryption or decryption operation. @n + * The variable length key ranges from 40 bits to 256 bits, in steps of 8 bits. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Sets the initial vector. + * + * @since 2.0 + * + * @return An error code + * @param[in] initialVector The initial vector + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector); + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Initializes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input); + + + /** + * Finalizes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks This operation is not required for RC4. Always return @c null if this method is called. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + + /** + * Wraps a key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] secretKey The secret key to wrap + * @remarks This operation is not supported in the %Rc4Cipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey); + + /** + * Unwraps a previously wrapped key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] wrappedKey The wrapped key to unwrap + * @remarks This operation is not supported in the %Rc4Cipher class. + * Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Rc4Cipher(const Rc4Cipher& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Rc4Cipher& operator =(const Rc4Cipher& rhs); + +private: + _SymmetricCipher* __pSymmetricCipher; + const evp_cipher_st* __pCipherAlgorithm; + Tizen::Base::String __cipherAlgorithm; + + class _Rc4CipherImpl* __pRc4CipherImpl; + friend class _Rc4CipherImpl; + +}; // Rc4Cipher + +} } } // Tizen::Security::Crypto + +#endif // _FSEC_CRYPTO_RC4_CIPHER_H_ diff --git a/inc/FSecCryptoRsaCipher.h b/inc/FSecCryptoRsaCipher.h new file mode 100644 index 0000000..42d0800 --- /dev/null +++ b/inc/FSecCryptoRsaCipher.h @@ -0,0 +1,166 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoRsaCipher.h + * @brief This is the header file for the %RsaCipher class. + * + * This header file contains the declarations of the %RsaCipher class. + */ +#ifndef _FSEC_CRYPTO_RSA_CIPHER_H_ +#define _FSEC_CRYPTO_RSA_CIPHER_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class RsaCipher + * @brief This class provides methods for encryption and decryption using the Rivest Shamir Adleman (RSA) algorithm. + * + * @since 2.0 + * + * The %RsaCipher class provides methods to encrypt and decrypt messages, and is used in the asymmetric cipher + * operations. @n + * + * For more information on using the Rivest Shamir Adleman (RSA) algorithm for asymmetric ciphers, see Ciphers. + * + * @see Tizen::Security::KeyPair + * @see Tizen::Security::IPublicKey + * @see Tizen::Security::IPrivateKey + */ +class _OSP_EXPORT_ RsaCipher + : public virtual IAsymmetricCipher + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + RsaCipher(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~RsaCipher(void); + + /** + * Sets an asymmetric private key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of IKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetPrivateKey(const Tizen::Security::IKey& key); + + /** + * Sets an asymmetric public key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of IKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetPublicKey(const Tizen::Security::IKey& key); + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + RsaCipher(const RsaCipher& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + RsaCipher& operator =(const RsaCipher& rhs); + +private: + Tizen::Base::ByteBuffer __privateKey; + Tizen::Base::ByteBuffer __publicKey; + + class _RsaCipherImpl* __pRsaCipherImpl; + friend class _RsaCipherImpl; + +}; //RsaCipher + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_RSA_CIPHER_H_ diff --git a/inc/FSecCryptoRsaSignature.h b/inc/FSecCryptoRsaSignature.h new file mode 100644 index 0000000..09c9db0 --- /dev/null +++ b/inc/FSecCryptoRsaSignature.h @@ -0,0 +1,165 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoRsaSignature.h + * @brief This is the header file for the %RsaSignature class. + * + * This header file contains the declarations of the %RsaSignature class. + */ +#ifndef _FSEC_CRYPTO_RSA_SIGNATURE_H_ +#define _FSEC_CRYPTO_RSA_SIGNATURE_H_ + +#include +#include + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class RsaSignature + * @brief This class implements the Rivest Shamir Adleman (RSA) signatures. + * + * @since 2.0 + * + * The %RsaSignature class implements the Rivest Shamir Adleman (RSA) signatures. @n + * + * For more information on the class features, see Ciphers. + * + * @see ISignature + * @see IKeyPairGenerator + * @see KeyPair + * @see IPublicKey + * @see IPrivateKey + * @see PublicKey + * @see PrivateKey + */ +class _OSP_EXPORT_ RsaSignature + : public virtual ISignature + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + RsaSignature(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~RsaSignature(void); + + /** + * Sets an asymmetric private key for signature. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of IKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetPrivateKey(const Tizen::Security::IKey& key); + + /** + * Sets an asymmetric public key for verification. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of IKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetPublicKey(const Tizen::Security::IKey& key); + + /** + * Signs the data. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* SignN(const Tizen::Base::ByteBuffer& input); + + /** + * Verifies the data. @n + * The verification is done by comparing the @c signedData to the signature created by the @c data. + * + * @since 2.0 + * + * @return @c true if the signed data is correct, @n + * else @c false + * @param[in] data An instance of Tizen::Base::ByteBuffer that contains the original data + * @param[in] signedData A instance of Tizen::Base::ByteBuffer that contains the signed data + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual bool Verify(const Tizen::Base::ByteBuffer& data, const Tizen::Base::ByteBuffer& signedData); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + RsaSignature(const RsaSignature& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + RsaSignature& operator =(const RsaSignature& rhs); + +private: + Tizen::Base::ByteBuffer __privateKey; + Tizen::Base::ByteBuffer __publicKey; + + class _RsaSignatureImpl* __pRsaSignatureImpl; + friend class _RsaSignatureImpl; + +}; //RsaSignature + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_RSA_SIGNATURE_H_ diff --git a/inc/FSecCryptoSha1Hash.h b/inc/FSecCryptoSha1Hash.h new file mode 100644 index 0000000..ad5dbd4 --- /dev/null +++ b/inc/FSecCryptoSha1Hash.h @@ -0,0 +1,174 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSha1Hash.h + * @brief This is the header file for the %Sha1Hash class. + * + * This header file contains the declarations of the %Sha1Hash class. + */ +#ifndef _FSEC_CRYPTO_SHA1_HASH_H_ +#define _FSEC_CRYPTO_SHA1_HASH_H_ + +#include + +struct env_md_ctx_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class Sha1Hash + * @brief This class implements the SHA-1 hash algorithm. + * + * @since 2.0 + * + * The %Sha1Hash class implements the SHA-1 hash algorithm. @n + * + * For more information on the class features, see Hashing. + * + * @see IHash + * @see Md5Hash + * @see Sha2Hash + */ +class _OSP_EXPORT_ Sha1Hash + : public virtual IHash + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Sha1Hash(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Sha1Hash(void); + + /** + * Sets the hash algorithm. @n + * The %SetAlgorithm() method is not supported by this class. Do not call this method. @n + * If this method is called, it returns @c E_UNSUPPORTED_ALGORITHM. + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the hash algorithm @n + * For example "SHA2/224", "SHA2/256", "SHA2/386", or "SHA2/512". + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + * @remarks Do not call this method. It is not supported. + */ + virtual result SetAlgorithm(const Tizen::Base::String& algorithm); + + /** + * Gets the hashes of a data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetHashN(const Tizen::Base::ByteBuffer& input) const; + + /** + * Initializes a multiple-part hash operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part hash operation while processing another data part. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual result Update(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part hash operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Sha1Hash(const Sha1Hash& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Sha1Hash& operator =(const Sha1Hash& rhs); + +private: + env_md_ctx_st* __pEvpMdCtx; + + class _Sha1HashImpl* __pSha1HashImpl; + friend class _Sha1HashImpl; + +}; //Sha1Hash + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_SHA1_HASH_H_ diff --git a/inc/FSecCryptoSha1Hmac.h b/inc/FSecCryptoSha1Hmac.h new file mode 100644 index 0000000..a22bcee --- /dev/null +++ b/inc/FSecCryptoSha1Hmac.h @@ -0,0 +1,189 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSha1Hmac.h + * @brief This is the header file for the %Sha1Hmac class. + * + * This header file contains the declarations of the %Sha1Hmac class. + */ +#ifndef _FSEC_CRYPTO_SHA1_HMAC_H_ +#define _FSEC_CRYPTO_SHA1_HMAC_H_ + +#include + +struct hmac_ctx_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class Sha1Hmac + * @brief This class implements the SHA-1 HMAC algorithm. + * + * @since 2.0 + * + * The %Sha1Hmac class implements the SHA-1 HMAC algorithm. @n + * + * For more information on the class features, see Hashing. + * + * @see IHmac + * @see Md5Hmac + * @see Sha2Hmac + */ +class _OSP_EXPORT_ Sha1Hmac + : public virtual IHmac + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Sha1Hmac(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Sha1Hmac(void); + + /** + * Sets the HMAC algorithm. @n + * The %SetAlgorithm() method is not supported by this class. Do not call this method. + * If this method is called, it returns @c E_UNSUPPORTED_ALGORITHM. + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the HMAC algorithm @n + * For example, "HMACSHA2/224", "HMACSHA2/256", "HMACSHA2/386", or "HMACSHA2/512". + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + * @remarks Do not call this method. It is not supported. + */ + virtual result SetAlgorithm(const Tizen::Base::String& algorithm); + + /** + * Sets the secret key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Gets HMAC with the given input. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetHmacN(const Tizen::Base::ByteBuffer& input) const; + + /** + * Initializes a multiple-part HMAC operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part HMAC operation while processing another data part. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual result Update(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part HMAC operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Sha1Hmac(const Sha1Hmac& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Sha1Hmac& operator =(const Sha1Hmac& rhs); + +private: + hmac_ctx_st* __pSha1HmacCtx; + Tizen::Base::ByteBuffer __keyBytes; + + class _Sha1HmacImpl* __pSha1HmacImpl; + friend class _Sha1HmacImpl; + +}; //Sha1Hmac + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_SHA1_HMAC_H_ diff --git a/inc/FSecCryptoSha2Hash.h b/inc/FSecCryptoSha2Hash.h new file mode 100644 index 0000000..6075888 --- /dev/null +++ b/inc/FSecCryptoSha2Hash.h @@ -0,0 +1,172 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSha2Hash.h + * @brief This is the header file for the %Sha2Hash class. + * + * This header file contains the declarations of the %Sha2Hash class. + */ +#ifndef _FSEC_CRYPTO_SHA2_HASH_H_ +#define _FSEC_CRYPTO_SHA2_HASH_H_ + +#include + +struct env_md_st; +struct env_md_ctx_st; + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class Sha2Hash + * @brief This class implements the SHA-2 hash algorithm. + * + * @since 2.0 + * + * The %Sha2Hash class implements the SHA-2 hash algorithm. @n + * + * For more information on the class features, see Hashing. + * + * @see Tizen::Security::Crypto::IHash + * @see Tizen::Security::Crypto::Md5Hash + * @see Tizen::Security::Crypto::Sha1Hash + */ +class _OSP_EXPORT_ Sha2Hash + : public virtual IHash + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Sha2Hash(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Sha2Hash(void); + + /** + * Sets the hash algorithm. + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the hash algorithm @n + * For example, "SHA2/224", "SHA2/256", "SHA2/386", or "SHA2/512". + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + */ + virtual result SetAlgorithm(const Tizen::Base::String& algorithm); + + /** + * Gets the hashes of the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetHashN(const Tizen::Base::ByteBuffer& input) const; + + /** + * Initializes the multiple-part hash operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part hash operation while processing another data part. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual result Update(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part hash operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Sha2Hash(const Sha2Hash& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Sha2Hash& operator =(const Sha2Hash& rhs); + +private: + const env_md_st* __pAlgorithm; + env_md_ctx_st* __pEvpMdCtx; + + class _Sha2HashImpl* __pSha2HashImpl; + friend class _Sha2HashImpl; + +}; //Sha2Hash + +} } } //Tizen::Security:Crypto + +#endif //_FSEC_CRYPTO_SHA2_HASH_H_ diff --git a/inc/FSecCryptoSha2Hmac.h b/inc/FSecCryptoSha2Hmac.h new file mode 100644 index 0000000..e9a181e --- /dev/null +++ b/inc/FSecCryptoSha2Hmac.h @@ -0,0 +1,188 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSha2Hmac.h + * @brief This is the header file for the %Sha2Hmac class. + * + * This header file contains the declarations of the %Sha2Hmac class. + */ +#ifndef _FSEC_CRYPTO_SHA2_HMAC_H_ +#define _FSEC_CRYPTO_SHA2_HMAC_H_ + +#include + +struct env_md_st; +struct hmac_ctx_st; + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @class Sha2Hmac + * @brief This class implements the SHA-2 HMAC algorithm. + * + * @since 2.0 + * + * The %Sha2Hmac class implements the SHA-2 HMAC algorithm. @n + * + * For more information on the class features, see Hashing. + * + * @see Tizen::Security::Crypto::IHmac + * @see Tizen::Security::Crypto::Md5Hmac + * @see Tizen::Security::Crypto::Sha1Hmac + */ +class _OSP_EXPORT_ Sha2Hmac + : public virtual IHmac + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Sha2Hmac(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Sha2Hmac(void); + + /** + * Sets the HMAC algorithm. + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the HMAC algorithm @n + * For example, "HMACSHA2/224", "HMACSHA2/256", "HMACSHA2/386", or "HMACSHA2/512". + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The algorithm is not supported. + */ + virtual result SetAlgorithm(const Tizen::Base::String& algorithm); + + /** + * Sets the secret key. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Gets the HMAC with the given input. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetHmacN(const Tizen::Base::ByteBuffer& input) const; + + /** + * Initializes the multiple-part HMAC operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part HMAC operation while processing another part of the data. + * + * @since 2.0 + * + * @return An error code + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + */ + virtual result Update(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part HMAC operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Sha2Hmac(const Sha2Hmac& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + Sha2Hmac& operator =(const Sha2Hmac& rhs); + +private: + hmac_ctx_st* __pSha2HmacCtx; + Tizen::Base::ByteBuffer __keyBytes; + const env_md_st* __pAlgorithm; + + class _Sha2HmacImpl* __pSha2HmacImpl; + friend class _Sha2HmacImpl; + +}; //Sha2Hmac + +} } } //Tizen::Security:Crypto + +#endif //_FSEC_CRYPTO_SHA2_HMAC_H_ diff --git a/inc/FSecCryptoSkipJackCipher.h b/inc/FSecCryptoSkipJackCipher.h new file mode 100644 index 0000000..cd933c7 --- /dev/null +++ b/inc/FSecCryptoSkipJackCipher.h @@ -0,0 +1,268 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSkipJackCipher.h + * @brief This is the header file for the %SkipJackCipher class. + * + * This header file contains the declarations of the %SkipJackCipher class. + */ +#ifndef _FSEC_CRYPTO_SKIPJACK_CIPHER_H_ +#define _FSEC_CRYPTO_SKIPJACK_CIPHER_H_ + +#include + +struct evp_cipher_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SymmetricCipher; +/** + * @class SkipJackCipher + * @brief This class provides methods for encryption and decryption using the Skipjack algorithm. + * + * @since 2.0 + * + * The %SkipJackCipher class provides a symmetric cipher using the Skipjack algorithm. Appropriate values have to be set for the requested mode or key bit or + * padding scheme and the cipher operation (CIPHER_ENCRYPT or CIPHER_DECRYPT) parameters. @n + * + * For more information on the class features, see Ciphers. + * + * @see ISymmetricCipher + * @see DesCipher + * @see DesEdeCipher + */ +class _OSP_EXPORT_ SkipJackCipher + : public virtual ISymmetricCipher + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + SkipJackCipher(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~SkipJackCipher(void); + + /** + * Constructs and initializes this instance of %SkipJackCipher with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] transformation The name of the requested mode or padding scheme @n + * As the default key size of the Skipjack cipher is 80 bits, there is no need to mention it explicitly. + * For example, "CBC/PKCS7PADDING" or "ECB/NOPADDING". + * @param[in] opMode The cipher operation mode @n + * The only valid values for %SkipJackCipher are @c CIPHER_ENCRYPT and @c CIPHER_DECRYPT. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c opMode contains invalid value for the cipher operation. + * @remarks If @c opMode is not matching the actual operation, the result of the operation is @c null and an exception is returned. @n + * For example, if @c opMode is set to @c CIPHER_ENCRYPT, @c CIPHER_WRAP, or @c CIPHER_UNWRAP and the DecryptN() method is used, then the result obtained is @c null and an exception is returned. + */ + + virtual result Construct(const Tizen::Base::String& transformation, enum CipherOperation opMode); + + /** + * Sets a symmetric key for encryption or decryption. + * + * @since 2.0 + * + * @return An error code + * @param[in] key An instance of ISecretKey + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified key is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetKey(const Tizen::Security::ISecretKey& key); + + /** + * Sets the initial vector. + * + * @since 2.0 + * + * @return An error code + * @param[in] initialVector The initial vector + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector); + + /** + * Encrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* EncryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Decrypts the data (single-part). + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The input Tizen::Base::ByteBuffer is empty or contains invalid data. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual Tizen::Base::ByteBuffer* DecryptN(const Tizen::Base::ByteBuffer& input); + + /** + * Initializes the multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_KEY_NOT_FOUND The specified key is not found. + * @exception E_INVALID_OPERATION The specified cipher operation mode for this method is invalid. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + * @remarks A secret key and an initial vector are set before calling this method. + */ + virtual result Initialize(void); + + /** + * Updates a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] input An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_INVALID_ARG The specified instance of Tizen::Base::ByteBuffer is invalid or empty. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input); + + /** + * Finalizes a multiple-part encryption or decryption operation. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OVERFLOW This operation has caused the memory to overflow. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or + * the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* FinalizeN(void); + + /** + * Wraps the specified key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] secretKey The secret key to wrap + * @remarks This operation is not supported in %SkipJackCipher. Therefore, this method always returns @c null. + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey); + + /** + * Unwraps the specified wrapped key. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] wrappedKey The wrapped key to unwrap + * @remarks This operation is not supported in %SkipJackCipher. Therefore, this method always returns @c null. @n + * @remarks The @c E_UNSUPPORTED_ALGORITHM exception is returned using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + SkipJackCipher(const SkipJackCipher& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + SkipJackCipher& operator =(const SkipJackCipher& rhs); + +private: + _SymmetricCipher* __pSymmetricCipher; + const evp_cipher_st* __pCipherAlgorithm; + Tizen::Base::String __cipherAlgorithm; + + class _SkipJackCipherImpl* __pSkipJackCipherImpl; + friend class _SkipJackCipherImpl; + +}; //SkipJackCipher + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_SKIPJACK_CIPHER_H_ diff --git a/inc/FSecCryptoTypes.h b/inc/FSecCryptoTypes.h new file mode 100644 index 0000000..797ac11 --- /dev/null +++ b/inc/FSecCryptoTypes.h @@ -0,0 +1,72 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoTypes.h + * @brief This is the header file that defines the different enumerations. + * + * This is the header file that defines the different enumerations that can be used for cryptography. + */ +#ifndef _FSEC_CRYPTO_TYPES_H_ +#define _FSEC_CRYPTO_TYPES_H_ + + +namespace Tizen { namespace Security { namespace Crypto +{ + +/** + * @enum CipherOperation + * + * Defines the cipher operation. + * + * @since 2.0 + */ + +enum CipherOperation +{ + CIPHER_ENCRYPT = 0, /** + + +namespace Tizen { namespace Security +{ + +/** + * @class DesEdeSecureRandom + * @brief This class provides a secure random object with the Data Encryption Standard in the Encrypt-Decrypt-Encrypt (DES-EDE) mode. + * + * @since 2.0 + * + * The %DesEdeSecureRandom class generates a secure random object to deterministically seed cryptographic algorithms. The Data Encryption Standard (DES) + * method generates user-defined number of random bytes in the Encrypt-Decrypt-Encrypt mode. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see ISecureRandom + * @see AesSecureRandom + * @see DesSecureRandom + */ +class _OSP_EXPORT_ DesEdeSecureRandom + : public virtual ISecureRandom + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + DesEdeSecureRandom(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DesEdeSecureRandom(void); + + /** + * Generates a user-defined number of random bytes. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @param[in] numBytes The number of random bytes to generate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c numBytes is @c 0 or negative. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or the Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* GenerateRandomBytesN(int numBytes); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DesEdeSecureRandom(const DesEdeSecureRandom& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DesEdeSecureRandom& operator =(const DesEdeSecureRandom& rhs); + +private: + class _DesEdeSecureRandomImpl* __pDesEdeSecureRandomImpl; + friend class _DesEdeSecureRandomImpl; + +}; //DesEdeSecureRandom + +} } //Tizen::Security + +#endif // _FSEC_DESEDE_SECURE_RANDOM_H_ diff --git a/inc/FSecDesSecureRandom.h b/inc/FSecDesSecureRandom.h new file mode 100644 index 0000000..7ee4bee --- /dev/null +++ b/inc/FSecDesSecureRandom.h @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecDesSecureRandom.h + * @brief This is the header file for the %DesSecureRandom class. + * + * This header file contains the declarations of the %DesSecureRandom class. + */ +#ifndef _FSEC_DES_SECURE_RANDOM_H_ +#define _FSEC_DES_SECURE_RANDOM_H_ + +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class DesSecureRandom + * @brief This class provides a secure random object with Data Encryption Standard (DES) method. + * + * @since 2.0 + * + * The %DesSecureRandom class generates a secure random object that can be used to seed deterministic, cryptographic algorithms. + * The DES method generates a user-defined number of random bytes. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see ISecureRandom + * @see AesSecureRandom + * @see DesEdeSecureRandom + */ +class _OSP_EXPORT_ DesSecureRandom + : public virtual ISecureRandom + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + DesSecureRandom(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DesSecureRandom(void); + + /** + * Generates a user-specified number of random bytes. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class, @n + * else @c null if an error occurs + * @param[in] numBytes The number of random bytes to generate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c numBytes is @c 0 or negative. + * @exception E_SYSTEM A system error has occurred. @n + * The Tizen::Base::ByteBuffer operation has failed. + */ + virtual Tizen::Base::ByteBuffer* GenerateRandomBytesN(int numBytes); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DesSecureRandom(const DesSecureRandom& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DesSecureRandom& operator =(const DesSecureRandom& rhs); + +private: + class _DesSecureRandomImpl* __pDesSecureRandomImpl; + friend class _DesSecureRandomImpl; + +}; //DesSecureRandom + +} } //Tizen::Security + +#endif // _FSEC_DES_SECURE_RANDOM_H_ diff --git a/inc/FSecDhKeyParameters.h b/inc/FSecDhKeyParameters.h new file mode 100644 index 0000000..b92ec51 --- /dev/null +++ b/inc/FSecDhKeyParameters.h @@ -0,0 +1,187 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecDhKeyParameters.h + * @brief This is the header file for the %DhKeyParameters class. + * + * This header file contains the declarations of the %DhKeyParameters class. + */ +#ifndef _FSEC_DH_KEY_PARAMETERS_H_ +#define _FSEC_DH_KEY_PARAMETERS_H_ + +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class DhKeyParameters + * @brief This class provides methods for retrieving the parameters for the Diffie-Hellman (DH) algorithm. + * + * @since 2.0 + * + * The %DhKeyParameters class provides a subset of the domain parameters for the DH algorithm. + * For example, a prime number and a generator value are used to exchange keys between two parties. @n + * + * For more information on the class features, see Key exchanging. + * + * @see IKeyParameters + * + * The following example demonstrates how to use the %DhKeyParameters class. + * + * @code + * void GetParameterExample(void) + * { + * result r = E_SUCCESS; + * KeyPairGenerator *pKeyPairGen = null; + * IKeyParameters *pKeyParams = null; + * + * int size = 1024; + * int nResult = 0; + * ByteBuffer* pResult = null; + * + * // Generates the key. + * pKeyPairGen = new KeyPairGenerator(); + * if (null == pKeyPairGen) + * { + * goto CATCH; + * } + * + * r = pKeyPairGen->Construct(size, L"DH"); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pKeyParams = pKeyPairGen->GenerateKeyParametersN(); + * if (null == pKeyParams) + * { + * goto CATCH; + * } + * + * pResult = pKeyParams->GetParameterValueN(KEY_PARAMETER_DH_P); + * if (null == pResult) + * { + * goto CATCH; + * } + * + * nResult = pKeyParams->GetParameterSize(KEY_PARAMETER_DH_PRIVATE_KEY_SIZE); + * + * CATCH: + * delete pKeyPairGen; + * delete pResult; + * delete pKeyParams; + * + * } + * @endcode + */ + +class _OSP_EXPORT_ DhKeyParameters + : public IKeyParameters + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + DhKeyParameters(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~DhKeyParameters(void); + + /** + * Constructs and initializes this instance of IKeyParameters with the specified key parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] primeNumber The prime number 'p' to instantiate + * @param[in] generatorNumber The generator value 'g' to instantiate + * @param[in] privateKeySize The size of the private key to instantiate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const Tizen::Base::ByteBuffer& primeNumber, const Tizen::Base::ByteBuffer& generatorNumber, int privateKeySize); + + /** + * Gets the value of domain parameters (in Tizen::Base::ByteBuffer format) for the specified key parameter type. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the parameter values, @n + * else @c null if an error occurs + * @param[in] paramType The type of the parameter + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_TYPE The specified @c paramType is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetParameterValueN(KeyParameterType paramType) const; + + /** + * Gets the size of the private key component. + * + * @since 2.0 + * + * @return The size of the private key component + * @param[in] paramType The type of the parameter + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_TYPE The specified @c paramType is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetParameterSize(KeyParameterType paramType) const; + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DhKeyParameters(const DhKeyParameters& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + DhKeyParameters& operator =(const DhKeyParameters& rhs); + +private: + Tizen::Base::ByteBuffer __prime; + Tizen::Base::ByteBuffer __generator; + int __privateKeySize; + + class _DhKeyParametersImpl* __pDhKeyParametersImpl; + friend class _DhKeyParametersImpl; + +}; //DhKeyParameters + +} } //Tizen::Security + +#endif //_FSEC_DH_KEY_PARAMETERS_H_ diff --git a/inc/FSecIKey.h b/inc/FSecIKey.h new file mode 100644 index 0000000..7973719 --- /dev/null +++ b/inc/FSecIKey.h @@ -0,0 +1,110 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecIKey.h + * @brief This is the header file for the %IKey interface. + * + * This header file contains the declarations of the %IKey interface. + */ +#ifndef _FSEC_IKEY_H_ +#define _FSEC_IKEY_H_ + +#include + +namespace Tizen { namespace Security +{ + +/** + * @interface IKey + * @brief This interface provides methods that help in setting the buffer for the key. These methods also extract the encoding format of the key. + * + * @since 2.0 + * + * The %IKey interface provides methods that help in setting the buffer for the key. These methods also extract the encoding format of the key. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see Tizen::Security::IPrivateKey + * @see Tizen::Security::IPublicKey + * @see Tizen::Security::ISecretKey + * @see Tizen::Security::PrivateKey + * @see Tizen::Security::PublicKey + * @see Tizen::Security::SecretKey + */ +class _OSP_EXPORT_ IKey +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IKey(void){} + + /** + * Gets the name of the primary encoding format of the key. + * + * @since 2.0 + * + * @return The primary encoding format of the key + */ + virtual Tizen::Base::String GetFormat(void) const = 0; + + /** + * Gets the key in its primary encoding format. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedN(void) const = 0; + + /** + * Sets the key buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyBuffer An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keyBuffer is invalid. + */ + virtual result SetKey(const Tizen::Base::ByteBuffer& keyBuffer) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IKey_Reserved1(void) {} + +}; //IKey + +} } //Tizen::Security + +#endif // _FSEC_IKEY_H_ diff --git a/inc/FSecIKeyPairGenerator.h b/inc/FSecIKeyPairGenerator.h new file mode 100644 index 0000000..22439fb --- /dev/null +++ b/inc/FSecIKeyPairGenerator.h @@ -0,0 +1,103 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecIKeyPairGenerator.h + * @brief This is the header file for the %IKeyPairGenerator interface. + * + * This header file contains the declarations of the %IKeyPairGenerator interface. + */ +#ifndef _FSEC_IKEY_PAIR_GENERATOR_H_ +#define _FSEC_IKEY_PAIR_GENERATOR_H_ + +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @interface IKeyPairGenerator + * @brief This interface provides the abstract methods for generating a pair of public and private keys. + * + * @since 2.0 + * + * The %IKeyPairGenerator interface provides the abstract methods for generating a pair of public and private keys. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see Tizen::Security::KeyPair + */ +class _OSP_EXPORT_ IKeyPairGenerator +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IKeyPairGenerator(void){} + + /** + * Constructs and initializes an instance of %IKeyPairGenerator with the specified modulus size. + * + * @since 2.0 + * + * @return An error code + * @param[in] modulusBitSize The modulus size in bits + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c modulusBitSize is invalid. @n + * The modulus size must be atleast greater than or equal to @c 1024 bits @n + * to generate cryptographically secure keys. + */ + virtual result Construct(int modulusBitSize) = 0; + + /** + * Generates a new key pair. + * + * @since 2.0 + * + * @return A pointer to the KeyPair class, @n + * else @c null if the method fails to generate the key pair + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The requested algorithm is not supported. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::KeyPair* GenerateKeyPairN(void) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IKeyPairGenerator_Reserved1(void) {} + +}; //IKeyPairGenerator + +} } //Tizen::Security + +#endif // _FSEC_IKEY_PAIR_GENERATOR_H_ diff --git a/inc/FSecIKeyParameters.h b/inc/FSecIKeyParameters.h new file mode 100644 index 0000000..3df274f --- /dev/null +++ b/inc/FSecIKeyParameters.h @@ -0,0 +1,114 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecIKeyParameters.h + * @brief This is the header file for the %IKeyParameters interface. + * + * This header file contains the declarations of the %IKeyParameters interface. + */ +#ifndef _FSEC_CRYPTO_IKEY_PARAMETERS_H_ +#define _FSEC_CRYPTO_IKEY_PARAMETERS_H_ + +#include +#include + +namespace Tizen { namespace Security +{ + +/** + * @interface IKeyParameters + * @brief This interface provides the abstract methods for retrieving the parameters of the key exchange algorithms. + * + * @since 2.0 + * + * The %IKeyParameters interface provides the abstract methods for retrieving the parameters of the key exchange algorithms. @n + * + * For more information on the class features, see Key exchanging. + * + * @see Tizen::Security::KeyPair + */ +class _OSP_EXPORT_ IKeyParameters +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IKeyParameters(void) {} + + /** + * Gets the value of the parameter for a specified key parameter type. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the parameter values, @n + * else @c null if an error occurs + * @param[in] paramType The type of the parameter @n + * For example, @c KEY_PARAMETER_DH_G. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_TYPE The specified @c paramType is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetParameterValueN(KeyParameterType paramType) const = 0; + + /** + * Gets the size of the key parameter in bits for the specified key parameter type. + * + * @since 2.0 + * + * @return The size of the parameter, @n + * else @c 0 if an error occurs + * @param[in] keyParameterType The type of the parameter @n + * For example, @c PRIVATE_KEY_SIZE. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_TYPE The specified @c paramType is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetParameterSize(KeyParameterType keyParameterType) const = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IKeyParameters_Reserved1(void) {} + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IKeyParameters_Reserved2(void) {} + +}; //IKeyParameters + +} } //Tizen::Security + +#endif //_FSEC_CRYPTO_IKEY_PAIR_PARAMETERS_H_ diff --git a/inc/FSecIPrivateKey.h b/inc/FSecIPrivateKey.h new file mode 100644 index 0000000..b0649a4 --- /dev/null +++ b/inc/FSecIPrivateKey.h @@ -0,0 +1,106 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecIPrivateKey.h + * @brief This is the header file for the %IPrivateKey interface. + * + * This header file contains the declarations of the %IPrivateKey interface. + */ +#ifndef _FSEC_IPRIVATE_KEY_H_ +#define _FSEC_IPRIVATE_KEY_H_ + +#include + + +namespace Tizen { namespace Security +{ + +/** + * @interface IPrivateKey + * @brief This interface provides the functionality shared by all the private key instances. + * + * @since 2.0 + * + * The %IPrivateKey interface provides the functionality shared by all the private key instances. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + */ +class _OSP_EXPORT_ IPrivateKey + : public virtual IKey +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IPrivateKey(void){} + + /** + * Gets the name of the primary encoding format of a key. + * + * @since 2.0 + * + * @return The primary encoding format of a key + */ + virtual Tizen::Base::String GetFormat(void) const = 0; + + /** + * Gets a private key in its primary encoding format. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedN(void) const = 0; + + /** + * Sets the private key buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyBuffer An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keyBuffer is invalid. + */ + virtual result SetKey(const Tizen::Base::ByteBuffer& keyBuffer) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IPrivateKey_Reserved1(void) {} + +}; //IPrivateKey + +} } //Tizen::Security + +#endif //_FSEC_IPRIVATE_KEY_H_ diff --git a/inc/FSecIPublicKey.h b/inc/FSecIPublicKey.h new file mode 100644 index 0000000..739d07e --- /dev/null +++ b/inc/FSecIPublicKey.h @@ -0,0 +1,106 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecIPublicKey.h + * @brief This is the header file for the %IPublicKey interface. + * + * This header file contains the declarations of the %IPublicKey interface. + */ +#ifndef _FSEC_IPUBLIC_KEY_H_ +#define _FSEC_IPUBLIC_KEY_H_ + +#include + + +namespace Tizen { namespace Security +{ + +/** + * @interface IPublicKey + * @brief This interface provides the functionality shared by all the public key instances. + * + * @since 2.0 + * + * The %IPublicKey interface provides the functionality shared by all the public key instances. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + */ +class _OSP_EXPORT_ IPublicKey + : public virtual IKey +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IPublicKey(void){} + + /** + * Gets the name of the primary encoding format of a key. + * + * @since 2.0 + * + * @return The primary encoding format of a key + */ + virtual Tizen::Base::String GetFormat(void) const = 0; + + /** + * Gets a public key in its primary encoding format. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedN(void) const = 0; + + /** + * Sets the public key buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyBuffer An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keyBuffer is invalid. + */ + virtual result SetKey(const Tizen::Base::ByteBuffer& keyBuffer) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IPublicKey_Reserved1(void) {} + +}; //IPublicKey + +} } //Tizen::Security + +#endif //_FSEC_IPUBLIC_KEY_H_ diff --git a/inc/FSecISecretKey.h b/inc/FSecISecretKey.h new file mode 100644 index 0000000..d6b0601 --- /dev/null +++ b/inc/FSecISecretKey.h @@ -0,0 +1,106 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecISecretKey.h + * @brief This is the header file for the %ISecretKey interface. + * + * This header file contains the declarations of the %ISecretKey interface. + */ +#ifndef _FSEC_ISECRET_KEY_H_ +#define _FSEC_ISECRET_KEY_H_ + +#include + + +namespace Tizen { namespace Security +{ + +/** + * @interface ISecretKey + * @brief This interface provides methods that help in setting the buffer for the key. These methods also extract the encoding format of the key. + * + * @since 2.0 + * + * The %ISecretKey interface provides methods that help in setting the buffer for the key. These methods also extract the encoding format of the key. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + */ +class _OSP_EXPORT_ ISecretKey + : public virtual IKey +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISecretKey(void){} + + /** + * Gets the name of the primary encoding format of this key. + * + * @since 2.0 + * + * @return The primary encoding format of the key + */ + virtual Tizen::Base::String GetFormat(void) const = 0; + + /** + * Gets the secret key in its primary encoding format. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the output, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedN(void) const = 0; + + /** + * Sets the secret key buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyBuffer An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keyBuffer is invalid. + */ + virtual result SetKey(const Tizen::Base::ByteBuffer& keyBuffer) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISecretKey_Reserved1(void) {} + +}; //ISecretKey + +} } //Tizen::Security + +#endif //_FSEC_ISECRET_KEY_H_ diff --git a/inc/FSecISecretKeyGenerator.h b/inc/FSecISecretKeyGenerator.h new file mode 100644 index 0000000..40bb416 --- /dev/null +++ b/inc/FSecISecretKeyGenerator.h @@ -0,0 +1,89 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecISecretKeyGenerator.h + * @brief This is the header file for the %ISecretKeyGenerator interface. + * + * This header file contains the declarations of the %ISecretKeyGenerator interface. + */ +#ifndef _FSEC_ISECRET_KEY_GENERATOR_H_ +#define _FSEC_ISECRET_KEY_GENERATOR_H_ + +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @interface ISecretKeyGenerator + * @brief This interface provides the abstract methods for generating a secret (symmetric) key. + * + * @since 2.0 + * + * The %ISecretKeyGenerator interface provides the abstract methods for generating a secret (symmetric) key. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see Tizen::Security::ISecretKey + */ +class _OSP_EXPORT_ ISecretKeyGenerator +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISecretKeyGenerator(void) {} + + /** + * Generates a new secret key. + * + * @since 2.0 + * + * @return A pointer to the ISecretKey interface, @n + * else @c null if the secret key generation fails + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::ISecretKey* GenerateKeyN(void) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISecretKeyGenerator_Reserved1(void) {} + + +}; //ISecretKeyGenerator + +} } //Tizen::Security + +#endif // _FSEC_ISECRET_KEY_GENERATOR_H_ diff --git a/inc/FSecISecureRandom.h b/inc/FSecISecureRandom.h new file mode 100644 index 0000000..136a3b7 --- /dev/null +++ b/inc/FSecISecureRandom.h @@ -0,0 +1,92 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecISecureRandom.h + * @brief This is the header file for the %ISecureRandom interface. + * + * This header file contains the declarations of the %ISecureRandom interface. + */ +#ifndef _FSEC_ISECURE_RANDOM_H_ +#define _FSEC_ISECURE_RANDOM_H_ + +#include +#include + +namespace Tizen { namespace Security +{ + +/** + * @interface ISecureRandom + * @brief This interface provides the abstract methods for generating a secure random object. + * + * @since 2.0 + * + * The %ISecureRandom interface provides the abstract methods for generating a secure random object. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see Tizen::Security::AesSecureRandom + * @see Tizen::Security::DesSecureRandom + * @see Tizen::Security::DesEdeSecureRandom + */ +class _OSP_EXPORT_ ISecureRandom +{ + +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes @n + * are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISecureRandom(void) {} + + /** + * Generates a user-specified number of random bytes. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class, @n + * else @c null if an error occurs + * @param[in] numBytes The number of random bytes to generate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c numBytes is @c 0 or negative. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + + */ + virtual Tizen::Base::ByteBuffer* GenerateRandomBytesN(int numBytes) = 0; + +protected: + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void ISecureRandom_Reserved1(void) {} + +}; //ISecureRandom + +} } //Tizen::Security + +#endif // _FSEC_ISECURE_RANDOM_H_ diff --git a/inc/FSecKeaKeyParameters.h b/inc/FSecKeaKeyParameters.h new file mode 100644 index 0000000..053cb79 --- /dev/null +++ b/inc/FSecKeaKeyParameters.h @@ -0,0 +1,194 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecKeaKeyParameters.h + * @brief This is the header file for the %KeaKeyParameters class. + * + * This header file contains the declarations of the %KeaKeyParameters class. + */ +#ifndef _FSEC_KEA_KEY_PARAMETERS_H_ +#define _FSEC_KEA_KEY_PARAMETERS_H_ + +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class KeaKeyParameters + * @brief This class provides parameters for a Key Exchange mechanism using the KEA algorithm. + * + * @since 2.0 + * + * The %KeaKeyParameters class provides a subset of domain parameters for the KEA algorithm. + * For example, a prime number and a generator value are used to exchange keys between the two parties. @n + * + * For more information on the class features, see Key exchanging. + * + * @see IKeyParameters + * + * The following example demonstrates how to use the %KeaKeyParameters class. + * + * @code + * void GetParameterExample(void) + * { + * result r = E_SUCCESS; + * KeyPairGenerator *pKeyPairGen = null; + * IKeyParameters *pKeyParams = null; + * + * int size = 1024; + * int nResult = 0; + * ByteBuffer* pResult = null; + * + * // Generates the key. + * pKeyPairGen = new KeyPairGenerator(); + * if (null == pKeyPairGen) + * { + * goto CATCH; + * } + * + * r = pKeyPairGen->Construct(size, "KEA"); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * pKeyParams = pKeyPairGen->GenerateKeyParametersN(); + * if (null == pKeyParams) + * { + * goto CATCH; + * } + * + * pResult = pKeyParams->GetParameterValueN(KEY_PARAMETER_KEA_P); + * if (null == pResult) + * { + * goto CATCH; + * } + * + * nResult = pKeyParams->GetParameterSize(KEY_PARAMETER_KEA_PRIVATE_KEY_SIZE); + * + * CATCH: + * delete pKeyPairGen; + * delete pResult; + * delete pKeyParams; + * + * } + * @endcode + */ + +class _OSP_EXPORT_ KeaKeyParameters + : public IKeyParameters + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + KeaKeyParameters(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~KeaKeyParameters(void); + + /** + * Constructs and initializes an instance of %KeaKeyParameters with the specified key parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] primeNumber The prime number to instantiate + * @param[in] generatorNumber The generator value to instantiate + * @param[in] privateKeySize The size of the private key to instantiate + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * + */ + result Construct(const Tizen::Base::ByteBuffer& primeNumber, const Tizen::Base::ByteBuffer& generatorNumber, int privateKeySize); + + /** + * Gets the Tizen::Base::ByteBuffer value of parameters for the specified key parameter type. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class that contains the parameter values, @n + * else @c null if an error occurs + * @param[in] paramType The parameter type @n + * For example, @c KEY_PARAMETER_KEA_P. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_UNSUPPORTED_TYPE The specified @c paramType is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetParameterValueN(KeyParameterType paramType) const; + + /** + * Gets the size of the private key component. + * + * @since 2.0 + * + * @return The size of the private key component + * @param[in] paramType The parameter type @n + * For example, @c KEY_PARAMETER_PRIVATE_KEY_SIZE. + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_TYPE The specified @c paramType is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetParameterSize(KeyParameterType paramType) const; + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + KeaKeyParameters(const KeaKeyParameters& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + KeaKeyParameters& operator =(const KeaKeyParameters& rhs); + +private: + Tizen::Base::ByteBuffer __prime; + Tizen::Base::ByteBuffer __generator; + int __privateKeySize; + + class _KeaKeyParametersImpl* __pKeaKeyParametersImpl; + friend class _KeaKeyParametersImpl; + +}; //KeaKeyParameter + +} } //Tizen::Security + +#endif //_FSEC_KEA_KEY_EXCHANGE_PARAMS_H diff --git a/inc/FSecKeyPair.h b/inc/FSecKeyPair.h new file mode 100644 index 0000000..4361921 --- /dev/null +++ b/inc/FSecKeyPair.h @@ -0,0 +1,157 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecKeyPair.h + * @brief This is the header file for the %KeyPair class. + * + * This header file contains the declarations of the %KeyPair class. + */ +#ifndef _FSEC_KEY_PAIR_H_ +#define _FSEC_KEY_PAIR_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class KeyPair + * @brief This class is a simple holder for a key pair (a public and a private key). + * + * @since 2.0 + * + * The %KeyPair class manages a pair of keys comprising of a public and a private key, which are used in asymmetric ciphers. The key pairs are mainly used to encrypt messages and provide digital signatures. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see IKeyPairGenerator + * @see Tizen::Security::IPublicKey + * @see Tizen::Security::IPrivateKey + */ +class _OSP_EXPORT_ KeyPair + : public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + KeyPair(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~KeyPair(void); + + /** + * Constructs and initializes the current instance of %KeyPair with the specified public and private keys. + * + * @since 2.0 + * + * @return An error code + * @param[in] publicKey An instance of IPublicKey + * @param[in] privateKey An instance of IPrivateKey + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c publicKey or @c privateKey is invalid. + */ + result Construct(Tizen::Security::IPublicKey& publicKey, Tizen::Security::IPrivateKey& privateKey); + + /** + * Gets the public key component of the current instance of %KeyPair. + * + * @since 2.0 + * + * @return A pointer to IPublicKey + */ + Tizen::Security::IPublicKey* GetPublicKey(void) const; + + /** + * Gets the private key component of the current instance of %KeyPair. + * + * @since 2.0 + * + * @return A pointer to IPrivateKey + */ + Tizen::Security::IPrivateKey* GetPrivateKey(void) const; + + /** + * Sets the public key. + * + * @since 2.0 + * + * @return An error code + * @param[in] pubKey An instance of Tizen::Base::ByteBuffer that contains the public key + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c pubKey is invalid. + * @remarks Only ASN.1 encoding format is supported for input buffer. + */ + result SetPublicKey(const Tizen::Base::ByteBuffer& pubKey); + + /** + * Sets the private key. + * + * @since 2.0 + * + * @return An error code + * @param[in] privKey An instance of Tizen::Base::ByteBuffer that contains the private key + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c privKey is invalid. + * @remarks Only ASN.1 encoding format is supported for input buffer. + */ + result SetPrivateKey(const Tizen::Base::ByteBuffer& privKey); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + KeyPair(const KeyPair& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + KeyPair& operator =(const KeyPair& rhs); + +private: + Tizen::Security::IPublicKey* __pPubKey; + Tizen::Security::IPrivateKey* __pPriKey; + + class _KeyPairImpl* __pKeyPairImpl; + friend class _KeyPairImpl; + +}; //KeyPair + +} } //Tizen::Security + +#endif // _FSEC_KEY_PAIR_H_ diff --git a/inc/FSecKeyPairGenerator.h b/inc/FSecKeyPairGenerator.h new file mode 100644 index 0000000..c3ad392 --- /dev/null +++ b/inc/FSecKeyPairGenerator.h @@ -0,0 +1,191 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecKeyPairGenerator.h + * @brief This is the header file for the %KeyPairGenerator class. + * + * This header file contains the declarations of the %KeyPairGenerator class. + */ +#ifndef _FSEC_KEY_PAIR_GENERATOR_H_ +#define _FSEC_KEY_PAIR_GENERATOR_H_ + +#include +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class KeyPairGenerator + * @brief This class provides a pair of public and private keys for the Public key algorithm. + * + * @since 2.0 + * + * The %KeyPairGenerator class generates a key pair and its parameters that consists of a public and private key. These are used in asymmetric ciphers. The generated key pair and parameters are based on the underlying key pair encryption algorithm. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see Tizen::Security::IKeyPairGenerator + * @see Tizen::Security::KeyPair + */ +class _OSP_EXPORT_ KeyPairGenerator + : public virtual IKeyPairGenerator + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + KeyPairGenerator(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~KeyPairGenerator(void); + + /** + * Constructs and initializes an instance of %KeyPairGenerator with the specified parameter. + * + * @since 2.0 + * + * @return An error code + * @param[in] modulusBitSize The modulus size in bits + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified size is invalid. @n + * The modulus size must be at least greater than or equal to @c 1024 bits @n + * to generate cryptographically secure keys. + */ + virtual result Construct(int modulusBitSize); + + /** + * Constructs and initializes an instance of %KeyPairGenerator with the specified parameters. + * + * @since 2.0 + * + * @return An error code + * @param[in] modulusBitSize The modulus size in bits @n + * This is used for key generation. + * @param[in] algorithm The algorithm used to generate the key parameters @n + * The supported algorithms are RSA, DH, and KEA. The default value is RSA. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified size is invalid. @n + * @exception E_UNSUPPORTED_ALGORITHM The requested @c algorithm is not supported. @n + * The modulus size must be at least greater than or equal to @c 1024 bits @n + * to generate cryptographically secure keys. + */ + result Construct(int modulusBitSize, const Tizen::Base::String algorithm); + + /** + * Generates the key parameters based on the underlying key pair algorithm. @n + * For example, in case of the DH or KEA algorithm, this method generates key parameters based on the DSA + * algorithm (X186.3 specification). + * The supported algorithms are RSA, DH, and KEA. + * The generated key parameters may be required to create a key pair. The RSA algorithm + * does not call this method to generate a key pair. + * + * @since 2.0 + * + * @return A pointer to the IKeyParameters class that contains a subset of the domain parameters ('p' prime + * number, 'g' generator) that are used to generate a key pair, @n + * else @c null if the method fails to create the key parameters + * @param[in] lInBits The size of 'p', a prime number in bits @n + * The size must be @c 1024 bits, @c 2048 bits, or @c 3072 bits. + * @param[in] nInBits The size of 'g', a generator value in bits @n + * The size must be: + * - 160 bits, when @c lInBits is @c 1024 bits. + * - 254 or 256 bits, when @c lInBits is @c 2048 bits. + * - 256 bits, when @c lInBits is @c 3072 bits. + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The requested algorithm is not supported. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Security::IKeyParameters* GenerateKeyParametersN(int lInBits = 1024, int nInBits = 160) const; + + /** + * Generates a new key pair. + * + * @since 2.0 + * + * @return A pointer to the KeyPair class, @n + * else @c null if the method fails to create the key pair + * @param[in] pKeyParams The domain parameters of the key exchange algorithm @n + * These parameters are instantiated. + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The requested algorithm is not supported. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Security::KeyPair* GenerateKeyPairN(Tizen::Security::IKeyParameters* pKeyParams) const; + + /** + * Generates a new key pair. + * + * @since 2.0 + * + * @return A pointer to the KeyPair class, @n + else @c null if the method fails to create the key pair + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_ALGORITHM The requested algorithm is not supported. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. @n + * The method has failed to operate with the OpenSSL library, or the Tizen::Base::ByteBuffer operation has failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::KeyPair* GenerateKeyPairN(void) const; + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + KeyPairGenerator(const KeyPairGenerator& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + KeyPairGenerator& operator =(const KeyPairGenerator& rhs); + +private: + Tizen::Base::String __algorithm; + int __modulusBitSize; + + class _KeyPairGeneratorImpl* __pKeyPairGeneratorImpl; + friend class _KeyPairGeneratorImpl; + +}; //KeyPairGenerator + +} } //Tizen::Security + +#endif // _FSEC_KEY_PAIR_GENERATOR_H_ diff --git a/inc/FSecPrivateKey.h b/inc/FSecPrivateKey.h new file mode 100644 index 0000000..069ef15 --- /dev/null +++ b/inc/FSecPrivateKey.h @@ -0,0 +1,132 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecPrivateKey.h + * @brief This is the header file for the %PrivateKey class. + * + * This header file contains the declarations of the %PrivateKey class. + */ +#ifndef _FSEC_PRIVATE_KEY_H_ +#define _FSEC_PRIVATE_KEY_H_ + +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class PrivateKey + * @brief This class specifies the RSA private key. + * + * @since 2.0 + * + * The %PrivateKey class manages a private key, which is used in asymmetric ciphers. The RSA algorithm decrypts the data using the private key. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see IKey + * @see IPrivateKey + * @see IKeyPairGenerator + */ +class _OSP_EXPORT_ PrivateKey + : public virtual IKey + , public virtual IPrivateKey + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + PrivateKey(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~PrivateKey(void); + + /** + * Gets the name of the primary encoding format of the current instance of %PrivateKey. + * + * @since 2.0 + * + * @return The primary encoding format of a key + */ + virtual Tizen::Base::String GetFormat(void) const; + + /** + * Gets the private key in its primary encoding format. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedN(void) const; + + /** + * Sets the private key buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyBuffer An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keyBuffer is invalid. + * @remarks Only ASN.1 encoding format is supported for input buffer. + */ + virtual result SetKey(const Tizen::Base::ByteBuffer& keyBuffer); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + PrivateKey(const PrivateKey& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + PrivateKey& operator =(const PrivateKey& rhs); + +private: + Tizen::Base::String __algorithm; + Tizen::Base::String __encodedFormat; + Tizen::Base::ByteBuffer __keyBytes; + + class _PrivateKeyImpl* __pPrivateKeyImpl; + friend class _PrivateKeyImpl; + +}; // PrivateKey + +} } // Tizen::Security + +#endif //_FSEC_PRIVATE_KEY_H_ diff --git a/inc/FSecPublicKey.h b/inc/FSecPublicKey.h new file mode 100644 index 0000000..2e971a5 --- /dev/null +++ b/inc/FSecPublicKey.h @@ -0,0 +1,132 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecPublicKey.h + * @brief This is the header file for the %PublicKey class. + * + * This header file contains the declarations of the %PublicKey class. + */ +#ifndef _FSEC_PUBLIC_KEY_H_ +#define _FSEC_PUBLIC_KEY_H_ + +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class PublicKey + * @brief This class specifies the RSA public key. + * + * @since 2.0 + * + * The %PublicKey class manages a public key, which is used in asymmetric ciphers. + * The RSA algorithm encrypts the data using the public key. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see IKey + * @see IPublicKey + * @see IKeyPairGenerator + */ +class _OSP_EXPORT_ PublicKey + : public virtual IKey + , public virtual IPublicKey + , public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + PublicKey(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~PublicKey(void); + + /** + * Gets the name of the primary encoding format of the current instance of %PublicKey. + * + * @since 2.0 + * + * @return The primary encoding format of the key + */ + virtual Tizen::Base::String GetFormat(void) const; + + /** + * Gets the public key in its primary encoding format. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedN(void) const; + + /** + * Sets the public key buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyBuffer An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keyBuffer is invalid. + * @remarks Only ASN.1 encoding format is supported for input buffer. + */ + virtual result SetKey(const Tizen::Base::ByteBuffer& keyBuffer); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + PublicKey(const PublicKey& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + PublicKey& operator =(const PublicKey& rhs); + +private: + Tizen::Base::String __algorithm; + Tizen::Base::String __encodedFormat; + Tizen::Base::ByteBuffer __keyBytes; + + class _PublicKeyImpl* __pPublicKeyImpl; + friend class _PublicKeyImpl; + +}; //PublicKey + +} } //Tizen::Security + +#endif //_FSEC_PUBLIC_KEY_H_ diff --git a/inc/FSecSecretKey.h b/inc/FSecSecretKey.h new file mode 100644 index 0000000..86f8526 --- /dev/null +++ b/inc/FSecSecretKey.h @@ -0,0 +1,130 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecSecretKey.h + * @brief This is the header file for the %SecretKey class. + * + * This header file contains the declarations of the %SecretKey class. + */ +#ifndef _FSEC_SECRET_KEY_H_ +#define _FSEC_SECRET_KEY_H_ + +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class SecretKey + * @brief This class specifies a secret key. + * + * @since 2.0 + * + * The %SecretKey class manages a secret key, which is used in symmetric ciphers, such as Advanced Encryption Standard (AES), Data Encryption Standard (DES), and Triple Data Encryption Standard (3DES). @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see IKey + * @see ISecretKey + * @see SecretKeyGenerator + * @see ISecretKeyGenerator + */ +class _OSP_EXPORT_ SecretKey + : public virtual IKey + , public virtual ISecretKey + , public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + SecretKey(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~SecretKey(void); + + /** + * Gets the name of the primary encoding format of the current instance of %SecretKey. + * + * @since 2.0 + * + * @return The primary encoding format of a key + */ + virtual Tizen::Base::String GetFormat(void) const; + + /** + * Gets the secret key in its primary encoding format. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer class, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::ByteBuffer* GetEncodedN(void) const; + + /** + * Sets the secret key buffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyBuffer An instance of Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keyBuffer is invalid. + */ + virtual result SetKey(const Tizen::Base::ByteBuffer& keyBuffer); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + SecretKey(const SecretKey& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + SecretKey& operator =(const SecretKey& rhs); + +private: + Tizen::Base::ByteBuffer __keyBytes; + + class _SecretKeyImpl* __pSecretKeyImpl; + friend class _SecretKeyImpl; + +}; //SecretKey + +} } // Tizen::Security + +#endif //_FSEC_SECRET_KEY_H_ diff --git a/inc/FSecSecretKeyGenerator.h b/inc/FSecSecretKeyGenerator.h new file mode 100644 index 0000000..80d6f71 --- /dev/null +++ b/inc/FSecSecretKeyGenerator.h @@ -0,0 +1,152 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecSecretKeyGenerator.h + * @brief This is the header file for the %SecretKeyGenerator class. + * + * This header file contains the declarations of the %SecretKeyGenerator class. + */ +#ifndef _FSEC_SECRET_KEY_GENERATOR_H_ +#define _FSEC_SECRET_KEY_GENERATOR_H_ + +#include +#include +#include + + +namespace Tizen { namespace Security +{ + +/** + * @class SecretKeyGenerator + * @brief This class is used for generating a secret (symmetric) key. + * + * @since 2.0 + * + * The %SecretKeyGenerator class generates a secret key, which is used in symmetric ciphers. The generated secret key is based on an encryption algorithm. @n + * + * For more information on the class features, see Key Management and CSPRNG. + * + * @see ISecretKeyGenerator + */ +class _OSP_EXPORT_ SecretKeyGenerator + : public virtual ISecretKeyGenerator + , public Tizen::Base::Object +{ + +public: + /** + * The object is not fully constructed after this constructor is called. For full construction, @n + * the Construct() method must be called right after calling this constructor. + * + * @since 2.0 + */ + SecretKeyGenerator(void); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~SecretKeyGenerator(void); + + /** + * Constructs and initializes this instance of %SecretKeyGenerator with the specified key. + * + * @since 2.0 + * + * @return An error code + * @param[in] keyBytes The key of type Tizen::Base::ByteBuffer + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keyBytes is invalid or an empty Tizen::Base::ByteBuffer. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const Tizen::Base::ByteBuffer& keyBytes); + + /** + * Constructs and initializes this instance of %SecretKeyGenerator for the specified algorithm. + * + * @since 2.0 + * + * @return An error code + * @param[in] algorithm The name of the secure random generator algorithm @n + * For example, "AES","DES" or "3DES". + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c algorithm is invalid or an empty string. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(const Tizen::Base::String& algorithm); + + /** + * Constructs and initializes this instance of %SecretKeyGenerator with the specified key size. @n + * The default algorithm is Advanced Encryption Standard (AES). + * + * @since 2.0 + * + * @return An error code + * @param[in] keySize The key size + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c keySize is @c 0 or negative. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(int keySize); + + /** + * Generates a new secret key. + * + * @since 2.0 + * + * @return A pointer to the ISecretKey interface, @n + * else @c null if it fails to generate a secret key + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Security::ISecretKey* GenerateKeyN(void); + +private: + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + SecretKeyGenerator(const SecretKeyGenerator& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + SecretKeyGenerator& operator =(const SecretKeyGenerator& rhs); + +private: + Tizen::Base::String __algorithm; + int __keyGenSize; + Tizen::Security::ISecureRandom* __pRandom; + Tizen::Base::ByteBuffer __keyBytes; + + class _SecretKeyGeneratorImpl* __pSecretKeyGeneratorImpl; + friend class _SecretKeyGeneratorImpl; + +}; //SecretKeyGenerator + +} } //Tizen::Security + +#endif // _FSEC_SECRET_KEY_GENERATOR_H_ diff --git a/inc/FSecurity.h b/inc/FSecurity.h new file mode 100644 index 0000000..a587a64 --- /dev/null +++ b/inc/FSecurity.h @@ -0,0 +1,78 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecurity.h + * @brief This is the header file for the %Security namespace. + * + * This header file contains the declarations of the %Security namespace. + * + */ +#ifndef _FSECURITY_H_ +#define _FSECURITY_H_ + +#include "FSecAesSecureRandom.h" +#include "FSecDesEdeSecureRandom.h" +#include "FSecDesSecureRandom.h" +#include "FSecIKey.h" +#include "FSecIKeyPairGenerator.h" +#include "FSecIPrivateKey.h" +#include "FSecIPublicKey.h" +#include "FSecISecretKey.h" +#include "FSecISecretKeyGenerator.h" +#include "FSecISecureRandom.h" +#include "FSecKeyPair.h" +#include "FSecKeyPairGenerator.h" +#include "FSecPrivateKey.h" +#include "FSecPublicKey.h" +#include "FSecSecretKey.h" +#include "FSecSecretKeyGenerator.h" +#include "FSecIKeyParameters.h" +#include "FSecCryptoIKeyExchange.h" +#include "FSecCryptoKeaKeyExchange.h" +#include "FSecCryptoDhKeyExchange.h" +#include "FSecKeaKeyParameters.h" +#include "FSecDhKeyParameters.h" +#include "FSecCrypto.h" +#include "FSecCert.h" + + +/** + * @namespace Tizen::Security + * @brief This namespace contains classes and interfaces for security services. + * + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * + * The %Security namespace contains classes for + * managing certificates, cryptographic keys, signatures, and for generating pseudo-random numbers. @n + * + * For more information on the %Security namespace features, see Security Guide. @n + * + * The following diagram illustrates the relationships between the classes and sub-namespaces belonging to the %Security namespace. + * @image html security_classdiagram.png + * + */ +namespace Tizen { namespace Security +{ + +} } //Tizen::Security + +#endif // _FSECURITY_H_ diff --git a/inc/FSysAlarm.h b/inc/FSysAlarm.h new file mode 100755 index 0000000..475dc0b --- /dev/null +++ b/inc/FSysAlarm.h @@ -0,0 +1,181 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysAlarm.h + * @brief This is the header file for the %Alarm class. + * + * This header file contains the declarations of the %Alarm class. + */ + +#ifndef _FSYS_ALARM_H_ +#define _FSYS_ALARM_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @class Alarm + * @brief This class provides methods for creating, deleting, and updating an alarm. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Alarm class provides methods to create a one-time or repeating alarm. + * + * For more information on the class features, see System Guide. + */ + +class _OSP_EXPORT_ Alarm + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + */ + Alarm(void); + + /** + * This is the destructor for this class. @n + * It unregisters the current instance of %Alarm from the system. + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + ~Alarm(void); + + /** + * Initializes an instance of %Alarm with the specified @c listener. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener A reference to IAlarmEventListener + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(IAlarmEventListener& listener); + + /** + * Sets a one-time alarm. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/alarm + * + * @return An error code + * @param[in] duetime The time for the alarm to ring + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG The specified @c duetime is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks If this Alarm instance is already registered by this method, exist alarm is cancelled automatically. + */ + result Set(const Tizen::Base::DateTime& duetime); + + /** + * Sets a repeating alarm. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/alarm + * + * @return An error code + * @param[in] start The time for the alarm to ring first + * @param[in] period The interval in minutes between consecutive alarm rings + * @param[in] pEnd The time for the alarm ring to end + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * @remarks If this Alarm instance is already registered by this method, exist alarm is cancelled automatically. @n If @c pEnd is @c null, the alarm repeats forever. + */ + result Set(const Tizen::Base::DateTime& start, int period, const Tizen::Base::DateTime* pEnd = null); + + /** + * Cancels the alarm. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/alarm + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM A system error has occurred. + */ + result Cancel(void); + + /** + * Gets the start time for the current instance of %Alarm. + * + * @since 2.0 + * + * @return An instance of Tizen::Base::DateTime indicating the start time for the alarm + * @remarks If this Alarm instance is not registered by %Set method, return value is default value of %DateTime class. + */ + const Tizen::Base::DateTime GetStartTime(void) const; + + /** + * Gets the period of the current instance of %Alarm in minutes. + * + * @since 2.0 + * + * @return The period of the current instance of %Alarm in minutes + * @remarks If this Alarm instance is not registered by %Set method, return value is 0. + */ + int GetPeriod(void) const; + + /** + * Gets the end time for the current instance of %Alarm. + * + * @since 2.0 + * + * @return A pointer to Tizen::Base::DateTime indicating the end time for the alarm, @n + * else @c null if the end time has not been set + */ + const Tizen::Base::DateTime* GetEndTime(void) const; + +private: + /** + * This is the default copy constructor for this class. The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + Alarm(const Alarm& alarml); + + /** + * This is the assignment operator for this class. The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + Alarm& operator =(const Alarm& alarml); + +private: + friend class _AlarmImpl; + + class _AlarmImpl* __pAlarmImpl; + +}; // Alarm + +} } // Tizen::System + +#endif // _FSYS_ALARM_H_ diff --git a/inc/FSysBattery.h b/inc/FSysBattery.h new file mode 100644 index 0000000..e11acf5 --- /dev/null +++ b/inc/FSysBattery.h @@ -0,0 +1,132 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @if OSPCOMPAT + * @file FSysBattery.h + * @brief This is the header file for the %Battery class. + * + * This header file contains the declarations of the %Battery class. + * @endif + */ + +#ifndef _FSYS_BATTERY_H_ +#define _FSYS_BATTERY_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @if OSPCOMPAT + * @if OSPDEPREC + * @class Battery + * @brief [Deprecated] This class provides methods to get information related to the battery charge. + * + * @since 2.0 + * + * @deprecated This class is deprecated. Instead of using this class, use the PowerManager class. + * @final This class is not intended for extension. + * + * The %Battery class provides methods to get the status related to battery levels and + * determine whether the battery is currently being charged. + * You cannot create an instance of this class directly. + * + * For more information on the class features, see Battery Status. + * @endif + * @endif + */ +class _OSP_EXPORT_ Battery + : public Tizen::Base::Object +{ + +public: + /** + * Gets the current charge remaining in the battery as a percentage. + * + * @deprecated This method is deprecated. Instead of using this method, use the PowerManager::GetCurrentBatteryLevelInPercentage() method. + * @since 2.0 + * + * @return An error code + * @param[out] level The percentage of the charge remaining in the battery + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The battery service is not available. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The resolution of the level is 1% since 2.0. The range of the level is 0(Minimum) to 100(Maximum). + */ + static result GetCurrentLevelInPercentage(int& level); + + /** + * Gets the current charging level of the battery. + * + * @deprecated This method is deprecated. Instead of using this method, use the PowerManager::GetCurrentBatteryLevel() method. + * @since 2.0 + * + * @return An error code + * @param[out] level A value from the enumerator BatteryLevel indicating the current charging level + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The battery service is not available. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetCurrentLevel(BatteryLevel& level); + + /** + * Checks whether the battery is currently charging. + * + * @deprecated This method is deprecated. Instead of using this method, use the PowerManager::IsCharging() method. + * @since 2.0 + * + * @return An error code + * @param[out] charging Set to @c true if the charging cable is connected to the phone, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The battery service is not available. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result IsCharging(bool& charging); + +private: + /** + * This is the default constructor for this class. This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + Battery(void); + + /** + * This is the destructor for this class. + * This destructor overrides Tizen::Base::Object::~Object(). @n + */ + virtual ~Battery(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + Battery(const Battery& value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + Battery& operator =(const Battery& value); + +private: + friend class _BatteryImpl; +}; // Battery + +} } // Tizen::System + +#endif // _FSYS_BATTERY_H_ diff --git a/inc/FSysDeviceManager.h b/inc/FSysDeviceManager.h new file mode 100644 index 0000000..d4d14c7 --- /dev/null +++ b/inc/FSysDeviceManager.h @@ -0,0 +1,221 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysDeviceManager.h + * @brief This is the header file for the %DeviceManager class. + * + * This header file contains the declarations of the %DeviceManager class. + * + * + */ + +#ifndef _FSYS_DEVICE_MANAGER_H_ +#define _FSYS_DEVICE_MANAGER_H_ + +#include + +namespace Tizen { namespace System +{ + +class IDeviceEventListener; + +/** +* @enum DeviceType +* Defines the type of the supported devices. +* +* @since 2.0 +* +*/ +enum DeviceType +{ + BluetoothHeadset, // This enum value is deprecated. Instead of using this enum value, use DEVICE_TYPE_BLUETOOTH_HEADSET. + Charger, // This enum value is deprecated. Instead of using this enum value, use DEVICE_TYPE_CHARGER. + UsbClient, // This enum value is deprecated. Instead of using this enum value, use DEVICE_TYPE_USB_CLIENT. + TvOut, // This enum value is deprecated. Instead of using this enum value, use DEVICE_TYPE_TV_OUT. + WiredHeadset, // This enum value is deprecated. Instead of using this enum value, use DEVICE_TYPE_WIRED_HEADSET. + WiredHeadphone, // This enum value is deprecated. Instead of using this enum value, use DEVICE_TYPE_WIRED_HEADPHONE. + StorageCard, // This enum value is deprecated. Instead of using this enum value, use DEVICE_TYPE_STORAGE_CARD. + Keyboard, // This enum value is deprecated. Instead of using this enum value, use DEVICE_TYPE_KEYBOARD. + DEVICE_TYPE_BLUETOOTH_HEADSET = BluetoothHeadset, /**< Bluetooth headset */ + DEVICE_TYPE_CHARGER = Charger, /**< Charger*/ + DEVICE_TYPE_USB_CLIENT = UsbClient, /**< USB client */ + DEVICE_TYPE_TV_OUT = TvOut, /**< TV out */ + DEVICE_TYPE_WIRED_HEADSET = WiredHeadset, /**< Wired headset */ + DEVICE_TYPE_WIRED_HEADPHONE = WiredHeadphone, /**< Wired headphone */ + DEVICE_TYPE_STORAGE_CARD = StorageCard, /**< Storage card */ + DEVICE_TYPE_KEYBOARD = Keyboard, /**< Hardware Built-in keyboard */ + DEVICE_TYPE_HDMI, /**< HDMI @if OSPCOMPAT @b Since @ 2.0 @endif */ +}; + +/** + * @class DeviceManager + * @brief This class provides methods for device management. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %DeviceManager class provides listener to handle events for various external device, + * such as a Bluetooth headset, HDMI, and headphone. + * This class also gets the current state of the device. You cannot create an instance of this class directly. + * + * For more information on the class features, see External Device Management. + * + * @see IDeviceEventListener + * + */ +class _OSP_EXPORT_ DeviceManager + : public Tizen::Base::Object +{ + +public: + /** + * Gets the specific device state. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with %Tizen API versions @b prior @b to @b 2.0. @n + * For more information, see @ref DeviceManagerGetStatePage "here". + * @endif + * + * @param[in] deviceType The value from the enumerator DeviceType indicating the device + * @param[out] state The device state of type Tizen::Base::String + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_ARG The specified @c deviceType is not valid. + * @exception E_UNSUPPORTED_OPERATION The specified @c deviceType is not supported on this model. + */ + static result GetState(DeviceType deviceType, Tizen::Base::String& state); + + /** + * @if OSPCOMPAT + * @page DeviceManagerGetStatePage Compatibility for GetState() + * @section DeviceManagerGetStatePageIssueSection Issues + * Implementation of this method in %Tizen API version prior to 2.0 has the following issue: @n + * The GetState() method does not return E_DEVICE_UNAVAILABLE anymore. The E_DEVICE_UNAVAILABLE exception is removed. + * @section DeviceManagerGetStatePageIssueSection Resolutions + * The E_UNSUPPORTED_OPERATION exception is added since 2.0. So, use E_UNSUPPORTED_OPERATION instead of E_DEVICE_UNAVAILABLE. + * @endif + */ + + /** + * Adds a device event listener. + * + * @if OSPCOMPAT + * @brief [Compatibility] + * @endif + * @since 2.0 + * @if OSPCOMPAT + * @compatibility This method has compatibility issues with %Tizen API versions @b prior @b to @b 2.0. @n + * For more information, see @ref DeviceManagerAddDeviceEventListenerPage "here". + * @endif + * + * @return An error code + * @param[in] deviceType The types of a device + * @param[in] listener The device event listener + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_ARG The specified @c deviceType is not valid. + * @exception E_OBJ_ALREADY_EXIST The specified @c deviceType and @c listener are already registered. + * @exception E_UNSUPPORTED_OPERATION The specified @c deviceType is not supported on this model. + */ + static result AddDeviceEventListener(DeviceType deviceType, IDeviceEventListener& listener); + + /** + * @if OSPCOMPAT + * @page DeviceManagerAddDeviceEventListenerPage Compatibility for AddDeviceEventListener() + * @section DeviceManagerAddDeviceEventListenerPageIssueSection Issues + * Implementation of this method in %Tizen API version prior to 2.0 has the following issue: @n + * This AddDeviceEventListener() method does not return E_DEVICE_UNAVAILABLE anymore. The E_DEVICE_UNAVAILABLE exception is removed. + * @section DeviceManagerAddDeviceEventListenerPageIssueSection Resolutions + * The E_UNSUPPORTED_OPERATION exception is added since 2.0. So, use E_UNSUPPORTED_OPERATION instead of E_DEVICE_UNAVAILABLE exception. + * @endif + */ + + /** + * Removes a device event listener from all types of devices. + * + * @since 2.0 + * + * @return An error code + * @param[in] deviceType The types of a device + * @param[in] listener The device event listener + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_ARG The specified @c deviceType is not valid. + * @exception E_OBJ_NOT_FOUND The specified @c deviceType and @c listener are not registered. + * @exception E_UNSUPPORTED_OPERATION The specified @c deviceType is not supported on this model. + */ + static result RemoveDeviceEventListener(DeviceType deviceType, IDeviceEventListener& listener); + + /** + * @if OSPCOMPAT + * @page DeviceManagerRemoveDeviceEventListenerPage Compatibility for RemoveDeviceEventListener() + * @section DeviceManagerRemoveDeviceEventListenerPageIssueSection Issues + * Implementation of this method in %Tizen API version prior to 2.0 has the following issue: @n + * This RemoveDeviceEventListener() method does not return E_DEVICE_UNAVAILABLE anymore. The E_DEVICE_UNAVAILABLE exception is removed. + * @section DeviceManagerRemoveDeviceEventListenerPageIssueSection Resolutions + * The E_UNSUPPORTED_OPERATION exception is added since 2.0. So, use E_UNSUPPORTED_OPERATION instead of E_DEVICE_UNAVAILABLE exception. + * @endif + */ + + /** + * Removes all device event listeners. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + static result RemoveAllDeviceEventListeners(void); + +private: + /** + * This is the default constructor for this class. This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + DeviceManager(void); + + /** + * This is the destructor for this class. This destructor overrides Tizen::Base::Object::~Object(). @n + */ + virtual ~DeviceManager(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + DeviceManager(const DeviceManager& value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + DeviceManager& operator =(const DeviceManager& value); + +private: + friend class _DeviceManagerImpl; + class _DeviceManagerImpl* __pDeviceManagerImpl; + +}; // DeviceManager + +} } // Tizen::System +#endif // _FSYS_DEVICE_MANAGER_H_ diff --git a/inc/FSysEnvironment.h b/inc/FSysEnvironment.h new file mode 100644 index 0000000..28544ee --- /dev/null +++ b/inc/FSysEnvironment.h @@ -0,0 +1,149 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysEnvironment.h + * @brief This is the header file for the %Environment class. + * + * This header file contains the declarations of the %Environment class. + */ + +#ifndef _FSYS_ENVIRONMENT_H_ +#define _FSYS_ENVIRONMENT_H_ + +#include + +namespace Tizen { namespace System +{ + +/** + * @enum PredefinedDirectoryType + * + * Defines the type of the pre-defined directory used to classify files to be stored. + * + * @since 2.0 + */ +enum PredefinedDirectoryType +{ + PREDEFINED_DIRECTORY_IMAGES = 0, /** The directory for image files to be stored in internal storage (read-write permission) */ + PREDEFINED_DIRECTORY_SOUNDS, /** the directory for sound files to be stored in internal storage (read-write permission) */ + PREDEFINED_DIRECTORY_VIDEOS, /** The directory for video files to be stored in internal storage (read-write permission) */ + PREDEFINED_DIRECTORY_CAMERA, /** The directory for files to be stored in internal storage by camera application (read-write permission) */ + PREDEFINED_DIRECTORY_DOWNLOADS, /** The directory for files to be stored in internal storage by download manager (read-write permission) */ + PREDEFINED_DIRECTORY_OTHERS, /** The directory for other files to be stored in internal storage (read-write permission) */ + + PREDEFINED_DIRECTORY_EXTERNAL_IMAGES = 100, /** The directory for image files to be stored in external MMC (read-write permission) */ + PREDEFINED_DIRECTORY_EXTERNAL_SOUNDS, /** the directory for sound files to be stored in external MMC (read-write permission) */ + PREDEFINED_DIRECTORY_EXTERNAL_VIDEOS, /** The directory for video files to be stored in external MMC (read-write permission) */ + PREDEFINED_DIRECTORY_EXTERNAL_CAMERA, /** The directory for files to be stored in external MMC by camera application (read-write permission) */ + PREDEFINED_DIRECTORY_EXTERNAL_DOWNLOADS, /** The directory for files to be stored in external MMC by download manager (read-write permission) */ + PREDEFINED_DIRECTORY_EXTERNAL_OTHERS, /** The directory for other files to be stored in external MMC (read-write permission) */ + + PREDEFINED_DIRECTORY_APPLICATIONS = 200, /** The directory for applications to be installed in internal storage (read-only permission) */ + PREDEFINED_DIRECTORY_EXTERNAL_APPLICATIONS, /** The directory for applications to be installed in external MMC (read-only permission) */ +}; + +/** + * @class Environment + * @brief This class provides methods for getting the system environment variables. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Environment class provides methods for getting the system environment variables. + */ +class _OSP_EXPORT_ Environment +{ + +public: + /** + * Gets the path for the media directory that is usually used to store media contents. + * + * @since 2.0 + * + * @return The media directory path + */ + static Tizen::Base::String GetMediaPath(void); + + /** + * Gets the path for the default download directory that is usually used to store downloaded contents by the Tizen::Content::DownloadManager class. + * + * @since 2.0 + * + * @return The default download directory path + */ + static Tizen::Base::String GetDefaultDownloadPath(void); + + /** + * Gets the path for the external storage. + * + * @since 2.0 + * + * @return The external storage directory path + */ + static Tizen::Base::String GetExternalStoragePath(void); + + /** + * Gets the directory path according to the pre-defined directory type. + * + * @since 2.0 + * + * @return The pre-defined directory path according to the specified @c dirType, @n + * else an empty string if the specified @c dirType is invalid + * @param[in] dirType The pre-defined directory type + * @remarks The directory path for some directory types such as IMAGES, SOUNDS, VIDEOS, CAMERA, DOWNLOADS, and OTHERS may not yet exist, + * so you must make sure that it exists before using it. + * @see PredefinedDirectoryType + * @see Tizen::Io::Directory::Create() + */ + static Tizen::Base::String GetPredefinedPath(PredefinedDirectoryType dirType); + +private: + /** + * The implementation of this constructor is intentionally blank to prohibit creation of an instance. + * + * @since 2.0 + */ + Environment(void); + + /** + * The implementation of this destructor is intentionally blank because an instance cannot be created. + * + * @since 2.0 + */ + ~Environment(void); + + /** + * This copy constructor is intentionally declared as private to prohibit copying. + * + * @since 2.0 + */ + Environment(const Environment& rhs); + + /** + * This copy assignment operator is intentionally declared as private to prohibit copying. + * + * @since 2.0 + */ + Environment& operator =(const Environment& rhs); + +}; // Environment + +}} // Tizen::System + +#endif // _FSYS_ENVIRONMENT_H_ diff --git a/inc/FSysIAlarmEventListener.h b/inc/FSysIAlarmEventListener.h new file mode 100644 index 0000000..40331fc --- /dev/null +++ b/inc/FSysIAlarmEventListener.h @@ -0,0 +1,94 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysIAlarmEventListener.h + * @brief This is the header file for the %IAlarmEventListener interface. + * + * This header file contains the declarations of the %IAlarmEventListener interface. + */ + +#ifndef _FSYS_IALARM_EVENT_LISTENER_H_ +#define _FSYS_IALARM_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +class AlarmEvent; +class Alarm; + +/** + * @interface IAlarmEventListener + * @brief This interface is the listener of the alarm event. + * + * @since 2.0 + * + * The %IAlarmEventListener interface must be registered and implemented by an application to receive Alarm events from the system. + * + */ +class _OSP_EXPORT_ IAlarmEventListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IAlarmEventListener(void) {} + + /** + * Called when the alarm expires. + * + * @since 2.0 + * + * @param[in] alarm The alarm that expires + */ + virtual void OnAlarmExpired(Alarm& alarm) = 0; + +protected: + // The following methods are reserved, and the name of methods can be changed at any time without prior notice. + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + // + virtual void OnIAlarmEventListener_Reserved1(void) {}; + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIAlarmEventListener_Reserved2(void) {}; + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIAlarmEventListener_Reserved3(void) {}; + +}; // IAlarmEventListener + +} } // Tizen::System + +#endif // _FSYS_IALARM_EVENT_LISTENER_H_ diff --git a/inc/FSysIBatteryEventListener.h b/inc/FSysIBatteryEventListener.h new file mode 100644 index 0000000..b592198 --- /dev/null +++ b/inc/FSysIBatteryEventListener.h @@ -0,0 +1,90 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysIBatteryEventListener.h + * @brief This is the header file for the %IBatteryEventListener interface. + * + * This header file contains the declarations of the %IBatteryEventListener interface. + */ + +#ifndef _FSYS_IBATTERY_EVENT_LISTENER_H_ +#define _FSYS_IBATTERY_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @interface IBatteryEventListener + * @brief This interface is the listener of the battery event. + * + * @since 2.0 + * + * The %IBatteryEventListener interface must be registered and implemented by an application to receive Battery events from the system. + */ + +class _OSP_EXPORT_ IBatteryEventListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + + virtual ~IBatteryEventListener(void) {} + /** + * Called when the battery level is changed. + * + * @since 2.0 + * + * @param[in] percentage The changed battery level + * @remarks The resolution of the level is @c 5%. The range of the level is @c 0 (Minimum) to @c 100 (Maximum). + */ + virtual void OnBatteryLevelChangedInPercentage(int percentage) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIBatteryEventListener_Reserved1(void) {}; + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIBatteryEventListener_Reserved2(void) {}; + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIBatteryEventListener_Reserved3(void) {}; + +}; // IBatteryEventListener + +} } // Tizen::System + +#endif // _FSYS_IALARM_EVENT_LISTENER_H_ diff --git a/inc/FSysIChargingEventListener.h b/inc/FSysIChargingEventListener.h new file mode 100644 index 0000000..c4ca327 --- /dev/null +++ b/inc/FSysIChargingEventListener.h @@ -0,0 +1,89 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysIChargingEventListener.h + * @brief This is the header file for the %IChargingEventListener interface. + * + * This header file contains the declarations of the %IChargingEventListener interface. + */ + +#ifndef _FSYS_ICHARGING_EVENT_LISTENER_H_ +#define _FSYS_ICHARGING_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @interface IChargingEventListener + * @brief This interface is the listener of the charging event. + * @since 2.0 + * + * The %IChargingEventListener interface must be registered and implemented by an application to + * receive events from the system when the device charging state changes. + * + */ +class _OSP_EXPORT_ IChargingEventListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IChargingEventListener(void) {} + + /** + * Called when the charging state is changed. + * + * @since 2.0 + * + * @param[in] charging The charging state + */ + virtual void OnChargingStateChanged(bool charging) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIChargingEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIChargingEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIChargingEventListener_Reserved3(void) {} + +}; // IChargingEventListener + +} } // Tizen::System + +#endif // _FSYS_ICHARGING_EVENT_LISTENER_H_ diff --git a/inc/FSysIDeviceEventListener.h b/inc/FSysIDeviceEventListener.h new file mode 100644 index 0000000..c3618f2 --- /dev/null +++ b/inc/FSysIDeviceEventListener.h @@ -0,0 +1,92 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysIDeviceEventListener.h + * @brief This is the header file for the %IDeviceEventListener interface. + * + * This header file contains the declarations of the %IDeviceEventListener interface. + */ + +#ifndef _FSYS_IDEVICE_EVENT_LISTENER_H_ +#define _FSYS_IDEVICE_EVENT_LISTENER_H_ + +#include +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @interface IDeviceEventListener + * @brief This interface is the listener of the device state changes. + * + * @since 2.0 + * + * The %IDeviceEventListener interface must be registered and implemented by an application to receive device events from the system. + * + * @see DeviceManager + */ +class _OSP_EXPORT_ IDeviceEventListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~IDeviceEventListener(void) {} + + /** + * Called when a device state is changed. + * + * @since 2.0 + * + * @param[in] deviceType The types of a device + * @param[in] state The device state of type Tizen::Base::String + */ + virtual void OnDeviceStateChanged(DeviceType deviceType, const Tizen::Base::String& state) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIDeviceEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIDeviceEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIDeviceEventListener_Reserved3(void) {} + +}; // IDeviceEventListener + +} } // Tizen::System + +#endif // _FSYS_IDEVICE_EVENT_LISTENER_H_ diff --git a/inc/FSysIRuntimeInfoGetIntAsyncResultListener.h b/inc/FSysIRuntimeInfoGetIntAsyncResultListener.h new file mode 100644 index 0000000..5f5f74e --- /dev/null +++ b/inc/FSysIRuntimeInfoGetIntAsyncResultListener.h @@ -0,0 +1,91 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FSysIRuntimeInfoGetIntAsyncResultListener.h +* @brief This is the header file for the %IRuntimeInfoGetIntAsyncResultListener interface. +* +* This header file contains the declarations of the %IRuntimeInfoGetIntAsyncResultListener interface. +*/ + +#ifndef _FSYS_IRUNTIME_INFO_GET_INT_ASYNC_RESULT_LISTENER_H_ +#define _FSYS_IRUNTIME_INFO_GET_INT_ASYNC_RESULT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** +* @interface IRuntimeInfoGetIntAsyncResultListener +* @brief This interface defines the result listener for an asynchronous method call to the RuntimeInfo class. +* +* @since 2.0 +* +* The %IRuntimeInfoGetIntAsyncResultListener interface defines the result listener for an asynchronous method call to the RuntimeInfo class. An instance of this interface is removed automatically by platform, after result is notified. +* +*/ +class _OSP_EXPORT_ IRuntimeInfoGetIntAsyncResultListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ IRuntimeInfoGetIntAsyncResultListener (void) {} + /** + * Called when a result received from an asynchronous method call is a key of type @c int. + * + * @since 2.0 + * + * @param[in] value The @c int type runtime information + * @param[in] r An error code + * @exception E_SUCCESS The result is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual void OnResultReceivedForGetValueAsync(int value, result r) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IGetValueAsyncResultListener_Reserved1 (void){} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IGetValueAsyncResultListener_Reserved2 (void){} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IGetValueAsyncResultListener_Reserved3 (void){} + +}; // IRuntimeInfoGetIntAsyncResultListener + +} } // Tizen::System +#endif // _FSYS_IRUNTIME_INFO_GET_INT_ASYNC_RESULT_LISTENER_H_ + diff --git a/inc/FSysIRuntimeInfoGetLonglongAsyncResultListener.h b/inc/FSysIRuntimeInfoGetLonglongAsyncResultListener.h new file mode 100644 index 0000000..80c5265 --- /dev/null +++ b/inc/FSysIRuntimeInfoGetLonglongAsyncResultListener.h @@ -0,0 +1,90 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FSysIRuntimeInfoGetLonglongAsyncResultListener.h +* @brief This is the header file for the %IRuntimeInfoGetLonglongAsyncResultListener interface. +* +* This header file contains the declarations of the %IRuntimeInfoGetLonglongAsyncResultListener interface. +*/ + +#ifndef _FSYS_IRUNTIME_INFO_GET_LONGLONG_ASYNC_RESULT_LISTENER_H_ +#define _FSYS_IRUNTIME_INFO_GET_LONGLONG_ASYNC_RESULT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** +* @interface IRuntimeInfoGetLonglongAsyncResultListener +* @brief This interface defines the result listener for an asynchronous method call to the RuntimeInfo class. +* +* @since 2.0 +* +* The %IRuntimeInfoGetLonglongAsyncResultListener interface defines the result listener for an asynchronous method call to the RuntimeInfo class. An instance of this interface is removed automatically by platform, after result is notified. +* +*/ +class _OSP_EXPORT_ IRuntimeInfoGetLonglongAsyncResultListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ IRuntimeInfoGetLonglongAsyncResultListener (void) {} + /** + * Called when a result received from an asynchronous method call is a key of type @c long @c long. + * + * @since 2.0 + * + * @param[in] value The @c long @c long type runtime information + * @param[in] r An error code + * @exception E_SUCCESS The result is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + virtual void OnResultReceivedForGetValueAsync(long long value, result r) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IGetValueAsyncResultListener_Reserved1 (void){} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IGetValueAsyncResultListener_Reserved2 (void){} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void IGetValueAsyncResultListener_Reserved3 (void){} + +}; // IRuntimeInfoGetLonglongAsyncResultListener + +} } // Tizen::System +#endif // _FSYS_IRUNTIME_INFO_GET_LONGLONG_ASYNC_RESULT_LISTENER_H_ diff --git a/inc/FSysIScreenEventListener.h b/inc/FSysIScreenEventListener.h new file mode 100644 index 0000000..c260dea --- /dev/null +++ b/inc/FSysIScreenEventListener.h @@ -0,0 +1,91 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysIScreenEventListener.h + * @brief This is the header file of the %IScreenEventListener interface. + * + * This header file contains the declarations of the %IScreenEventListener interface. + */ + +#ifndef _FSYS_ISCREEN_EVENT_LISTENER_H_ +#define _FSYS_ISCREEN_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @interface IScreenEventListener + * @brief This interface is the listener of the screen event. + * + * @since 2.0 + * + * The %IScreenEventListener interface must be registered and implemented by an application to receive screen events from the system. + * + */ +class _OSP_EXPORT_ IScreenEventListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * Called when the screen turns on. @n + * Gets the released resources or resumes the operations that were paused or stopped in OnScreenOff(). + * + * @since 2.0 + */ + virtual void OnScreenOn(void) = 0; + + /** + * Called when the screen turns off. @n + * Unless there is a strong reason to do otherwise, release resources (such as 3D, media, and sensors) to allow the device to enter the sleep mode to save the battery. + *Invoking a lengthy asynchronous method within this listener method can be risky, because it is not guaranteed to invoke a callback before the device enters the sleep mode. + *Similarly, do not perform lengthy operations in this listener method. All operations must be quick ones. + * + *@since 2.0 + */ + virtual void OnScreenOff(void) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIScreenEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIScreenEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnIScreenEventListener_Reserved3(void) {} + +}; // IScreenEventListener + +} } // Tizen::System + +#endif // _FSYS_ISCREEN_EVENT_LISTENER_H_ diff --git a/inc/FSysISettingEventListener.h b/inc/FSysISettingEventListener.h new file mode 100644 index 0000000..bbee668 --- /dev/null +++ b/inc/FSysISettingEventListener.h @@ -0,0 +1,89 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysISettingEventListener.h + * @brief This is the header file of the %ISettingEventListener interface. + * + * This header file contains the declarations of the %ISettingEventListener interface. + */ + +#ifndef _FSYS_ISETTING_EVENT_LISTENER_H_ +#define _FSYS_ISETTING_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @interface ISettingEventListener + * @brief This interface is the listener of the setting event. + * + * @since 2.0 + * + * The %ISettingEventListener interface must be registered and implemented by an application to receive setting events from the system. + * + */ +class _OSP_EXPORT_ ISettingEventListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISettingEventListener(void) {} + /** + * Called when a certain setting value has been changed. + * + * @since 2.0 + * + * @param[in] key The key name of the changed setting information + * @remarks Invokes one of the overloaded getter methods of Tizen::System::SettingInfo to get the changed value corresponding to the given key. + */ + virtual void OnSettingChanged(Tizen::Base::String& key) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingEventListener_Reserved3(void) {} + +}; // ISettingEventListener + +} } // Tizen::System + +#endif // _FSYS_ISETTING_EVENT_LISTENER_H_ diff --git a/inc/FSysISettingInfoSetValueAsyncResultListener.h b/inc/FSysISettingInfoSetValueAsyncResultListener.h new file mode 100644 index 0000000..e3ca52d --- /dev/null +++ b/inc/FSysISettingInfoSetValueAsyncResultListener.h @@ -0,0 +1,133 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/* + * @file FSysISettingInfoSetValueAsyncResultListener.h + * @brief This is the header file of the %ISettingInfoSetValueAsyncResultListener interface. + * + * This header file contains the declarations of the %ISettingInfoSetValueAsyncResultListener interface. + */ + +#ifndef _FSYS_ISETTING_INFO_SET_VALUE_ASYNC_RESULT_LISTENER_H_ +#define _FSYS_ISETTING_INFO_SET_VALUE_ASYNC_RESULT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @interface ISettingInfoSetValueAsyncResultListener + * @brief This interface defines the result listener for an asynchronous setting change method call. + * + * @since 2.0 + * + * The %ISettingInfoSetValueAsyncResultListener interface must be registered and implemented by an application to receive result for an asynchronous setting change method call. + * + */ +class _OSP_EXPORT_ ISettingInfoSetValueAsyncResultListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @since 2.0 + */ + virtual ~ISettingInfoSetValueAsyncResultListener(void) {} + + /** + *Called when a result is received for an asynchronous setting change method call. + * + * @since 2.0 + * + * @param[in] key The key name of the changed setting information + * @param[in] r An error code + * @exception E_SUCCESS The result is successful. + * @exception E_SYSTEM The method cannot proceed due to severe system error. + */ + + virtual void OnResultReceivedForSetValueAsync(const Tizen::Base::String& key, result r) = 0; + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved3(void) {} + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved4(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved5(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved6(void) {} + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved7(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved8(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // @since 2.0 + virtual void OnISettingInfoSetValueAsyncResultListener_Reserved9(void) {} + +}; // ISettingEventListener + +} } // Tizen::System + +#endif // _FSYS_ISETTING_INFO_SET_VALUE_ASYNC_RESULT_LISTENER_H_ diff --git a/inc/FSysPowerManager.h b/inc/FSysPowerManager.h new file mode 100755 index 0000000..6f3a329 --- /dev/null +++ b/inc/FSysPowerManager.h @@ -0,0 +1,313 @@ + +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysPowerManager.h + * @brief This is the header file for the %PowerManager class. + * + * This header file contains the declarations of the %PowerManager class. + */ + +#ifndef _FSYS_POWER_MANAGER_H_ +#define _FSYS_POWER_MANAGER_H_ + +#include + +namespace Tizen { namespace System +{ + +class IScreenEventListener; +class IChargingEventListener; +class IBatteryEventListener; + +/** + * @enum BatteryLevel + * + * Defines the representation of the remaining charge in the battery. + * + * @since 2.0 + */ +enum BatteryLevel +{ + BATTERY_FULL, // This enum value is deprecated. Instead of using this enum value, use BATTERY_LEVEL_FULL. + BATTERY_HIGH, // This enum value is deprecated. Instead of using this enum value, use BATTERY_LEVEL_HIGH. + BATTERY_LOW, // This enum value is deprecated. Instead of using this enum value, use BATTERY_LEVEL_LOW. + BATTERY_CRITICAL, // This enum value is deprecated. Instead of using this enum value, use BATTERY_LEVEL_CRITICAL. + BATTERY_EMPTY, // This enum value is deprecated. Instead of using this enum value, use BATTERY_LEVEL_EMPTY. + BATTERY_LEVEL_FULL = BATTERY_FULL,/**< The battery is fully charged */ + BATTERY_LEVEL_HIGH = BATTERY_HIGH,/**< The battery has plenty of charge */ + BATTERY_LEVEL_LOW = BATTERY_LOW,/**< The battery has little charge */ + BATTERY_LEVEL_CRITICAL = BATTERY_CRITICAL,/**< The battery charge is at a critical state @n It is strongly recommended to stop using all multimedia features because they are not guaranteed to work correctly at this level. */ + BATTERY_LEVEL_EMPTY = BATTERY_EMPTY, /**< The battery is empty @n It is strongly recommended to prepare for the safe termination of the application because the device will start a shutdown process soon after entering this level. */ +}; + +/** + * @enum PowerMode + * + * Defines the representation of the charge remaining in the battery. + * + * @since 2.0 + */ +enum PowerMode +{ + POWER_STANDBY, // This enum value is deprecated. Instead of using this enum value, use POWER_MODE_STANDBY. + POWER_SLEEP, // This enum value is deprecated. Instead of using this enum value, use POWER_MODE_SLEEP. + POWER_MODE_STANDBY = POWER_STANDBY, /**< The battery is fully charged */ + POWER_MODE_SLEEP = POWER_SLEEP, /**< The battery has plenty of charge */ +}; + +/** + * @class PowerManager + * @brief This class provides methods for power management. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %PowerManager class provides methods for managing the device power state. + * + * For more information on the class features, see Screen Power Management. + + */ + +class _OSP_EXPORT_ PowerManager + : public Tizen::Base::Object +{ + +public: + /** + * Changes the policy of the screen power management. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/power + * + * @return An error code + * @param[in] keepOn Set to @c true if the screen remains in the 'ON' state until the application goes to the background, @n + * else @c false if the state of the screen is controlled by the default power control policy of the system + * @param[in] dimming Set to @c true if the screen is dimmed when there is no user input for a certain amount of time, @n + * else @c false if the screen is not dimmed + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM A system error has occurred. + * @remarks The application should explicitly call this method again, if the screen is to be kept 'ON' after coming back from the background state. + */ + static result KeepScreenOnState(bool keepOn, bool dimming = true); + + /** + * Restores the screen brightness control. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The brightness is never changed. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see SetScreenBrightness() + */ + static result RestoreScreenBrightness(void); + + /** + * Sets the screen brightness level for an application. + * + * @since 2.0 + * @privilege %http://tizen.org/privilege/power + * + * @return An error code + * @param[in] brightness The brightness level to set @n + * The parameter value can range between @c 1 (minimum) and @c 10 (maximum). + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_OUT_OF_RANGE The specified @c brightness is out of range. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks This brightness level is only available when an application is running on the foreground. Even if the brightness is set to level 1, a black screen is not displayed. Level 1 is the minimum brightness level that can be set for an application. + * @see RestoreScreenBrightness() + */ + + static result SetScreenBrightness(int brightness); + /** + * Gets the screen brightness level of an application. + * + * @since 2.0 + * + * @return The brightness level of the current application + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks This method returns the screen brightness level set for an application. If the brightness level is not set, it will return the default system brightness level. @n + * In case of error, this method returns @c -1. + */ + static int GetScreenBrightness(void); + + /** + * Checks whether the screen is on. + * + * @since 2.0 + * + * @return @c true if the screen is on, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks This method returns @c true when the screen is in the dimming state, and @c false in case of an error. + */ + static bool IsScreenOn(void); + + /** + * Turns on the screen. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/power + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM A system error has occurred. + */ + static result TurnScreenOn(void); + + /** + * Turns off the screen. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/power + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM A system error has occurred. + */ + static result TurnScreenOff(void); + + /** + * Changes the policy of the CPU (Central Processing Unit) power management. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/power + * + * @return An error code + * @param[in] enable Set to @c true to prevent the CPU from going into sleep mode, @n + * else @c false to let the state of the CPU follow the system default power management policy + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM A system error has occurred. + */ + static result KeepCpuAwake(bool enable); + + /** + * Sets the screen event listener. + * + * @since 2.0 + * + * @param[in] listener The screen event listener + * @see IScreenEventListener + */ + static void SetScreenEventListener(IScreenEventListener& listener); + + /** + * Sets the charging event listener. + * + * @since 2.0 + * + * @param[in] listener The charging event listener + */ + static void SetChargingEventListener(IChargingEventListener& listener); + + /** + * Sets the battery event listener. + * + * @since 2.0 + * + * @return An error code + * @param[in] pListener The battery event listener + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks If @c pListener is set to @c null, the pre-registered listener is unregistered. + */ + static result SetBatteryEventListener(IBatteryEventListener* pListener); + + /** + * Gets the current charge remaining in the battery as a percentage. + * + * @since 2.0 + * + * @return The percentage of the charge remaining in the battery. + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_OPERATION The method is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remakrs The specific error code can be accessed using the GetLastResult() method. + * @remarks The resolution of the level is @c 1 percentage. The range of the level is minimum @c 0 to maximum @c 100. + */ + static int GetCurrentBatteryLevelInPercentage(void); + + /** + * Gets the current charging level of the battery. + * + * @since 2.0 + * + * @return A value from the enumerator BatteryLevel indicating the current charging level + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_OPERATION The method is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static BatteryLevel GetCurrentBatteryLevel(void); + + /** + * Checks whether the battery is currently charging. + * + * @since 2.0 + * + * @return @c true if the charging cable is connected to the phone, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_OPERATION The method is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static bool IsCharging(void); + +private: + /** + * This is the default constructor for this class. This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + PowerManager(void); + /** + * This is the destructor for this class. This destructor overrides Tizen::Base::Object::~Object(). + */ + virtual ~PowerManager(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + PowerManager(const PowerManager& value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + PowerManager& operator = (const PowerManager& value); + +private: + friend class _PowerManagerImpl; + class _PowerManagerImpl* __pPowerManagerImpl; +}; // PowerManager + +} } // Tizen::System + +#endif // _FSYS_POWER_MANAGER_H_ diff --git a/inc/FSysRuntimeInfo.h b/inc/FSysRuntimeInfo.h new file mode 100755 index 0000000..67b36a0 --- /dev/null +++ b/inc/FSysRuntimeInfo.h @@ -0,0 +1,246 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysRuntimeInfo.h + * @brief This is the header file for the %RuntimeInfo class. + * + * This header file contains the declarations of the %RuntimeInfo class. + */ + +#ifndef _FSYS_RUNTIME_INFO_H_ +#define _FSYS_RUNTIME_INFO_H_ + +#include +#include +#include + +namespace Tizen { namespace System +{ + +class IRuntimeInfoGetIntAsyncResultListener; +class IRuntimeInfoGetLonglongAsyncResultListener; + +/** + * @class RuntimeInfo + * @brief This class provides methods for getting runtime information. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %RuntimeInfo class provides runtime information, such as the allocated memory used by the application storage, memory, and CPU utilization. To get the information, you must provide the RuntimeInfo key. + * + * For more information on the class features, see Runtime Information. + * + * The following example demonstrates how to use the %RuntimeInfo class. + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::System; + * + * result + * MyClass::GetAllocatedMemory(void) + * { + * result r = E_SUCCESS; + * + * String key(L"http://tizen.org/runtime/memory.allocated"); + * int allocatedMemory = 0; + * + * r = RuntimeInfo::GetValue(key, allocatedMemory); + * TryCatch(r == E_SUCCESS, , "MyRuntimeInfo: Failed to get value"); + * + * return E_SUCCESS; + * + * CATCH: + * return r; + * } + * @endcode + * + */ + +class _OSP_EXPORT_ RuntimeInfo + : public Tizen::Base::Object +{ + +public: + /** + * Gets the specific Tizen::Base::String type runtime information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the runtime information + * @param[out] value The runtime information of type Tizen::Base::String + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, Tizen::Base::String& value); + + /** + * Gets the specific integer type runtime information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the runtime information @n + * @if OSPCOMPAT + * The following key values are updated: @n + * - @b Since: @b 2.0 Refer here. + * @xmlonly memory.allocated, memory.available @endxmlonly + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @endif + * @param[out] value The integer type runtime information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, int& value); + + /** + * Gets the specific @c long @c long type runtime information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the runtime information @n + * @if OSPCOMPAT + * The following key values are updated: @n + * - @b Since: @b 2.0 Refer here. + * @xmlonly storage.external.available, storage.internal.available, storage.media.available @endxmlonly + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @xmlonly @endxmlonly MaxAllocatableMemory, AvailableVideoMemory @xmlonly @endxmlonly + * @endif + * @param[out] value The @c long @c long type runtime information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, long long& value); + + /** + * Gets the specific double type runtime information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the runtime information + * @param[out] value The @c double type runtime information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, double& value); + + /** + * Gets the specific @c bool type runtime information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the runtime information + * @param[out] value The @c bool type runtime information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, bool& value); + + /** + * Gets the specific UuId type runtime information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the runtime information + * @param[out] value The UuId type runtime information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, Tizen::Base::UuId& value); + + /** + * Gets the specific @c long @c long type runtime information based on specified designators (key) asynchronously. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key of the runtime information + * @param[in] listener The result listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The listener instance ownership is transferred to platform. After notifying result, listener instance is removed automatically. A reuse of the listener instance is not allowed. + */ + static result GetValueAsync(const Tizen::Base::String& key, IRuntimeInfoGetLonglongAsyncResultListener* listener); + + /** + * Gets the specific @c int type runtime information based on specified designators (key) asynchronously. + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key of the runtime information + * @param[in] listener The result listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The listener instance ownership is transferred to platform. After notifying result, listener instance is removed automatically. A reuse of the listener instance is not allowed. + */ + static result GetValueAsync(const Tizen::Base::String& key, IRuntimeInfoGetIntAsyncResultListener* listener); + +private: + /** + * This is the default constructor for this class. This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + RuntimeInfo(void); + + /** + * This is the destructor for this class. This destructor overrides Tizen::Base::Object::~Object(). + */ + virtual ~RuntimeInfo(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + RuntimeInfo(const RuntimeInfo& value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + RuntimeInfo& operator =(const RuntimeInfo& value); + +private: + friend class _RuntimeInfoImpl; + class _RuntimeInfoImpl* __pRuntimeInfoImpl; +}; // RuntimeInfo + +} } // Tizen::System + +#endif // _FSYS_RUNTIME_INFO_H_ diff --git a/inc/FSysSettingInfo.h b/inc/FSysSettingInfo.h new file mode 100755 index 0000000..21c3c00 --- /dev/null +++ b/inc/FSysSettingInfo.h @@ -0,0 +1,505 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysSettingInfo.h + * @brief This is the header file for the %SettingInfo class. + * + * This header file contains the declarations of the %SettingInfo class. + */ + +#ifndef _FSYS_SETTING_INFO_H_ +#define _FSYS_SETTING_INFO_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @class SettingInfo + * @brief This class provides methods for managing setting information. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %SettingInfo class provides methods to managing the variety user setting elements. Please refer SettingInfo key. + * + * For more information on the class features, see Settings Information. + * + * The following example demonstrates how to use the %SettingInfo class. + * + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::System; + * + * result + * MyClass::GetSettingInfomation(void) + * { + * result r = E_SUCCESS; + * + * String key(L"http://tizen.org/setting/location.gps"); + * bool gpsEnabled = false; + * + * r = SettingInfo::GetValue(key, gpsEnabled); + * TryCatch(r == E_SUCCESS, , "MySettingInfo: To get a value is failed"); + * + * return E_SUCCESS; + * + * CATCH: + * return r; + * } + * @endcode + * + */ +class _OSP_EXPORT_ SettingInfo + : public Tizen::Base::Object +{ + +public: + /** + * Gets the specific Tizen::Base::String type setting information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the setting information @n + * @if OSPCOMPAT + * The following key values are updated: @n + * - @b Since: @b 2.0 Refer here. + * @xmlonly locale.country, locale.time.format, locale.date.format, locale.datetime.format, font.type, locale.language, theme, sound.ringtone, screen.wallpaper, screen.wallpaper.lock, usbmode @endxmlonly + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @endif + * @param[out] value The setting information of type Tizen::Base::String + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, Tizen::Base::String& value); + + /** + * Gets the specific integer type setting information based on the specified + * designators (keys). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the setting information @n + * @if OSPCOMPAT + * The following key values are updated: @n + * - @b Since: @b 2.0 Refer here. + * @xmlonly font.size, sound.media.volume, sound.notification.volume, sound.ringtone.volume, sound.system.volume, vibrator.level @endxmlonly + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @endif + * @param[out] value The setting information of type integer + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, int& value); + + /** + * Gets the specific @c long @c long type setting information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[out] value The setting information of type @c long @c long + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, long long& value); + + /** + * Gets the specific double type setting information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[out] value The setting information of type double + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, double& value); + + /** + * Gets the specific @c bool type setting information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the setting information @n + * @if OSPCOMPAT + * The following key values are updated: @n + * - @b Since: @b 2.0 Refer here. + * @xmlonly network.roaming, network.flightmode, network.packetservice, locale.time.format.24hour, location.gps, location.wps, sound.silentmode, motion @endxmlonly + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @endif + * @param[out] value The setting information of type bool + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, bool& value); + + /** + * Gets the specific UuId type setting information based on the specified + * designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[out] value The setting information of type UuId + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, Tizen::Base::UuId& value); + + /** + * Checks whether specific designator(key) is supported or not. + * + * @since 2.0 + * + * @return @c true if the key is supported, @n + * else @c false + * @param[in] key The key name of the setting information + * + */ + static bool HasKey(const Tizen::Base::String& key); + + /** + * Sets the specific @c bool type setting information based on the specified designators (key). + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/setting + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[in] value The setting information of type bool + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGED_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG The specified @c value is invalid value. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result SetValue(const Tizen::Base::String& key, bool value); + + /** + * Sets the specific @c int type setting information based on the specified designators (key). + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/setting + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[in] value The setting information of type int + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGED_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG The specified @c value is invalid value. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result SetValue(const Tizen::Base::String& key, int value); + + /** + * Sets the specific Tizen::Base::String type setting information based on the specified designators (key). + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/setting + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[in] value The setting information of type Tizen::Base::String + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGED_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG The specified @c value is invalid value. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result SetValue(const Tizen::Base::String& key, Tizen::Base::String value); + + /** + * Sets the system wallpaper. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/setting + * + * @return An error code + * @param[in] filePath The file path of the wallpaper + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_FILE_NOT_FOUND The entry for the specified wallpaper file or the file path cannot be found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specified wallpaper file is copied to the managed folder by the system, while the previously set wallpaper is removed.
This parameter is compatible with "Wallpaper". + */ + + static result SetWallpaper(const Tizen::Base::String& filePath); + + /** + * Sets the system ringtone. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/setting + * + * @return An error code + * @param[in] filePath The file path of the ringtone + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_FILE_NOT_FOUND The entry for the specified wallpaper file or the file path cannot be found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specified ringtone file has to exist in the media directory. + */ + static result SetRingtone(const Tizen::Base::String& filePath); + + /** + * Sets the sound volume level. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/setting + * + * @return An error code + * @param[in] soundCategory The sound volume category + * @param[in] level The sound volume level of the designated category + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG The specified @c soundCategory is invalid. + * @exception E_OUT_OF_RANGE The specified @c level is outside the bounds of @c soundCategory. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result SetVolume(const Tizen::Base::String& soundCategory, int level); + + /** + * Adds the setting event listener. @n + * This listener is called when a setting value is changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The setting event listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_ALREADY_EXIST The listener is already added. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see RemoveSettingEventListener() + */ + static result AddSettingEventListener(ISettingEventListener& listener); + + /** + * Removes the setting event listener. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener The setting event listener + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The listener is not added. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see AddSettingEventListener() + */ + static result RemoveSettingEventListener(ISettingEventListener& listener); + + /** + * @if VISPARTNER-MANUFACTURER + * Gets the specific @c bool type setting information based on the specified designators (key). + * + * @since 2.0 + * + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/systemsetting.read + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[out] value The setting information of type bool + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGED_DENIED The application does not have the privilege to call this method. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @endif + */ + static result GetValueForPrivilegedKey(const Tizen::Base::String& key, bool& value); + + /** + * @if VISPARTNER-MANUFACTURER + * Sets the specific @c bool type setting information based on the specified designators (key). + * + * @since 2.0 + * + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/systemsetting.write + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[in] value The setting information of type bool + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGED_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG The specified @c value is invalid value. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @endif + */ + static result SetValueForPrivilegedKey(const Tizen::Base::String& key, bool value); + + /** + * @if VISPARTNER-MANUFACTURER + * Sets the specific @c bool type setting information based on the specified designators (key) asynchronously. + * + * @since 2.0 + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/systemsetting.write + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[in] value The setting information of type bool + * @param[in] listener The result listener. + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGED_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG The specified @c value is invalid value. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key is existed, However it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The listener instance ownership is transferred to platform. After notifying result, listener instance is removed automatically. A reuse of the listener instance is not allowed. + * @endif + */ + static result SetValueAsyncForPrivilegedKey(const Tizen::Base::String& key, bool value, ISettingInfoSetValueAsyncResultListener* listener); + + /** + * @if VISPARTNER-MANUFACTURER + * Sets the specific Tizen::Base::String type setting information based on the specified designators (key). + * + * @since 2.0 + * + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/systemsetting.write + * + * @return An error code + * @param[in] key The key name of the setting information + * @param[in] value The setting information of type Tizen::Base::String + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGED_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG The specified @c value is invalid value. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_UNSUPPORTED_OPERATION The specified @c key exists. However, it is not supported by this device. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @endif + */ + static result SetValueForPrivilegedKey(const Tizen::Base::String& key, Tizen::Base::String value); + + /** + * @if VISPARTNER-MANUFACTURER + * Resets current device. @n + * All data is removed and device is initialized. + * + * @since 2.0 + * + * @visibility partner-manufacturer + * @privilege %http://tizen.org/privilege/systemsetting.write + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGED_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @endif + */ + static result ResetToFactoryDefault(void); + + /** + * @if OSPCOMPAT + * @if OSPDEPREC + * Sets the setting event listener. + * + * @deprecated This method is provided only for backward compatibility and will be deleted in the near future. Instead of using this method, it is recommended to use AddSettingEventListener() and RemoveSettingEventListener(). + * @since 2.0 + * + * @return An error code + * @param[in] pListener The setting event listener + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks If the value of the listener object (pListener) is @c null, the setting event listener is not called. + * @endif + * @endif + */ + static result SetSettingEventListener(ISettingEventListener* pListener); + + +private: + /** + * This is the default constructor for this class. This default constructor is intentionally + declared as private so that only the platform can create an instance. + */ + SettingInfo(void); + + /** + * This is the destructor for this class. This destructor overrides Tizen::Base::Object::~Object(). + */ + virtual ~SettingInfo(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + SettingInfo(const SettingInfo& value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + SettingInfo& operator =(const SettingInfo& value); + +private: + friend class _SettingInfoImpl; + class _SettingInfoImpl* __pSettingInfoImpl; +}; // SettingInfo + +} } // Tizen::System + +#endif // _FSYS_SETTING_INFO_H_ diff --git a/inc/FSysSystemInfo.h b/inc/FSysSystemInfo.h new file mode 100755 index 0000000..55cf971 --- /dev/null +++ b/inc/FSysSystemInfo.h @@ -0,0 +1,303 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysSystemInfo.h + * @brief This is the header file for the %SystemInfo class. + * + * This header file contains the declarations of the %SystemInfo class. + */ + +#ifndef _FSYS_SYSTEM_INFO_H_ +#define _FSYS_SYSTEM_INFO_H_ + +#include +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @enum SystemInfoValueType + * + * Defines the data type for the %SystemInfo class. + * + * @since 2.0 + */ +enum SystemInfoValueType +{ + VALUE_TYPE_STRING, // This enum value is deprecated. Instead of using this enum value, use SYSTEM_INFO_VALUE_TYPE_STRING. + VALUE_TYPE_INTEGER, // This enum value is deprecated. Instead of using this enum value, use SYSTEM_INFO_VALUE_TYPE_INTEGER. + VALUE_TYPE_DOUBLE, // This enum value is deprecated. Instead of using this enum value, use SYSTEM_INFO_VALUE_TYPE_DOUBLE. + VALUE_TYPE_UUID, // This enum value is deprecated. Instead of using this enum value, use SYSTEM_INFO_VALUE_TYPE_UUID. + SYSTEM_INFO_VALUE_TYPE_STRING = VALUE_TYPE_STRING, /**< The Tizen::Base::String type */ + SYSTEM_INFO_VALUE_TYPE_INTEGER = VALUE_TYPE_INTEGER, /**< The Tizen::Base::Integer type */ + SYSTEM_INFO_VALUE_TYPE_DOUBLE = VALUE_TYPE_DOUBLE, /**< The Tizen::Base::Double type */ + SYSTEM_INFO_VALUE_TYPE_UUID = VALUE_TYPE_UUID, /**< The Tizen::Base::UuId type */ +}; + +/** + * @class SystemInfo + * @brief This class provides methods for getting system information. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %SystemInfo class provides system information, such as the API and platform versions, supported device features, + * and screen dimensions. + * To get the information, you must provide the SystemInfo key. + * + * For more information on the class features, see System Information. + * + * The following example demonstrates how to use the %SystemInfo class. + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::System; + * + * result + * MyClass::GetSystemInfomation(void) + * { + * result r = E_SUCCESS; + * + * String key(L"http://tizen.org/system/duid"); + * String deviceUniqueId; + * + * r = SystemInfo::GetValue(key, deviceUniqueId); + * TryCatch(r == E_SUCCESS, , "MySystemInfo: To get a value is failed"); + * + * return E_SUCCESS; + * + * CATCH: + * return r; + * } + * @endcode + * + */ +class _OSP_EXPORT_ SystemInfo + : public Tizen::Base::Object +{ + +public: + /** + * Gets the specific Tizen::Base::String type system information based on the specified designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the system information @n + * @if OSPCOMPAT + * The following key values are updated: @n + * - @b Since: @b 2.0 Refer here. + * @xmlonly telephony, input.keyboard.layout, screen.size, screen.coordinatesystem.physical, screen.coordinatesystem.logical, platform.core.cpu.arch, platform.core.fpu.arch, platform.name, modelname, duid, map.provider @endxmlonly + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @endif + * @param[out] value The system information of type Tizen::Base::String + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, Tizen::Base::String& value); + + /** + * Gets the specific integer type system information based on the specified designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the system information @n + * @if OSPCOMPAT + * The following key values are updated: @n + * - @b Since: @b 2.0 Refer here. + * @xmlonly multipointtouch.pointcount, sound.media.volume.max, sound.notification.volume.max, sound.ringtone.volume.max, sound.system.volume.max, screen.bpp, screen.height, screen.width, screen.dpi @endxmlonly + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @endif + * @param[out] value The integer type system information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, int& value); + + /** + * Gets the specific double type system information based on the specified designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the system information + * @param[out] value The @c double type system information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, double& value); + + /** + * Gets the specific UuId type system information based on the specified designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the system information + * @param[out] value The UuId type system information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, Tizen::Base::UuId& value); + + /** + * Gets the specific system information based on the specified key and data type of the information. + * + * @since 2.0 + * + * @return A system information list + * @param[in] key The key name of the system information @n + * @if OSPCOMPAT + * The following key values are updated @n + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @endif + * @param[in] type The data type of the information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Tizen::Base::Collection::IList* GetValuesN(const Tizen::Base::String& key, SystemInfoValueType type); + + /** + * Gets the specific boolean type system information based on the specified designators (key). + * + * @since 2.0 + * + * @return An error code + * @param[in] key The key name of the system information @n + * @if OSPCOMPAT + * The following key values are updated: @n + * - @b Since: @b 2.0 Refer here. + * @xmlonly bluetooth, camera, camera.front, camera.front.flash, camera.back, camera.back.flash, location, location.wps, location.gps, microphone, nfc, sensor.barometer, sensor.barometer.wakeup, sensor.accelerometer, sensor.accelerometer.wakeup, sensor.magnetometer, sensor.magnetometer.wakeup, sensor.gyroscope, sensor.gyroscope.wakeup, sensor.photometer, sensor.photometer.wakeup, sensor.tiltmeter, sensor.tiltmeter.wakeup, sensor.proximity, sensor.proximity.wakeup, usb.host, usb.accessory, input.keyboard, wifi, wifi.direct, opengles.version.1_1, opengles.version.2_0, screen.desktopmode, screen.output.rca, screen.output.hdmi, fmradio, speech.recognition, sip.voip @endxmlonly + * - @b Deprecated All the key values provided prior to %Tizen 2.0 are deprecated. For more detailed information, refer + * here. + * @endif + * @param[out] value The @c bool type system information + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The specified @c key is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetValue(const Tizen::Base::String& key, bool& value); + + /** + * Gets the platform version in the "[Major].[Minor].[Build Version]" format. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/platforminfo + * + * @return An error code + * @param[out] platformVersion The platform version + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetPlatformVersion(Tizen::Base::String& platformVersion); + + /** + * Gets the Native API version in the "[Major].[Minor]" format. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/platforminfo + * + * @return An error code + * @param[out] nativeApiVersion The Native API version + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetNativeApiVersion(Tizen::Base::String& nativeApiVersion); + + /** + * Gets the WEB API version in the "[Major].[Minor]" format. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/platforminfo + * + * @return An error code + * @param[out] webApiVersion The %Tizen API version + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + */ + static result GetWebApiVersion(Tizen::Base::String& webApiVersion); + + /** + * @if VISPARTNER + * Gets the International Mobile Equipment Identity (IMEI) of the device. + * + * @since 2.0 + * + * @visibility partner + * @privilege %http://tizen.org/privilege/useridentity + * + * @return An error code + * @param[out] imei The IMEI of the device + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @endif + */ + static result GetImei(Tizen::Base::String& imei); + +private: + /** + * This is the default constructor for this class. This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + SystemInfo(void); + + /** + * This is the destructor for this class. This destructor overrides Tizen::Base::Object::~Object(). + */ + virtual ~SystemInfo(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + SystemInfo(const SystemInfo& value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + SystemInfo& operator =(const SystemInfo& value); + +private: + friend class _SystemInfoImpl; + class _SystemInfoImpl* __pSystemInfoImpl; +}; // SystemInfo + +} } // Tizen::System + +#endif //_FSYS_SYSTEM_INFO_H_ diff --git a/inc/FSysSystemTime.h b/inc/FSysSystemTime.h new file mode 100644 index 0000000..e916054 --- /dev/null +++ b/inc/FSysSystemTime.h @@ -0,0 +1,158 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysSystemTime.h + * @brief This is the header file for the %SystemTime class. + * + * This header file contains the declarations of the %SystemTime class. + */ + +#ifndef _FSYS_SYSTEM_TIME_H_ +#define _FSYS_SYSTEM_TIME_H_ + +#include +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @class SystemTime + * @brief This class provides methods to get the system time. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %SystemTime class provides methods to get the current system time, ticks, and uptime. + * It also supports the UTC, standard, and wall time modes. + * + * For more information on the class features, see System Time. + */ + +/** + * @enum TimeMode + * + * Defines the three types of time modes. + * + * @since 2.0 + */ +enum TimeMode +{ + UTC_TIME, // This enum value is deprecated. Instead of using this enum value, use UTC_TIME. + STANDARD_TIME, // This enum value is deprecated. Instead of using this enum value, use STANDARD_TIME. + WALL_TIME, // This enum value is deprecated. Instead of using this enum value, use TIME_MODE_WALL. + TIME_MODE_UTC = UTC_TIME, /**< The UTC Time */ + TIME_MODE_STANDARD = STANDARD_TIME, /**< The Standard Time */ + TIME_MODE_WALL = WALL_TIME, /**< The Wall Time */ +}; + +class _OSP_EXPORT_ SystemTime +{ + +public: + /** + * Gets the uptime in milliseconds since the system is booted. + * + * @since 2.0 + * + * @return An error code + * @param[out] uptime The uptime in milliseconds + * @exception E_SUCCESS The method is successful. + */ + static result GetUptime(Tizen::Base::TimeSpan& uptime); + + /** + * Gets the current system time. + * + * @since 2.0 + * + * @return An error code + * @param[out] currentTime The current system time in UTC + * @exception E_SUCCESS The method is successful. + */ + static result GetCurrentTime(Tizen::Base::DateTime& currentTime); + + /** + * Gets the current system time. + * + * @since 2.0 + * + * @return An error code + * @param[in] timeMode The time mode @c TIME_MODE_UTC, TIME_MODE_STANDARD, or @c TIME_MODE_WALL + * @param[out] currentTime The current system time + * @exception E_SUCCESS The method is successful. + */ + static result GetCurrentTime(TimeMode timeMode, Tizen::Base::DateTime& currentTime); + + /** + * Gets the current system time in milliseconds since 1/1/1970 UTC. + * + * @since 2.0 + * + * @return An error code + * @param[out] ticks The system time in milliseconds + * @exception E_SUCCESS The method is successful. + */ + static result GetTicks(long long& ticks); + + /* + * @if VISPARTNER + * Sets the current system time. + * + * @since 2.0 + * + * @return An error code + * @param[in] currentTime The current system time in UTC + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @endif + */ + static result SetCurrentTime(const Tizen::Base::DateTime& currentTime); +private: + /** + * This is the default constructor for this class. This default constructor is intentionally declared as private so that only the platform can create an instance. + */ + SystemTime(void); + + /** + * This is the destructor for this class. This destructor overrides Tizen::Base::Object::~Object(). + */ + virtual ~SystemTime(void); + + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + SystemTime(const SystemTime& value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + SystemTime& operator =(const SystemTime& value); + +private: + friend class _SystemTimeImpl; + class _SystemTimeImpl* __pSystemTimeImpl; + +}; // SystemTime + +} } // Tizen::System + +#endif // _FSYS_SYSTEM_TIME_H_ diff --git a/inc/FSysVibrator.h b/inc/FSysVibrator.h new file mode 100755 index 0000000..0d0c88a --- /dev/null +++ b/inc/FSysVibrator.h @@ -0,0 +1,210 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysVibrator.h + * @brief This is the header file for the %Vibrator class. + * + * This header file contains the declarations of the %Vibrator class. + */ + +#ifndef _FSYS_VIBRATOR_H_ +#define _FSYS_VIBRATOR_H_ + +#include + +namespace Tizen { namespace System +{ + +/** + * @class Vibrator + * @brief This class handles the vibration functionality of the device. + * + * @since 2.0 + * + * The %Vibrator class handles the vibration functionality of a device. It allows you to manage the device's vibrator parameters, such as vibration count and level. + * + * For more information on the class features, see Vibrator Management. + * + * The following example demonstrates how to use the %Vibrator class. + * + * @code + * + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::System; + * + * class MyVibratorClass + * { + * public: + * result VibratorExample(void); + * private: + * Vibrator vibrator; + * }; + * + * result + * MyVibratorClass::VibratorExample(void) + * { + * result r = vibrator.Construct(); + * if (IsFailed(r)) + * { + * goto CATCH; + * } + * + * // Vibrate with a given pattern and level + * vibrator.Start(2000, 1000, 1, 50); + * + * return E_SUCCESS; + * + * CATCH: + * // Do some exception handling + * return r; + * } + * @endcode + */ + +class _OSP_EXPORT_ Vibrator + : public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + * @remarks The object is not fully constructed after this constructor is called. For full construction, the Construct() method must be called right after calling this constructor. + */ + Vibrator(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + * + * @remarks If the instance is destroyed before the vibration stops, the vibration is stopped forcefully. + */ + virtual ~Vibrator(void); + + /** + * Initializes this instance of %Vibrator. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM An unknown operating system error has occurred. + * + */ + result Construct(void); + + /** + * Vibrates the device with the specified pattern and level. @n + * This method returns the result immediately so that the vibration occurs simultaneously as the device runs. + * If this method is called again before the previous vibration stops, the previous vibration is canceled and the new vibration starts immediately. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/vibrator + * + * @return An error code + * @param[in] onPeriod The period in milliseconds when the vibrator is on @n + * It should be greater than @c 0. + * @param[in] offPeriod The period in milliseconds when the vibrator is off @n + * It should be equal to or greater than @c 0. + * @param[in] count The number of times to execute the given pattern @n + * It should be greater than @c 0. + * @param[in] level The vibration level @n + * Ranges from [@c 0~ @c 100], where ' @c 0' is a special case indicating the system default level. + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_DEVICE_BUSY The device cannot be approached because of other operations. + * @exception E_DEVICE_FAILED The device operation has failed. + * @remarks Various devices may have different vibration capabilities. + * If the device supports only one level of vibration, then a level value between [@c 0~ @c 100] results in the default vibration. + * If the device supports many levels of vibration, then a level value @c 0 results in the system default vibration, value @c 1 results in the lowest frequency vibration, value @c 100 results in the highest frequency vibration, and intermediate values result in intermediate vibration levels. @n + * Devices have implementation-specific limits for the total duration of the vibration, and vibration cuts off at that limit even if the duration parameter is greater than the limit. + * + */ + result Start(long onPeriod, long offPeriod, int count, int level = 0); + + /** + * Vibrates the device for the specified duration at the specified @c level. @n + * This method returns the result immediately so that the vibration occurs simultaneously as the device runs. + * If this method is called again before the previous vibration stops, the previous vibration is canceled and the new vibration starts immediately. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/vibrator + * + * @return An error code + * @param[in] milliseconds The duration for the vibration in milliseconds @n + * It should be greater than @c 0. + * @param[in] level The vibration level @n + * Ranges from [@c 0~ @c 100], where ' @c 0' is a special case indicating the system default level. + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_DEVICE_BUSY The device cannot be approached because of other operations. + * @exception E_DEVICE_FAILED The device operation has failed. + * @remarks Various devices have different vibration capabilities. @n + * If the device supports only one level of vibration, then a level value between [@c 0~ @c 100] results in the default vibration. + * If the device supports many levels of vibration, then a level value @c 0 results in the system default vibration, value @c 1 results in the lowest frequency vibration, value @c 100 results in the highest frequency vibration, and intermediate values result in intermediate vibration levels. @n + * Devices have implementation-specific limits for the total duration of the vibration, and vibration cuts off at that limit even if the duration parameter is greater than the limit. + * + */ + result Start(long milliseconds, int level = 0); + + /** + * Turns the vibrator off. + * + * @since 2.0 + * + * @privilege %http://tizen.org/privilege/vibrator + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * @exception E_DEVICE_FAILED The device operation has failed. + * + */ + result Stop(void); + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + */ + Vibrator(const Vibrator& value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + */ + Vibrator& operator =(const Vibrator& value); + +private: + friend class _VibratorImpl; + class _VibratorImpl* __pVibratorImpl; + +}; // Vibrator + +} } // Tizen::System + +#endif diff --git a/inc/FSystem.h b/inc/FSystem.h new file mode 100644 index 0000000..b3914fe --- /dev/null +++ b/inc/FSystem.h @@ -0,0 +1,89 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSystem.h + * @brief This is the header file for the %System namespace. + * + * This header file contains the declarations of the %System namespace. + * + */ + +#ifndef _FSYSTEM_H_ +#define _FSYSTEM_H_ + +// Alarm +#include +#include + +// SystemTime +#include + +// Vibrator +#include + +// System Information +#include + +// Runtime Information +#include +#include +#include + +// Setting Information +#include +#include +#include + +// Power Manager +#include +#include +#include +#include + +// Device State +#include +#include + +// Environment +#include + +namespace Tizen +{ +/** + * @namespace Tizen::System + * @brief This namespace contains classes and interfaces for %System. + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library : @b osp-appfw + * + * The %System namespace provides system management features, such as system time, alarm, vibrator, power, and device management. + * It also provides the system, setting, and runtime information. + * + * For more information on the %System namespace features, see System Guide. + * + * The following diagram illustrates the relationships between the classes belonging to the %System namespace. + * + * @image html system_namespace_classdiagram.png + * + */ +namespace System +{}; // System +}; // Tizen + +#endif // _FSYSTEM_H_ diff --git a/inc/FText.h b/inc/FText.h new file mode 100644 index 0000000..44cc23b --- /dev/null +++ b/inc/FText.h @@ -0,0 +1,69 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText.h + * @brief This is the header file for the %Text namespace. + * + * This header file contains the declarations of the %Text namespace. + */ + +#ifndef _FTEXT_H_ +#define _FTEXT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/** + * @namespace Tizen::Text + * @brief This namespace contains classes that encode and decode characters. + * + * @since 2.0 + * + * @remarks @b Header @b %file: @b \#include @b @n + * @b Library: @b osp-appfw + * + * The %Text namespace contains the Encoding class, which is the base class for encoding and decoding many character encodings, such as UTF-8, UCS-2, Latin-1, GSM, and ASCII. It also contains the Decoder and Encoder classes for converting text blocks. The main purpose of this namespace is to support inter- + * operability between the various existing languages and scripts. + * %Text is a data consisting of a sequence of characters. + * It is also defined as a series of characters that can be displayed on a + * display terminal or printed on paper for human reading. + * + * For more information on the %Text namespace features, see Text Guide. + * + * The following diagram illustrates the relationships between the classes belonging to the %Text namespace. + * @image html text_using_the_apis_classdiagram.png + * + * + * + */ + +namespace Tizen { namespace Text +{ + +}} // Tizen::Text + +#endif //_FTEXT_H_ diff --git a/inc/FTextAsciiEncoding.h b/inc/FTextAsciiEncoding.h new file mode 100644 index 0000000..d2124a7 --- /dev/null +++ b/inc/FTextAsciiEncoding.h @@ -0,0 +1,379 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextAsciiEncoding.h + * @brief This is the header file for the %AsciiEncoding class. + * + * This header file contains the declarations of the %AsciiEncoding class. @n + * The %AsciiEncoding class is derived from the Encoding class. + */ +#ifndef _FTEXT_ASCII_ENCODING_H_ +#define _FTEXT_ASCII_ENCODING_H_ + +#include + + +namespace Tizen { namespace Text +{ + +/** + * @class AsciiEncoding + * @brief This class is an implementation of the American Standard Code for Information Interchange (ASCII) encoding. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %AsciiEncoding class encodes Unicode characters as single 7-bit ASCII characters. + * This encoding only supports ASCII character values between U+0000 and U+007F. + * + * For more information on the class features, see Converting All Text Data at Once. + * + * The following example demonstrates how to use the %AsciiEncoding class. + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Text; + * + * void + * MyClass::AsciiEncodingSample(void) + * { + * AsciiEncoding ascii; + * + * String str(L"012345 ABCDE"); + * + * int byteCount; + * ascii.GetByteCount(str, byteCount); + * + * // Encodes + * ByteBuffer* pBuffer = ascii.GetBytesN(str); + * + * int charCount; + * ascii.GetCharCount(*pBuffer, charCount); + * + * // Decodes + * String decodedStr; + * ascii.GetString(*pBuffer, decodedStr); + * + * if (str.Equals(decodedStr)) + * { + * //.... + * } + * + * delete pBuffer; + * } + * @endcode + */ + +class _OSP_EXPORT_ AsciiEncoding + : public Encoding +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + */ + AsciiEncoding(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Text::Encoding::~Encoding(). + * + * @since 2.0 + * + */ + virtual ~AsciiEncoding(void); + + /** + * Encodes an instance of the specified Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c chars is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetCharsN() + * @see GetBytesN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars) const; + + /** + * Encodes an instance of the specified Tizen::Base::String into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] str A string to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c str is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetString() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::String& str) const; + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetChars() + */ + virtual result GetBytes(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Encodes an instance of Tizen::Base::String into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c str or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c str. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c str. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetString() + */ + virtual result GetBytes(const Tizen::Base::String& str, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Decodes an instance of the specified Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer. @n + * The GetCharsN() method maintains no state consistency between conversions. The method is intended for + * conversions of complete blocks of bytes and characters in one operation. + * This method decodes in a single step. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte plus one and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c bytes is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::WcharBuffer instance is not changed. + * The GetChars() method maintains no state consistency between conversions. The method is intended for + * conversions of complete blocks of bytes and characters in one operation. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] chars The Tizen::Base::WcharBuffer instance where the resultant decoded string is stored + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes or @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c chars does not contain sufficient space to store the decoded bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetChars(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, Tizen::Base::WcharBuffer& chars, int charIndex = 0) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks GetString() assumes that the Tizen::Base::ByteBuffer instance contains all the bytes necessary to generate the entire string. + * If the bytes are in multiple byte arrays, use the Decoder class, which maintains state consistency + * between multiple calls. + * @see GetBytesN() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, Tizen::Base::String& str) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] index The index from where decoding begins + * @param[in] count The total number of bytes to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks GetString() assumes that the Tizen::Base::ByteBuffer instance contains all the bytes necessary to generate the entire string. + * If the bytes are in multiple byte arrays, use the Decoder class, which maintains state consistency + * between multiple calls. + * @see GetBytes() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, int index, int count, Tizen::Base::String& str) const; + + /** + * Gets the maximum number of bytes required for encoding a given number of characters. + * + * @since 2.0 + * + * @return The maximum number of bytes required for encoding a given number of characters + * @param[in] charCount The total number of characters to encode + * @remarks GetMaxByteCount() determines an appropriate buffer size for the byte arrays passed to GetBytes() for encoding. + * @see Encoding::GetByteCount() + * @see GetBytes() + */ + virtual int GetMaxByteCount(int charCount) const; + + /** + * Gets the maximum number of characters that are generated by decoding the specified number of bytes. + * + * @since 2.0 + * + * @return The maximum number of characters that are generated by decoding the specified number of bytes + * @param[in] byteCount The total number of bytes to encode + * @remarks GetMaxCharCount() determines an appropriate buffer size for character arrays passed to + * GetChars() or a decoder for encoding. + * @see Encoding::GetCharCount() + * @see GetChars() + */ + virtual int GetMaxCharCount(int byteCount) const; + + + /** + * Gets the encoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Encoder instance for the current encoding + * @remarks Contrary to GetBytes(), an encoder can convert partial sequences of characters into + * partial sequences of bytes by maintaining the appropriate state between the conversions. @n + * At present, only the Utf8Encoding class supports this method. Other classes return @c null. + * @see GetBytes() + */ + virtual Encoder* GetEncoderN(void) const; + + /** + * Gets the decoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Decoder instance for the current encoding + * @remarks Contrary to GetChars(), a decoder can convert partial sequences of bytes + * into partial sequences of characters by maintaining the appropriate state between the conversions. @n + * At present, only the Utf8Encoding class supports this method. Other classes return @c null. + * + * @see GetChars() + */ + virtual Decoder* GetDecoderN(void) const; + + /** + * Gets the encoding type of the current instance. + * + * @since 2.0 + * + * @return An encoding type + */ + virtual Tizen::Base::String GetEncodingType(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + AsciiEncoding(const AsciiEncoding& asciiEncoding); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + AsciiEncoding& operator =(const AsciiEncoding& asciiEncoding); + + friend class _AsciiEncodingImpl; + class _AsciiEncodingImpl* __pAsciiEncodingImpl; +}; + +} } // Tizen::Text +#endif //_FTEXT_ASCII_ENCODING_H_ diff --git a/inc/FTextDecoder.h b/inc/FTextDecoder.h new file mode 100644 index 0000000..511cb15 --- /dev/null +++ b/inc/FTextDecoder.h @@ -0,0 +1,158 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextDecoder.h + * @brief This is the header file for the %Decoder class. + * + * This header file contains the declarations of the %Decoder class. + */ + +#ifndef _FTEXT_DECODER_H_ +#define _FTEXT_DECODER_H_ + +#include +#include +#include + +namespace Tizen { namespace Text +{ +/** + * @class Decoder + * @brief This class is an implementation of the character decoder. + * + * @since 2.0 + * + * The %Decoder class converts blocks of encoded bytes into blocks of Unicode characters + * through successive calls to the GetCharsN() method. This class maintains state consistency information between + * successive calls to GetCharsN(), enabling it to decode a sequence of bytes that span adjacent blocks. + * + * For more information on the class features, see Converting Text Data in Separate Blocks. + * + */ + +class _OSP_EXPORT_ Decoder + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Decoder(void) { }; + + /** + * Gets the total number of characters that are generated by decoding a range of elements specified in the Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * @param[out] charCount The total number of characters that are generated by decoding the specified Tizen::Base::ByteBuffer instance + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see Encoder::GetByteCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, + int byteIndex, int byteCount, int& charCount, bool flush = false) const = 0; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte plus one in the buffer and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Encoder::GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes, bool flush = false) const = 0; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer as per the specified range. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte in the buffer and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The GetCharsN() method maintains state consistency between conversions. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks The pointer to the Tizen::Base::WcharBuffer instance is not terminated by a @c null character. + * @see Encoder::GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, + bool flush = false) const = 0; + +protected: + Decoder(void) + : _pDecoderImpl(null){}; + friend class _DecoderImpl; + class _DecoderImpl* _pDecoderImpl; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Decoder(const Decoder& decoder); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Decoder& operator =(const Decoder& decoder); + +}; + +} } // Tizen::Text +#endif //_FTEXT_DECODER_H_ diff --git a/inc/FTextEncoder.h b/inc/FTextEncoder.h new file mode 100644 index 0000000..bb91348 --- /dev/null +++ b/inc/FTextEncoder.h @@ -0,0 +1,156 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextEncoder.h + * @brief This is the header file for the %Encoder class. + * + * This header file contains the declarations of the %Encoder class. + * + */ +#ifndef _FTEXT_ENCODER_H_ +#define _FTEXT_ENCODER_H_ + +#include +#include +#include + +namespace Tizen { namespace Text +{ +/** + * @class Encoder + * @brief This class is an implementation of the character encoder. + * + * @since 2.0 + * + * The %Encoder class converts blocks of characters to blocks of encoded bytes + * through successive calls to the GetBytesN() method. This class maintains the state consistency information between + * successive calls to GetBytesN(), enabling it to encode a character into a sequence of bytes, + * such as surrogate pairs, that span adjacent blocks. + * + * For more information on the class features, see Converting Text Data in Separate Blocks. + */ + +class _OSP_EXPORT_ Encoder + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Encoder(void) { }; + + /** + * Gets the total number of bytes that are required to encode a range of characters in the specified Tizen::Base::WcharBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see Decoder::GetCharCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, + int charIndex, int charCount, int& byteCount, bool flush = false) const = 0; + + /** + * Encodes an instance of the specified Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one in the buffer and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Decoder::GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars, bool flush = false) const = 0; + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer as per the specified range. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte in the buffer and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks The pointer to the Tizen::Base::ByteBuffer instance is not terminated by a @c null character. + * @see Decoder::GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, + bool flush = false) const = 0; + +protected: + Encoder(void) + : _pEncoderImpl(null){}; + friend class _EncoderImpl; + class _EncoderImpl* _pEncoderImpl; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Encoder(const Encoder& encoder); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Encoder& operator =(const Encoder& encoder); +}; + +} } // Tizen::Text +#endif //_FTEXT_ENCODER_H_ diff --git a/inc/FTextEncoding.h b/inc/FTextEncoding.h new file mode 100644 index 0000000..66bf303 --- /dev/null +++ b/inc/FTextEncoding.h @@ -0,0 +1,658 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextEncoding.h + * @brief This is the header file for the %Encoding class. + * + * This header file contains the declarations of the %Encoding class. @n + * The %Encoding class is the base class for all character encoding classes. + */ +#ifndef _FTEXT_ENCODING_H_ +#define _FTEXT_ENCODING_H_ + +// Include +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Text +{ + +/** + * @class Encoding + * @brief This class implements character encoding. + * + * @since 2.0 + * + * The %Encoding class is the base class for all classes that implement character encoding. + * + * For more information on the class features, see Converting All Text Data at Once. + * + * The following example demonstrates how to use the %Encoding class. + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Text; + * + * void + * MyClass::EncodingSample(void) + * { + * Encoding* pEnc = Encoding::GetEncodingN(L"ISO-8859-2"); + * + * String str(L"Encoding Test \u0104\u02D8"); + * + * int byteCount; + * pEnc->GetByteCount(str, byteCount); + * + * // Encodes + * ByteBuffer* pBuffer = pEnc->GetBytesN(str); + * + * int charCount; + * pEnc->GetCharCount(*pBuffer, charCount); + * + * // Decodes + * String decodedStr; + * pEnc->GetString(*pBuffer, decodedStr); + * + * if (str.Equals(decodedStr)) + * { + * //.... + * } + * + * delete pBuffer; + * + * delete pEnc; + * } + * @endcode + */ + +class AsciiEncoding; +class Utf8Encoding; +class Ucs2Encoding; +class Latin1Encoding; +class GsmEncoding; + +class _OSP_EXPORT_ Encoding + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.0 + */ + virtual ~Encoding(void); + + /** + * Gets the total number of bytes that are required to encode the specified string. + * + * @since 2.0 + * + * @return An error code + * @param[in] str The string to encode + * @param[out] byteCount The total number of bytes that are required to encode the specified string + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c str is an empty string. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of bytes + * that are generated when the specified string is encoded. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::String& str, int& byteCount) const; + + /** + * Gets the total number of bytes that are required to encode the specified characters. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of bytes + * that are generated when the specified array of characters are encoded. + * @see GetMaxByteCount() + * @see GetByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int& byteCount) const; + + /** + * Gets the total number of bytes that are required to encode a range of characters in the specified Tizen::Base::WcharBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] byteCount The total number of bytes that are required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of bytes + * that are generated when the specified array of characters are encoded. + * @see GetMaxByteCount() + * @see GetByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, + int& byteCount) const; + + /** + * Encodes an instance of specified Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c chars is invalid or empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetCharsN() + * @see GetBytesN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars) const = 0; + + /** + * Encodes the specified string of type Tizen::Base::String to Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the position is zero. + * @param[in] str The string to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c str is invalid or is an empty string. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetString() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::String& str) const = 0; + + /** + * Encodes an instance of specified Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars The buffer containing the character array to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c chars or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method encodes a range of characters in Tizen::Base::WcharBuffer into a range of bytes in Tizen::Base::ByteBuffer. + * @see GetChars() + */ + virtual result GetBytes(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex) const = 0; + + /** + * Encodes an instance of Tizen::Base::String into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] str The string to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c str or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c str. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c str. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetString() + */ + virtual result GetBytes(const Tizen::Base::String& str, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex) const = 0; + + /** + * Gets the total number of characters that are generated by decoding an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] charCount The total number of characters that are generated by decoding a range of bytes in the specified Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of characters + * that are generated when the specified range of bytes are encoded. + * @see GetMaxCharCount() + * @see GetCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int& charCount) const; + + /** + * Gets the total number of characters that are generated by decoding a range of elements specified in the Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] charCount The total number of characters that are generated by decoding a range of bytes in the specified Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of characters + * that are generated when the specified range of bytes are encoded. + * @see GetMaxCharCount() + * @see GetCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte plus one and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c bytes is invalid or empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes) const = 0; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::WcharBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] chars The Tizen::Base::WcharBuffer instance where the resultant decoded data is stored + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or the specified @c chars does not contain sufficient space to store the decoded bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetChars(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, + Tizen::Base::WcharBuffer& chars, int charIndex) const = 0; + + /** + * Gets a string that contains the decoded representation of a range of bytes in the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * + * @see GetBytesN() + * @see GetString() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, Tizen::Base::String& str) const = 0; + + /** + * Gets a string that contains the decoded representation of a range of bytes in the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] index The index from where decoding begins + * @param[in] count The total number of bytes to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + * @see GetString() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, int index, int count, Tizen::Base::String& str) const = 0; + + /** + * Gets the maximum number of bytes that are required to encode the specified number of characters. + * + * @since 2.0 + * + * @return The maximum number of bytes that are required to encode the specified number of characters + * @param[in] charCount The total number of characters to encode + * @remarks This method determines an appropriate buffer size for the byte arrays passed to GetBytes() for encoding. + * @see GetByteCount() + * @see GetBytes() + */ + virtual int GetMaxByteCount(int charCount) const = 0; + + /** + * Gets the maximum number of characters that are generated by decoding the specified number of bytes. + * + * @since 2.0 + * + * @return The maximum number of characters that are generated by decoding the specified number of bytes + * @param[in] byteCount The total number of bytes to encode + * @remarks This method determines an appropriate buffer size for character arrays passed to + * GetChars() or a decoder for encoding. + * @see GetCharCount() + * @see GetChars() + */ + virtual int GetMaxCharCount(int byteCount) const = 0; + + /** + * Gets the encoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Encoder instance for the current encoding + * @remarks Contrary to GetBytes(), an encoder can convert partial sequences of characters into + * partial sequences of bytes by maintaining an appropriate state between the conversions. + * Currently, only UTF-8 encoding supports this method. The other classes return a value of @c null. + * @see GetBytes() + */ + virtual Encoder* GetEncoderN(void) const = 0; + + /** + * Gets the decoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Decoder instance for the current encoding + * @remarks Contrary to GetChars(), a decoder can convert partial sequences of bytes + * into partial sequences of characters by maintaining an appropriate state between the conversions. + * Currently, only UTF-8 encoding supports this method. The other classes return a value of @c null. + * @see GetChars() + */ + virtual Decoder* GetDecoderN(void) const = 0; + + /** + * Gets the encoding type of the current instance. + * + * @since 2.0 + * + * @return An encoding type + */ + virtual Tizen::Base::String GetEncodingType(void) const = 0; + + /** + * Gets an encoding for the UTF-8 format. + * + * @since 2.0 + * + * @return An encoding for the UTF-8 format + * + * @see Tizen::Text::Utf8Encoding + */ + static Utf8Encoding& GetUtf8Encoding(void); + + /** + * Gets an encoding for the UCS-2 format. + * + * @since 2.0 + * + * @return An encoding for the UCS-2 format + -* + * @see Tizen::Text::Ucs2Encoding + */ + static Ucs2Encoding& GetUcs2Encoding(void); + + /** + * Gets an encoding for the GSM format. + * + * @since 2.0 + * + * @return An encoding for the GSM format + * + * @see Tizen::Text::GsmEncoding + */ + static GsmEncoding& GetGsmEncoding(void); + + /** + * Gets an encoding for the Latin1 format. + * + * @since 2.0 + * + * @return An encoding for the Latin1 format + * + * @see Tizen::Text::Latin1Encoding + */ + static Latin1Encoding& GetLatin1Encoding(void); + + /** + * Gets an encoding for the ASCII format. + * + * @since 2.0 + * + * @return An encoding for the ASCII format + * + * @see Tizen::Text::AsciiEncoding + */ + static AsciiEncoding& GetAsciiEncoding(void); + + /** + * Gets an %Encoding instance from the specified encoding type. + * + * @since 2.0 + * + * @return An instance of %Encoding, @n + * else @c null if the method fails + * @param[in] encodingType An encoding type @n + * @exception E_SUCCESS The method is successful. + * @exception E_UNSUPPORTED_TYPE The specified encoding type is not supported. + * @remarks The specific error code can be accessed using the GetLastResult() method. @n + * The supported encoding types are ASCII, GSM, UCS-2, UCS-2LE, UCS-2BE, UCS-4, UCS-4LE, UCS-4BE, UTF-8, UTF-16, UTF-16LE, UTF-16BE, @n + * UTF-32, UTF-32LE, UTF-32BE, ISO-8859-1~16 (except ISO-8859-12), Windows-874, Windows-1250 ~ Windows-1258, @n + * KSC5601, BIG5, GB2312, Shift_JIS and ISO-2022-jp. + * @see Tizen::Text::Encoding::GetAvailableEncodingsN() + */ + static Encoding* GetEncodingN(const Tizen::Base::String& encodingType); + + /** + * Gets the encoding type of the specified %Encoding instance. + * + * @since 2.0 + * + * @return An encoding type + * @param[in] encoding An instance of %Encoding + */ + static Tizen::Base::String GetEncodingType(const Encoding& encoding); + + /** + * Gets a list of all the available encodings. + * + * @since 2.0 + * + * @return A list of Tizen::Base::String instances (ASCII, UTF-8, ISO-8859-1, ISO-8859-2, Windows-1254, and so on), @n + * else @c null if the method fails + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Tizen::Base::Collection::IList* GetAvailableEncodingsN(void); + + /** + * Converts an instance of Tizen::Base::ByteBuffer from one encoding format to another. + * + * @since 2.0 + * + * @return A new buffer for storing the result of the conversion, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last converted byte plus one and the starting position is zero. + * @param[in] src The source of the encoding + * @param[in] dst The destination of the encoding + * @param[in] srcBytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c srcBytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetBytes() + * @see GetChars() + */ + static Tizen::Base::ByteBuffer* ConvertN(const Encoding& src, const Encoding& dst, + const Tizen::Base::ByteBuffer& srcBytes); + + /** + * Converts a range of bytes in the Tizen::Base::ByteBuffer instance from one encoding format to another. + * + * @since 2.0 + * + * @return A new buffer for storing result of the conversion, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last converted byte plus one and the starting position is zero. + * @param[in] src The source of the encoding + * @param[in] dst The destination of the encoding + * @param[in] srcBytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] index The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @param[in] count The total number of bytes to convert + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c srcBytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the specified @c index or @c count is greater than the length of the specified @c srcBytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c index and @c count is greater than the length of the specified @c srcBytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetBytes() + * @see GetChars() + */ + static Tizen::Base::ByteBuffer* ConvertN(const Encoding& src, const Encoding& dst, const Tizen::Base::ByteBuffer& srcBytes, + int index, int count); + +protected: + Encoding(void); + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Encoding_Reserved1(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Encoding_Reserved2(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Encoding_Reserved3(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Encoding_Reserved4(void) { } + + // + // This method is for internal use only. Using this method can cause behavioral, security-related, + // and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void Encoding_Reserved5(void) { } + + friend class _EncodingImpl; + class _EncodingImpl* _pEncodingImpl; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Encoding(const Encoding& encoding); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Encoding& operator =(const Encoding& encoding); + +}; // Encoding + +} } // Tizen::Text + +#endif //_FTEXT_ENCODING_H_ diff --git a/inc/FTextGsmEncoding.h b/inc/FTextGsmEncoding.h new file mode 100644 index 0000000..5749a21 --- /dev/null +++ b/inc/FTextGsmEncoding.h @@ -0,0 +1,447 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextGsmEncoding.h + * @brief This is the header file for the %GsmEncoding class. + * + * This header file contains the declarations of the %GsmEncoding class. + * The %GsmEncoding class is derived from the Encoding class. + */ +#ifndef _FTEXT_GSM_ENCODING_H_ +#define _FTEXT_GSM_ENCODING_H_ + +#include + + +namespace Tizen { namespace Text +{ +/** + * @class GsmEncoding + * @brief This class is an implementation of the GSM character encoding. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %GsmEncoding class is an implementation of the GSM character encoding. + * The Global System for Mobile Communications (GSM) consists of 128 European characters. It supports a 7-bit + * default alphabet extension table for encoding. It is a target-dependent encoding type. + * + * For more information on the class features, see Converting All Text Data at Once. + * + * The following example demonstrates how to use the %GsmEncoding class. + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Text; + * + * void + * MyClass::GsmEncodingSample(void) + * { + * GsmEncoding gsm; + * + * String str(L"GSM Encoding test"); + * + * int byteCount; + * gsm.GetByteCount(str, byteCount); + * + * // Encodes + * ByteBuffer* pBuffer = gsm.GetBytesN(str); + * + * int charCount; + * gsm.GetCharCount(*pBuffer, charCount); + * + * // Decodes + * String decodedStr; + * gsm.GetString(*pBuffer, decodedStr); + * + * if (str.Equals(decodedStr)) + * { + * //.... + * } + * + * delete pBuffer; + * } + * @endcode + */ + +class _OSP_EXPORT_ GsmEncoding + : public Encoding +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + */ + GsmEncoding(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Text::Encoding::~Encoding(). + * + * @since 2.0 + */ + virtual ~GsmEncoding(void); + + /** + * Gets the total number of bytes that are required to encode a specified Tizen::Base::String instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string to encode + * @param[out] byteCount The total number of bytes required to encode the specified string + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c str is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of bytes + * that are generated when the specified string is encoded. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::String& str, int& byteCount) const; + + /** + * Gets the total number of bytes that are required to encode a specified Tizen::Base::WcharBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of bytes + * that are generated when the specified array of characters is encoded. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int& byteCount) const; + + /** + * Gets the total number of bytes that are required to encode a range of characters in the specified Tizen::Base::WcharBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of bytes + * that are generated when the specified array of characters is encoded. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const; + + /** + * Encodes an instance of the specified Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c chars is invalid or empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks The pointer to the Tizen::Base::ByteBuffer instance is not terminated by a @c null character. + * @see GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars) const; + + /** + * Encodes an instance of the specified Tizen::Base::String into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] str A string to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c str is invalid or empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks The pointer to the Tizen::Base::ByteBuffer instance is not terminated by a @c null character. + * @see GetString() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::String& str) const; + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c chars or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method encodes a range of characters in Tizen::Base::WcharBuffer into a range of bytes in Tizen::Base::ByteBuffer. + * @see GetChars() + */ + virtual result GetBytes(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Encodes an instance of Tizen::Base::String into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c str or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c str. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c str. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetString() + */ + virtual result GetBytes(const Tizen::Base::String& str, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Gets the total number of characters that are generated by decoding an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] charCount The total number of characters that are generated by decoding the specified Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of characters + * that are generated when the specified range of bytes are decoded. + * @see GetMaxCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int& charCount) const; + + /** + * Gets the total number of characters that are generated by decoding a range of elements specified in the Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] charCount The total number of characters that are generated by decoding the specified Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the total number of characters + * that are generated when the specified range of bytes are decoded. + * @see GetMaxCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte plus one and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c bytes is invalid or empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer as per the specified range. @n + * The position and limit of the %Tizen::Base::WcharBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] chars The Tizen::Base::WcharBuffer instance where the resultant decoded data is stored + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes or @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or the specified @c chars does not contain sufficient space to store the decoded bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetChars(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, + Tizen::Base::WcharBuffer& chars, int charIndex = 0) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytesN() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, Tizen::Base::String& str) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] index The index from where decoding begins + * @param[in] count The total number of bytes to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, int index, int count, Tizen::Base::String& str) const; + + + /** + * Gets the maximum number of bytes required for encoding the specified number of characters. + * + * @since 2.0 + * + * @return The maximum number of bytes required for encoding the specified number of characters + * @param[in] charCount The total number of characters to encode + * @remarks This method determines an appropriate buffer size for the byte arrays passed to GetBytes() for encoding. + * @see GetByteCount() + */ + virtual int GetMaxByteCount(int charCount) const; + + + /** + * Gets the maximum number of characters that are generated by decoding the specified number of bytes. + * + * @since 2.0 + * + * @return The maximum number of characters that are generated by decoding the specified number of bytes + * @param[in] byteCount The total number of bytes to encode + * @remarks This method determines an appropriate buffer size for character arrays passed to + * GetChars() or a decoder for encoding. + * @see GetByteCount() + */ + virtual int GetMaxCharCount(int byteCount) const; + + + /** + * Gets an encoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Encoder instance for the current encoding + * @remarks Contrary to GetBytes(), an encoder can convert partial sequences of characters into + * partial sequences of bytes by maintaining the appropriate state between the conversions. + * Currently only UTF-8 encoding supports this method. The other classes return a value of @c null. + * @see GetBytes() + */ + virtual Encoder* GetEncoderN(void) const; + + /** + * Gets a decoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Decoder instance for the current encoding + * @remarks Contrary to GetChars(), a decoder can convert partial sequences of bytes + * into partial sequences of characters by maintaining the appropriate state between the conversions. + * Currently only UTF-8 encoding supports this method. The other classes return a value of @c null. + * @see GetChars() + */ + virtual Decoder* GetDecoderN(void) const; + + /** + * Gets the encoding type of the current instance. + * + * @since 2.0 + * + * @return An encoding type + */ + virtual Tizen::Base::String GetEncodingType(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + GsmEncoding(const GsmEncoding& gsmEncoding); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + GsmEncoding& operator =(const GsmEncoding& gsmEncoding); + + friend class _GsmEncodingImpl; + class _GsmEncodingImpl* __pGsmEncodingImpl; +}; + +} } // Tizen::Text +#endif //_FTEXT_GSM_ENCODING_H_ diff --git a/inc/FTextLatin1Encoding.h b/inc/FTextLatin1Encoding.h new file mode 100644 index 0000000..61874d4 --- /dev/null +++ b/inc/FTextLatin1Encoding.h @@ -0,0 +1,372 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextLatin1Encoding.h + * @brief This is the header file for the %Latin1Encoding class. + * + * This header file contains the declarations of the %Latin1Encoding class. + * The %Latin1Encoding class is derived from the Encoding class. + */ +#ifndef _FTEXT_LATIN1_ENCODING_H_ +#define _FTEXT_LATIN1_ENCODING_H_ + +#include + + +namespace Tizen { namespace Text +{ +/** + * @class Latin1Encoding + * @brief This class is an implementation of the Latin1 encoding. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Latin1Encoding class is an implementation of the Latin1 encoding. + * ISO Latin-1 is a superset of the American Standard Code for Information Interchange(ASCII) character set and is very similar to the American National Standards Institute (ANSI) character set used in Windows, + * though the two are not identical. + * Latin1 also serves as the basis for the ANSI character set of MS Windows. + * Only the characters in ISO Latin-1 are guaranteed to be supported on an Internet website. + * When a %Web browser, such as Internet Explorer or Firefox formats a %Web page on a client system, such as + * Windows, it maps the ISO Latin-1 characters as best it can into the default character set. + * + * For more information on the class features, see Converting All Text Data at Once. + * + * The following example demonstrates how to use the %Latin1Encoding class. + + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Text; + * + * void + * MyClass::Latin1EncodingSample(void) + * { + * Latin1Encoding latin1; + * + * String str(L"Latin1Test \u00A1\u00A2"); + * + * int byteCount; + * latin1.GetByteCount(str, byteCount); + * + * // Encodes + * ByteBuffer* pBuffer = latin1.GetBytesN(str); + * + * int charCount; + * latin1.GetCharCount(*pBuffer, charCount); + * + * // Decodes + * String decodedStr; + * latin1.GetString(*pBuffer, decodedStr); + * + * if (str.Equals(decodedStr)) + * { + * //.... + * } + * + * delete pBuffer; + * } + * @endcode + */ + +class _OSP_EXPORT_ Latin1Encoding + : public Encoding +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Latin1Encoding(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Text::Encoding::~Encoding(). + * + * @since 2.0 + */ + virtual ~Latin1Encoding(void); + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c chars is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars) const; + + /** + * Encodes an instance of Tizen::Base::String into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] str A string to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c str is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetString() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::String& str) const; + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method encodes a range of characters in a Tizen::Base::WcharBuffer into a range of bytes in a Tizen::Base::ByteBuffer. + * @see GetChars() + */ + virtual result GetBytes(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Encodes an instance of Tizen::Base::String into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c str or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c str. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c str. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetString() + */ + virtual result GetBytes(const Tizen::Base::String& str, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte plus one and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::WcharBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] chars The Tizen::Base::WcharBuffer instance where the resultant decoded data is stored + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes or @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c chars does not contain sufficient space to store the decoded bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetChars(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, + Tizen::Base::WcharBuffer& chars, int charIndex = 0) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytesN() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, Tizen::Base::String& str) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] index The index from where decoding begins + * @param[in] count The total number of bytes to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, int index, int count, Tizen::Base::String& str) const; + + + /** + * Gets the maximum number of bytes required for encoding a given number of characters. + * + * @since 2.0 + * + * @return The maximum number of bytes required for encoding a given number of characters + * @param[in] charCount The total number of characters to encode + * @remarks This method determines an appropriate buffer size for the byte arrays passed to GetBytes() for encoding. + * @see Encoding::GetByteCount() + */ + virtual int GetMaxByteCount(int charCount) const; + + + /** + * Gets the maximum number of characters that are generated by decoding the specified number of bytes. + * + * @since 2.0 + * + * @return The maximum number of characters generated by decoding the specified number of bytes + * @param[in] byteCount The total number of bytes to encode + * @remarks This method determines an appropriate buffer size for character arrays passed to + * GetChars() or a decoder for encoding. + * @see Encoding::GetByteCount() + */ + virtual int GetMaxCharCount(int byteCount) const; + + + /** + * Gets the encoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Encoder instance for the current encoding + * @remarks Contrary to GetBytes(), an encoder can convert partial sequences of characters into + * partial sequences of bytes by maintaining the appropriate state between the conversions. + * Currently only Utf8Encoding supports this method. Other classes return @c null. + * @see GetBytes() + */ + virtual Encoder* GetEncoderN(void) const; + + /** + * Gets the decoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Decoder instance for the current encoding + * @remarks Contrary to GetChars(), a decoder can convert partial sequences of bytes + * into partial sequences of characters by maintaining the appropriate state between the conversions. + * Currently only Utf8Encoding supports this method. Other classes return @c null. + * @see GetChars() + */ + virtual Decoder* GetDecoderN(void) const; + + /** + * Gets the encoding type of the current instance. + * + * @since 2.0 + * + * @return An encoding type + */ + virtual Tizen::Base::String GetEncodingType(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Latin1Encoding(const Latin1Encoding& latin1Encoding); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Latin1Encoding& operator =(const Latin1Encoding& latin1Encoding); + + friend class _Latin1EncodingImpl; + class _Latin1EncodingImpl* __pLatin1EncodingImpl; +}; + +} } // Tizen::Text +#endif //_FTEXT_LATIN1_ENCODING_H_ diff --git a/inc/FTextUcs2Encoding.h b/inc/FTextUcs2Encoding.h new file mode 100644 index 0000000..40a2c17 --- /dev/null +++ b/inc/FTextUcs2Encoding.h @@ -0,0 +1,477 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextUcs2Encoding.h + * @brief This is the header file for the %Ucs2Encoding class. + * + * This header file contains the declarations of the %Ucs2Encoding class. + * The %Ucs2Encoding class is derived from the Encoding class. + */ +#ifndef _FTEXT_UCS2_ENCODING_H_ +#define _FTEXT_UCS2_ENCODING_H_ + +#include + + +namespace Tizen { namespace Text +{ +/** + * @class Ucs2Encoding + * @brief This class is an implementation of the UCS-2 encoding. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Ucs2Encoding class is an implementation of the UCS-2 encoding. + * Universal Character Set (UCS2) is a two-octet per character encoding type with a fixed width. + * UCS2 prepares several characters in advance to output the needed information fast. + * When printing out characters, users can avail different types of character sets. + * + * For more information on the class features, see Converting All Text Data at Once. + * + * The following example demonstrates how to use the %Ucs2Encoding class. + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Text; + * + * void + * MyClass::Ucs2EncodingSample(void) + * { + * Ucs2Encoding ucs2; + * + * String str(L"(\u03a0) and (\u03a3)"); // sigma and pi + * + * int byteCount; + * ucs2.GetByteCount(str, byteCount); + * + * // Encodes + * ByteBuffer* pBuffer = ucs2.GetBytesN(str); + * + * int charCount; + * ucs2.GetCharCount(*pBuffer, charCount); + * + * // Decodes + * String decodedStr; + * ucs2.GetString(*pBuffer, decodedStr); + * + * if (str.Equals(decodedStr)) + * { + * //.... + * } + * + * delete pBuffer; + * } + * + * @endcode + * + */ + +class _OSP_EXPORT_ Ucs2Encoding + : public Encoding +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Ucs2Encoding(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Text::Encoding::~Encoding(). + * + * @since 2.0 + */ + virtual ~Ucs2Encoding(void); + + /** + * Gets the total number of bytes that are generated by encoding an instance of Tizen::Base::String. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string to encode + * @param[out] byteCount The total number of bytes required to encode the string + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c str is an empty string. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the exact number of bytes + * that are produced if the given string is encoded. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::String& str, int& byteCount) const; + + /** + * Gets the total number of bytes that are generated by encoding an instance of Tizen::Base::WcharBuffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method determines the exact number of bytes + * that are produced if the given array of characters is encoded. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int& byteCount) const; + + /** + * Gets the total number of bytes that are required to encode a range of characters in the specified Tizen::Base::WcharBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks GetByteCount() determines the exact number of bytes + * that are produced if the given array of characters is encoded. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const; + + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c chars is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars) const; + + /** + * Encodes an instance of Tizen::Base::String into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] str A string to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c str is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetString() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::String& str) const; + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks This method encodes a range of characters in a Tizen::Base::WcharBuffer into a range of bytes in a Tizen::Base::ByteBuffer. + * @see GetChars() + */ + virtual result GetBytes(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Encodes an instance of Tizen::Base::String into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c str or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c str. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c str. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetString() + */ + virtual result GetBytes(const Tizen::Base::String& str, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Gets the total number of characters that are generated by decoding an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] charCount The total number of characters that are generated by decoding the specified Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks GetCharCount() determines the exact number of characters + * that are produced if the given range of bytes is converted. + * @see GetMaxCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int& charCount) const; + + /** + * Gets the total number of characters that are generated by decoding a range of elements specified in the Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] charCount The total number of characters that are generated by decoding the specified Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks GetCharCount() determines the exact number of characters + * that are produced if the given range of bytes is converted. + * @see GetMaxCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const; + + /** + *Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte plus one and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c bytes is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::WcharBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] chars The Tizen::Base::WcharBuffer instance where the resultant decoded data is stored + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes or @ chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c chars does not contain sufficient space to store the decoded bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetChars(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, + Tizen::Base::WcharBuffer& chars, int charIndex = 0) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytesN() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, Tizen::Base::String& str) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] index The index from where decoding begins + * @param[in] count The total number of bytes to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytesN() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, int index, int count, Tizen::Base::String& str) const; + + + /** + * Gets the maximum number of bytes required for encoding a given number of characters. + * + * @since 2.0 + * + * @return The maximum number of bytes required for encoding the given number of characters + * @param[in] charCount The total number of characters to encode + * @remarks GetMaxByteCount() determines an appropriate buffer size for the byte arrays passed to GetBytes() for encoding. + * @see GetByteCount() + * @see GetBytes() + */ + virtual int GetMaxByteCount(int charCount) const; + + + /** + * Gets the maximum number of characters that are generated by decoding the specified number of bytes. + * + * @since 2.0 + * + * @return The maximum number of characters generated by decoding the specified number of bytes + * @param[in] byteCount The total number of bytes to encode + * @remarks GetMaxCharCount() determines an appropriate buffer size for the character arrays passed to + * GetChars() or a decoder for encoding. + * @see GetByteCount() + * @see GetChars() + */ + virtual int GetMaxCharCount(int byteCount) const; + + + /** + * Gets the encoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Encoder instance for the current encoding + * @remarks Contrary to GetBytes(), an encoder can convert partial sequences of characters into + * partial sequences of bytes by maintaining the appropriate state between the conversions. + * Currently only Utf8Encoding supports this method. Other classes return @c null. + * @see GetBytes() + */ + virtual Encoder* GetEncoderN(void) const; + + + /** + * Gets the decoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Decoder instance for the current encoding + * @remarks Contrary to GetChars(), a decoder can convert partial sequences of bytes + * into partial sequences of characters by maintaining the appropriate state between the conversions. + * Currently only Utf8Encoding supports this method. Other classes return @c null. + * + * @see GetChars() + */ + virtual Decoder* GetDecoderN(void) const; + + /** + * Gets the encoding type of the current instance. + * + * @since 2.0 + * + * @return An encoding type + */ + virtual Tizen::Base::String GetEncodingType(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Ucs2Encoding(const Ucs2Encoding& ucs2Encoding); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Ucs2Encoding& operator =(const Ucs2Encoding& ucs2Encoding); + + friend class _Ucs2EncodingImpl; + class _Ucs2EncodingImpl* __pUcs2EncodingImpl; +}; + +} } // Tizen::Text +#endif //_FTEXT_UCS2_ENCODING_H_ diff --git a/inc/FTextUtf8Decoder.h b/inc/FTextUtf8Decoder.h new file mode 100644 index 0000000..6037b69 --- /dev/null +++ b/inc/FTextUtf8Decoder.h @@ -0,0 +1,212 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextUtf8Decoder.h + * @brief This is the header file for the %Utf8Decoder class. + * + * This header file contains the declarations of the %Utf8Decoder class. + * + */ +#ifndef _FTEXT_UTF8_DECODER_H_ +#define _FTEXT_UTF8_DECODER_H_ + +#include + + +namespace Tizen { namespace Text +{ +/** + * @class Utf8Decoder + * @brief This class is an implementation of the UTF-8 decoder. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Utf8Decoder class converts blocks of bytes into decoded blocks of characters. + * Universal Transformation Format-8 (UTF-8) is a translated language that is used on the internet. + * It converts the unicode into 8-bit bytes. + * UTF-8 encoding supports all unicode character values and surrogates. + * + * For more information on the class features, see Converting Text Data in Separate Blocks. + * + * The following example demonstrates how to use the %Utf8Decoder class. + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Text; + * + * void + * MyClass::Utf8DecoderSample(void) + * { + * Utf8Decoder utf8De; + * + * // Fills a ByteBuffer with long strings to decode it into the unicode strings + * ByteBuffer* pBB = PrepareUtf8DecoderSample(); + * + * int byteBufSize = pBB->GetCapacity(); + * + * int charCount; + * utf8De.GetCharCount(*pBB, 0, byteBufSize, charCount); + * + * WcharBuffer deChars; + * deChars.Construct(charCount + 1); // for L'\0' + * + * int byteIndex = 0; + * int byteCount = 100; + * + * while (byteIndex < byteBufSize) + * { + * WcharBuffer* pMB = null; + * + * if (byteBufSize - byteIndex < byteCount) + * { + * byteCount = byteBufSize - byteIndex; + * } + * + * // Converts Utf8 to Unicode using Utf8Decoder + * pMB = utf8De.GetCharsN(*pBB, byteIndex, byteCount); + * + * deChars.CopyFrom(*pMB); + * byteIndex += byteCount; + * + * delete pMB; + * } + * + * deChars.Set(L'\0'); + * deChars.Rewind(); + * + * delete pBB; + * } + * @endcode + */ + + +class _OSP_EXPORT_ Utf8Decoder + : public Decoder +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Utf8Decoder(void); + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Text::Decoder::~Decoder(). + * + * @since 2.0 + */ + virtual ~Utf8Decoder(void); + + /** + * Gets the total number of characters that are generated by decoding an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] charCount The total number of characters that are generated by decoding the specified Tizen::Base::ByteBuffer instance + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The conversion has failed due to invalid encoding range. + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount, bool flush = false) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte plus one and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes, bool flush = false) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer as per the specified range. + * + * @since 2.0 + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte and the starting position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The GetCharsN() method maintains state consistency between conversions. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks The pointer to the Tizen::Base::ByteBuffer instance is not terminated by a @c null character. + * + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, + bool flush = false) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Utf8Decoder(const Utf8Decoder& utf8Decoder); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Utf8Decoder& operator =(const Utf8Decoder& utf8Decoder); + + friend class _Utf8DecoderImpl; + class _Utf8DecoderImpl* __pUtf8DecoderImpl; +}; + + +} } // Tizen::Text +#endif //_FTEXT_UTF8_DECODER_H_ diff --git a/inc/FTextUtf8Encoder.h b/inc/FTextUtf8Encoder.h new file mode 100644 index 0000000..dc50a83 --- /dev/null +++ b/inc/FTextUtf8Encoder.h @@ -0,0 +1,221 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextUtf8Encoder.h + * @brief This is the header file for the %Utf8Encoder class. + * + * This header file contains the declarations of the %Utf8Encoder class. + * + */ +#ifndef _FTEXT_UTF8_ENCODER_H_ +#define _FTEXT_UTF8_ENCODER_H_ + +#include +#include + + +namespace Tizen { namespace Text +{ + +/** + * @class Utf8Encoder + * @brief This class is an implementation of the UTF-8 encoder. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Utf8Encoder class converts the blocks of characters into encoded blocks of bytes. + * Universal Transformation Format-8 (UTF-8) is a translated language that is used on the internet. It converts the + * unicode into 8-bit bytes. @n UTF-8 encoding supports all unicode character values and surrogates. + * Note that %Utf8Encoder is not used in reality, because keeping the internal state of encoding from unicode + * to UTF-8 can be avoided if the translation unit is even. + * This means that the real implementation of %Utf8Encoder is the same as that of Utf8Encoding in this state. + * + * For more information on the class features, see Converting Text Data in Separate Blocks. + * + * The following example demonstrates how to use the %Utf8Encoder class. + + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Text; + * + * void + * MyClass::Utf8EncoderSample(void) + * { + * Utf8Encoder utf8En; + * + * // Fills a WcharBuffer with the unicode strings to encode it into UTF8 format bytes. + * WcharBuffer* pMB = PrepareUtf8EncoderSample(); + * + * int charBufSize = pMB->GetCapacity(); + * + * int byteCount = 0; + * utf8En.GetByteCount(*pMB, 0, charBufSize, byteCount); + * + * ByteBuffer enBytes; + * enBytes.Construct(byteCount); + * + * int charIndex = 0; + * int charCount = 100; + * + * while (charIndex < charBufSize) + * { + * ByteBuffer* pBB = null; + * + * if (charBufSize - charIndex < charCount) + * { + * charCount = charBufSize - charIndex; + * } + * + * // Converts Unicode to Utf8 using Utf8Encoder. + * pBB = utf8En.GetBytesN(*pMB, charIndex, charCount); // flush is false + * + * enBytes.CopyFrom(*pBB); + * charIndex += charCount; + * + * delete pBB; + * } + * + * enBytes.SetByte('\0'); + * enBytes.Rewind(); + * + * delete pMB; + * } + * @endcode + */ + + +class _OSP_EXPORT_ Utf8Encoder + : public Encoder +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * + */ + Utf8Encoder(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Text::Encoder::~Encoder(). + * + * @since 2.0 + */ + virtual ~Utf8Encoder(void); + + /** + * Gets the total number of bytes that are required to encode a range of characters in the specified Tizen::Base::WcharBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see Utf8Decoder::GetCharCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, + int charIndex, int charCount, int& byteCount, bool flush = false) const; + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see Utf8Decoder::GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars, bool flush = false) const; + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer as per the specified range. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[in] flush Set to @c true to allow this instance to flush its state at the end of the conversion, @n + * else @c false + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks The pointer to the Tizen::Base::ByteBuffer instance is not terminated by a @c null character. + * @see Utf8Decoder::GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, + bool flush = false) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Utf8Encoder(const Utf8Encoder& utf8Encoder); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Utf8Encoder& operator =(const Utf8Encoder& utf8Encoder); + + friend class _Utf8EncoderImpl; + class _Utf8EncoderImpl* __pUtf8EncoderImpl; +}; + +} } // Tizen::Text +#endif //_FTEXT_UTF8_ENCODER_H_ diff --git a/inc/FTextUtf8Encoding.h b/inc/FTextUtf8Encoding.h new file mode 100644 index 0000000..10035cc --- /dev/null +++ b/inc/FTextUtf8Encoding.h @@ -0,0 +1,472 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextUtf8Encoding.h + * @brief This is the header file for the %Utf8Encoding class. + * + * This header file contains the declarations of the %Utf8Encoding class. + * The %Utf8Encoding class is derived from the Encoding class. + */ +#ifndef _FTEXT_UTF8_ENCODING_H_ +#define _FTEXT_UTF8_ENCODING_H_ + +#include +#include +#include + + +namespace Tizen { namespace Text +{ + +/** + * @class Utf8Encoding + * @brief This class is an implementation of the UTF-8 encoding. + * + * @since 2.0 + * + * @final This class is not intended for extension. + * + * The %Utf8Encoding class is an implementation of the UTF-8 encoding. + * Universal Transformation Format-8 (UTF-8) is a translated language used on the internet. It converts Unicode to 8-bit bytes. UTF-8 encoding supports all the Unicode character values and surrogates. + * + * For more information on the class features, see Converting All Text Data at Once. + * + * The following example demonstrates how to use the %Utf8Encoding class. + + * + * @code + * #include + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Text; + * + * void + * MyClass::Utf8EncodingSample(void) + * { + * Utf8Encoding utf8; + * + * String str(L"(\u03a0) and (\u03a3)"); + * + * int byteCount; + * utf8.GetByteCount(str, byteCount); + * + * // Encodes + * ByteBuffer* pBuffer = utf8.GetBytesN(str); + * + * int charCount; + * utf8.GetCharCount(*pBuffer, charCount); + * + * // Decodes + * String decodedStr; + * utf8.GetString(*pBuffer, decodedStr); + * + * if (str.Equals(decodedStr)) + * { + * //.... + * } + * + * delete pBuffer; + * } + * @endcode + * + */ + + +class _OSP_EXPORT_ Utf8Encoding + : public Encoding +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + Utf8Encoding(void); + + /** + * This is the destructor for this class. @n + * This destructor overrides Tizen::Text::Encoding::~Encoding(). + * + * @since 2.0 + */ + virtual ~Utf8Encoding(void); + + /** + * Gets the total number of bytes that are generated by encoding an instance of specified string. @n + * The GetByteCount() method determines the total number of bytes that are generated when the specified string is encoded. + * + * @since 2.0 + * + * @return An error code + * @param[in] str The string to encode + * @param[out] byteCount The total number of bytes required to encode the string + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c str is an empty string. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::String& str, int& byteCount) const; + + /** + * Gets the total number of bytes that are generated by encoding an instance of specified Tizen::Base::WcharBuffer. @n + * The GetByteCount() method determines the exact number of bytes + * produced if the given array of characters is encoded. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int& byteCount) const; + + /** + * Gets the total number of bytes that are required to encode a range of characters in the specified Tizen::Base::WcharBuffer instance. @n + * The GetByteCount() method determines the total number of bytes that are generated when the specified array of characters is encoded. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] byteCount The total number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const; + + /** + * Encodes an instance of specified Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c chars is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars) const; + + /** + * Encodes an instance of specified Tizen::Base::String into an instance of Tizen::Base::ByteBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::ByteBuffer instance where the resultant encoded string is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last encoded byte plus one and the starting position is zero. + * @param[in] str A string to encode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c str is an empty string. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetString() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::String& str) const; + + /** + * Encodes an instance of Tizen::Base::WcharBuffer into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] chars An instance of Tizen::Base::WcharBuffer to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c chars or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetChars() + */ + virtual result GetBytes(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Encodes an instance of Tizen::Base::String into an instance of Tizen::Base::ByteBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::ByteBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] str A string to encode + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @param[in] charCount The total number of characters to encode + * @param[out] bytes The Tizen::Base::ByteBuffer instance where the resultant encoded string is stored + * @param[in] byteIndex The starting index of the resultant encoding in the Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c str or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c charIndex or @c charCount is greater than the length of the specified @c str. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c str. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetString() + */ + virtual result GetBytes(const Tizen::Base::String& str, int charIndex, int charCount, + Tizen::Base::ByteBuffer& bytes, int byteIndex = 0) const; + + /** + * Gets the total number of characters that are generated by decoding an instance of Tizen::Base::ByteBuffer. @n + * The GetCharCount() method determines the exact number of characters + * produced if the given range of bytes is converted. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] charCount The total number of characters that are generated by decoding the specified Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetMaxCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int& charCount) const; + + /** + * Gets the total number of characters that are generated by decoding a range of elements specified in the Tizen::Base::ByteBuffer instance. @n + * The GetCharCount() method determines the exact number of characters + * produced if the given range of bytes is converted. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] charCount The total number of characters that are generated by decoding the specified Tizen::Base::ByteBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetMaxCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const; + + /** + * Decodes an instance of specified Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer. + * + * @since 2.0 + * + * @return A pointer to the Tizen::Base::WcharBuffer instance where the resultant decoded data is stored, @n + * else @c null if an exception occurs @n + * The buffer limit is the position of the last decoded byte plus one and the position is zero. + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c bytes is empty or invalid. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @see GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes) const; + + /** + * Decodes an instance of Tizen::Base::ByteBuffer into an instance of Tizen::Base::WcharBuffer as per the specified range. @n + * The position and limit of the pointer to the %Tizen::Base::WcharBuffer instance is not changed. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] byteIndex The index from where decoding begins + * @param[in] byteCount The total number of bytes to decode + * @param[out] chars The Tizen::Base::WcharBuffer instance where the resultant decoded data is stored + * @param[in] charIndex The index from where encoding begins in the Tizen::Base::WcharBuffer instance + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes or @c chars is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_OVERFLOW This operation has caused the memory to overflow, or + * the specified @c chars does not contain sufficient space to store the decoded bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetChars(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, + Tizen::Base::WcharBuffer& chars, int charIndex = 0) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytesN() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, Tizen::Base::String& str) const; + + /** + * Gets a string containing the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * + * @since 2.0 + * + * @return An error code + * @param[in] bytes An instance of Tizen::Base::ByteBuffer to decode + * @param[in] index The index from where decoding begins + * @param[in] count The total number of bytes to decode + * @param[out] str A Tizen::Base::String instance @n + * It contains the decoded representation of the specified Tizen::Base::ByteBuffer instance. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of an argument is outside the valid range defined by the method, or + * the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused the memory to underflow, or + * the sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds of the character encoding scheme. + * @see GetBytes() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, int index, int count, Tizen::Base::String& str) const; + + + /** + * Gets the maximum number of bytes required for encoding a given number of characters. + * + * @since 2.0 + * + * @return The maximum number of bytes required for encoding a given number of characters + * @param[in] charCount The total number of characters to encode + * @remarks GetMaxByteCount() determines an appropriate buffer size for the byte arrays passed to GetBytes() for encoding. + * @see GetByteCount() + * @see GetBytes() + */ + virtual int GetMaxByteCount(int charCount) const; + + + /** + * Gets the maximum number of characters that are generated by decoding the specified number of bytes. + * + * @since 2.0 + * + * @return The maximum number of characters generated by decoding the specified number of bytes + * @param[in] byteCount The total number of bytes to encode + * @remarks GetMaxCharCount() determines an appropriate buffer size for the character arrays passed to + * GetChars() or a decoder for encoding. + * @see GetCharCount() + * @see GetChars() + */ + virtual int GetMaxCharCount(int byteCount) const; + + /** + * Gets the encoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Encoder instance for the current encoding + * @remarks Contrary to GetBytes(), an encoder can convert partial sequences of characters into + * partial sequences of bytes by maintaining the appropriate states between the conversions. + * @see GetBytes() + */ + virtual Encoder* GetEncoderN(void) const; + + /** + * Gets the decoder for the current encoding. + * + * @since 2.0 + * + * @return A pointer to the Decoder instance for the current encoding + * @remarks Contrary to GetChars(), a decoder can convert partial sequences of bytes + * into partial sequences of characters by maintaining the appropriate states between the conversions. + * @see GetChars() + */ + virtual Decoder* GetDecoderN(void) const; + + /** + * Gets the encoding type of the current instance. + * + * @since 2.0 + * + * @return An encoding type + */ + virtual Tizen::Base::String GetEncodingType(void) const; + +private: + /** + * The implementation of this copy constructor is intentionally blank and declared as private to + * prohibit copying of objects. + */ + Utf8Encoding(const Utf8Encoding& utf8Encoding); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private + * to prohibit copying of objects. + */ + Utf8Encoding& operator =(const Utf8Encoding& utf8Encoding); + + friend class Utf8Decoder; + friend class _Utf8EncodingImpl; + class _Utf8EncodingImpl* __pUtf8EncodingImpl; +}; + +} } // Tizen::Text +#endif //_FTEXT_UTF8_ENCODING_H_ diff --git a/inc/FXml.h b/inc/FXml.h new file mode 100755 index 0000000..7b67f00 --- /dev/null +++ b/inc/FXml.h @@ -0,0 +1,164 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FXml.h + * @brief This is the header file for the Tizen::Xml namespace. + * + * This header file contains the introduction of the Tizen::Xml namespace. + */ +#ifndef _FXML_H_ +#define _FXML_H_ + +#include +#include +#include + +namespace Tizen +{ +/** + * @if OSPDEPREC + * @namespace Tizen::Xml + * @brief [Deprecated] This namespace contains interfaces to manipulate %XML documents. + * + * @deprecated This namespace is deprecated because Libxml2 open source library is supported by Tizen directly. Instead of using this namespace, use Libxml2 open source library directly. + * + * @since 2.0 + * + * @remarks Include Libxml2 open source library header and use APIs directly without any additional setting. + * + * + * + * + * + * For more information about using Libxml2 open source library, visit http://www.xmlsoft.org + * + * + * @code +// Sample data - map.xml + + + + + United Arab Emirates + Abu Dhabi + + + + Nigeria + Abuja + + + + Ghana + Accra + + + + Pitcairn Islands + Adamstown + + + +// Sample code for XmlSample.h +#include +#include + +class XmlSample : + public Tizen::Ui::Controls::Form +{ +// Construction +public: + XmlSample(void); + ~XmlSample(void); + +public: + virtual result OnInitializing(void); +}; + +// Sample code for XmlSample.cpp +#include +#include "XmlSample.h" + +using namespace Tizen::Base; + +result +XmlSample::OnInitializing(void) +{ + xmlDocPtr pDocument = null; + xmlNodePtr pRoot = null; + xmlNodePtr pCurrentElement = null; + + // Creates a XML document + pDocument = xmlParseFile("/Home/map.xml"); + pRoot = xmlDocGetRootElement(pDocument); + + for(pCurrentElement = pRoot->children; pCurrentElement; pCurrentElement = pCurrentElement->next) + { + String countryName; + xmlNodePtr pChildElement = null; + + if(pCurrentElement->type == XML_ELEMENT_NODE) + { + // Gets the element from the element + pChildElement = pCurrentElement->children->next; + + if(pChildElement) + { + // Gets the content from XML_TEXT_NODE + Tizen::Base::Utility::StringUtil::Utf8ToString ((char*)pChildElement->children->content, countryName); + AppLog("country : %S\n", countryName.GetPointer()); + } + } + } + + xmlFreeDoc(pDocument); + return E_SUCCESS; +} + * @endcode + * @endif + */ + +namespace Xml +{ +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + + +}; // Tizen::Xml +}; // Tizen + +using namespace Tizen::Xml; + +#endif // _FXML_H_ diff --git a/inc/Framework.h b/inc/Framework.h new file mode 100644 index 0000000..b21bcfd --- /dev/null +++ b/inc/Framework.h @@ -0,0 +1,37 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file Framework.h + * @brief This header file contains the declarations of the %Tizen namespace. + * + * This header file contains the declarations and descriptions of the %Tizen namespace. + */ +#ifndef _FRAMEWORK_H_ +#define _FRAMEWORK_H_ +/** + * @namespace Tizen + * @brief This namespace is the root namespace of the %Tizen native framework. + * + * The %Tizen namespace is the top-level namespace that encompasses all other + * C++ namespaces in Tizen. + */ +namespace Tizen +{ + +}; // Tizen + +#endif // _FRAMEWORK_H_ diff --git a/inc/unique_ptr.h b/inc/unique_ptr.h new file mode 100644 index 0000000..e56ed9c --- /dev/null +++ b/inc/unique_ptr.h @@ -0,0 +1,42 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#ifndef _UNIQUE_PTR_H_ +#define _UNIQUE_PTR_H_ + +#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) + +#include + +#else + +#include + +namespace std +{ + +using boost::unique_ptr; +using boost::default_delete; +using boost::move; +using boost::forward; +using boost::swap; + +} + +#endif // __cplusplus || EXPERIMENTAL + +#endif // _UNIQUE_PTR_H_ diff --git a/inc/unique_ptr.hpp b/inc/unique_ptr.hpp new file mode 100644 index 0000000..a1e5c06 --- /dev/null +++ b/inc/unique_ptr.hpp @@ -0,0 +1,536 @@ +/////////////////////////////////////////////////////////////////////////////// +// unique_ptr.hpp header file +// +// Copyright 2009 Howard Hinnant, Ion Gaztañaga. +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// See http://www.boost.org/libs/foreach for documentation + +// This is a C++03 emulation of std::unique_ptr placed in namespace boost. +// Reference http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2800.pdf +// for the latest unique_ptr specification, and +// reference http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html +// for any pending issues against this specification. + +#ifndef _BOOST_UNIQUE_PTR_HPP_ +#define _BOOST_UNIQUE_PTR_HPP_ + +//#include +#include +#include +#include +#include + +namespace boost +{ + +namespace detail_unique_ptr +{ + +typedef char one; +struct two {one _[2];}; + +// An is_convertible that considers From an rvalue (consistent with C++0X). +// This is a simplified version neglecting the types function, array, void and abstract types +// I had to make a special case out of is_convertible to make move-only +// types happy. + +namespace is_conv_imp +{ +template one test1(const T&); +template two test1(...); +template one test2(T); +template two test2(...); +template T source(); +} + +template +struct is_convertible +{ + static const bool value = sizeof(is_conv_imp::test1(is_conv_imp::source())) == 1; +}; + +template +struct is_convertible +{ + static const bool value = sizeof(is_conv_imp::test2(is_conv_imp::source())) == 1; +}; + +template +class rv +{ + T& r_; + +public: + explicit rv(T& r) : r_(r) {} + T* operator->() {return &r_;} + T& operator*() {return r_;} +}; + +template +struct identity +{ + typedef T type; +}; + +} // detail_unique_ptr + +template +inline +typename enable_if_c +< + !detail_unique_ptr::is_convertible >::value, + T& +>::type +move(T& t) +{ + return t; +} + +template +inline +typename enable_if_c +< + !detail_unique_ptr::is_convertible >::value, + const T& +>::type +move(const T& t) +{ + return t; +} + +template +inline +typename enable_if_c +< + detail_unique_ptr::is_convertible >::value, + T +>::type +move(T& t) +{ + return T(detail_unique_ptr::rv(t)); +} + +template +inline +typename enable_if_c +< + is_reference::value, + T +>::type +forward(typename detail_unique_ptr::identity::type t) +{ + return t; +} + +template +inline +typename enable_if_c +< + !is_reference::value, + T +>::type +forward(typename detail_unique_ptr::identity::type& t) +{ + return boost::move(t); +} + +template +inline +typename enable_if_c +< + !is_reference::value, + T +>::type +forward(const typename detail_unique_ptr::identity::type& t) +{ + return boost::move(const_cast(t)); +} + +namespace detail_unique_ptr { + +// A move-aware but stripped-down compressed_pair which only optimizes storage for T2 +template ::value> +class unique_ptr_storage +{ + T1 t1_; + T2 t2_; + + typedef typename add_reference::type T2_reference; + typedef typename add_reference::type T2_const_reference; + + unique_ptr_storage(const unique_ptr_storage&); + unique_ptr_storage& operator=(const unique_ptr_storage&); +public: + operator rv() {return rv(*this);} + + unique_ptr_storage() : t1_(), t2_() {} + + explicit unique_ptr_storage(T1 t1) + : t1_(boost::move(t1)), t2_() {} + + unique_ptr_storage(T1 t1, T2 t2) + : t1_(boost::move(t1)), t2_(boost::forward(t2)) {} + + T1& first() {return t1_;} + const T1& first() const {return t1_;} + + T2_reference second() {return t2_;} + T2_const_reference second() const {return t2_;} +}; + +template +class unique_ptr_storage + : private T2 +{ + T1 t1_; + typedef T2 t2_; + + unique_ptr_storage(const unique_ptr_storage&); + unique_ptr_storage& operator=(const unique_ptr_storage&); +public: + operator rv() {return rv(*this);} + + unique_ptr_storage() : t1_() {} + + explicit unique_ptr_storage(T1 t1) + : t1_(boost::move(t1)) {} + + unique_ptr_storage(T1 t1, T2 t2) + : t2_(boost::move(t2)), t1_(boost::move(t1)) {} + + T1& first() {return t1_;} + const T1& first() const {return t1_;} + + T2& second() {return *this;} + const T2& second() const {return *this;} +}; + +template +inline +void +swap(unique_ptr_storage& x, unique_ptr_storage& y) +{ + using std::swap; + swap(x.first(), y.first()); + swap(x.second(), y.second()); +} + +} // detail_unique_ptr + +template +struct default_delete +{ + default_delete() {} + template + default_delete(const default_delete&, + typename enable_if_c::value>::type* = 0) + {} + + void operator()(T* ptr) const + { + BOOST_STATIC_ASSERT(sizeof(T) > 0); + delete ptr; + } +}; + +template +struct default_delete +{ + void operator()(T* ptr) const + { + BOOST_STATIC_ASSERT(sizeof(T) > 0); + delete [] ptr; + } + +private: + + template void operator()(U*) const; +}; + +namespace detail_unique_ptr +{ + +namespace pointer_type_imp +{ + +template static two test(...); +template static one test(typename U::pointer* = 0); + +} // pointer_type_imp + +template +struct has_pointer_type +{ + static const bool value = sizeof(pointer_type_imp::test(0)) == 1; +}; + +namespace pointer_type_imp +{ + +template ::value> +struct pointer_type +{ + typedef typename D::pointer type; +}; + +template +struct pointer_type +{ + typedef T* type; +}; + +} // pointer_type_imp + +template +struct pointer_type +{ + typedef typename pointer_type_imp::pointer_type::type>::type type; +}; + +} // detail_unique_ptr + +template > +class unique_ptr +{ +public: + typedef T element_type; + typedef D deleter_type; + typedef typename detail_unique_ptr::pointer_type::type pointer; + +private: + detail_unique_ptr::unique_ptr_storage ptr_; + + typedef typename add_reference::type deleter_reference; + typedef typename add_reference::type deleter_const_reference; + + struct nat {int for_bool_;}; + + unique_ptr(unique_ptr&); + unique_ptr& operator=(unique_ptr&); + +public: + operator detail_unique_ptr::rv() {return detail_unique_ptr::rv(*this);} + unique_ptr(detail_unique_ptr::rv r) : ptr_(r->release(), boost::forward(r->get_deleter())) {} + unique_ptr& operator=(detail_unique_ptr::rv r) + { + reset(r->release()); + ptr_.second() = boost::move(r->get_deleter()); + return *this; + } + + unique_ptr() + { + BOOST_STATIC_ASSERT(!is_reference::value); + BOOST_STATIC_ASSERT(!is_pointer::value); + } + + explicit unique_ptr(pointer p) + : ptr_(p) + { + BOOST_STATIC_ASSERT(!is_reference::value); + BOOST_STATIC_ASSERT(!is_pointer::value); + } + + unique_ptr(pointer p, typename mpl::if_, + volatile typename remove_reference::type&, D>::type d) + : ptr_(boost::move(p), boost::forward(const_cast::type>(d))) {} + + template + unique_ptr(unique_ptr u, + typename enable_if_c + < + !boost::is_array::value && + detail_unique_ptr::is_convertible::pointer, pointer>::value && + detail_unique_ptr::is_convertible::value && + ( + !is_reference::value || + is_same::value + ) + >::type* = 0) + : ptr_(u.release(), boost::forward(boost::forward(u.get_deleter()))) {} + + ~unique_ptr() {reset();} + + unique_ptr& operator=(int nat::*) + { + reset(); + return *this; + } + + template + unique_ptr& + operator=(unique_ptr u) + { + reset(u.release()); + ptr_.second() = boost::move(u.get_deleter()); + return *this; + } + + typename add_reference::type operator*() const {return *get();} + pointer operator->() const {return get();} + pointer get() const {return ptr_.first();} + deleter_reference get_deleter() {return ptr_.second();} + deleter_const_reference get_deleter() const {return ptr_.second();} + operator int nat::*() const {return get() ? &nat::for_bool_ : 0;} + + void reset(pointer p = pointer()) + { + pointer t = get(); + if (t != pointer()) + get_deleter()(t); + ptr_.first() = p; + } + + pointer release() + { + pointer tmp = get(); + ptr_.first() = pointer(); + return tmp; + } + + void swap(unique_ptr& u) {detail_unique_ptr::swap(ptr_, u.ptr_);} +}; + +template +class unique_ptr +{ +public: + typedef T element_type; + typedef D deleter_type; + typedef typename detail_unique_ptr::pointer_type::type pointer; + +private: + detail_unique_ptr::unique_ptr_storage ptr_; + + typedef typename add_reference::type deleter_reference; + typedef typename add_reference::type deleter_const_reference; + + struct nat {int for_bool_;}; + + unique_ptr(unique_ptr&); + unique_ptr& operator=(unique_ptr&); + +public: + operator detail_unique_ptr::rv() {return detail_unique_ptr::rv(*this);} + unique_ptr(detail_unique_ptr::rv r) : ptr_(r->release(), boost::forward(r->get_deleter())) {} + unique_ptr& operator=(detail_unique_ptr::rv r) + { + reset(r->release()); + ptr_.second() = boost::move(r->get_deleter()); + return *this; + } + + unique_ptr() + { + BOOST_STATIC_ASSERT(!is_reference::value); + BOOST_STATIC_ASSERT(!is_pointer::value); + } + + explicit unique_ptr(pointer p) + : ptr_(p) + { + BOOST_STATIC_ASSERT(!is_reference::value); + BOOST_STATIC_ASSERT(!is_pointer::value); + } + + unique_ptr(pointer p, typename mpl::if_, + volatile typename remove_reference::type&, D>::type d) + : ptr_(boost::move(p), boost::forward(const_cast::type>(d))) {} + + ~unique_ptr() {reset();} + + T& operator[](size_t i) const {return get()[i];} + pointer get() const {return ptr_.first();} + deleter_reference get_deleter() {return ptr_.second();} + deleter_const_reference get_deleter() const {return ptr_.second();} + operator int nat::*() const {return get() ? &nat::for_bool_ : 0;} + + void reset(pointer p = pointer()) + { + pointer t = get(); + if (t != pointer()) + get_deleter()(t); + ptr_.first() = p; + } + + pointer release() + { + pointer tmp = get(); + ptr_.first() = pointer(); + return tmp; + } + + void swap(unique_ptr& u) {detail_unique_ptr::swap(ptr_, u.ptr_);} +private: + template + explicit unique_ptr(U, + typename enable_if_c::value>::type* = 0); + + template + unique_ptr(U, typename mpl::if_, + volatile typename remove_reference::type&, D>::type, + typename enable_if_c::value>::type* = 0); +}; + +template +inline +void +swap(unique_ptr& x, unique_ptr& y) +{ + x.swap(y); +} + +template +inline +bool +operator==(const unique_ptr& x, const unique_ptr& y) +{ + return x.get() == y.get(); +} + +template +inline +bool +operator!=(const unique_ptr& x, const unique_ptr& y) +{ + return !(x == y); +} + +template +inline +bool +operator<(const unique_ptr& x, const unique_ptr& y) +{ + return x.get() < y.get(); +} + +template +inline +bool +operator<=(const unique_ptr& x, const unique_ptr& y) +{ + return !(y < x); +} + +template +inline +bool +operator>(const unique_ptr& x, const unique_ptr& y) +{ + return y < x; +} + +template +inline +bool +operator>=(const unique_ptr& x, const unique_ptr& y) +{ + return !(x < y); +} + +} // boost + +#endif // _BOOST_UNIQUE_PTR_HPP_ diff --git a/osp-appfw.manifest b/osp-appfw.manifest new file mode 100644 index 0000000..11cea5f --- /dev/null +++ b/osp-appfw.manifest @@ -0,0 +1,16 @@ + + + + + + + + + + diff --git a/osp-appfw.pc.in b/osp-appfw.pc.in new file mode 100755 index 0000000..c064287 --- /dev/null +++ b/osp-appfw.pc.in @@ -0,0 +1,13 @@ +# Package Information for pkg-config + +prefix=@PREFIX@ +exec_prefix=/usr +libdir=/usr/lib/osp +includedir=/usr/include/osp + +Name: @PC_NAME@ +Description: @PACKAGE_DESCRIPTION@ +Version: @VERSION@ +Requires: @PC_REQUIRED@ +Libs: -L${libdir} @PC_LDFLAGS@ +Cflags: -I${includedir} \ No newline at end of file diff --git a/packaging/osp-appfw.spec b/packaging/osp-appfw.spec new file mode 100755 index 0000000..c72b0b3 --- /dev/null +++ b/packaging/osp-appfw.spec @@ -0,0 +1,226 @@ +%define debug_package %{nil} +%define __strip /bin/true + +Name: osp-appfw +Summary: The App Framework library of OSP +Version: 1.2.0.0 +Release: 1 +Group: TO_BE/FILLED_IN +License: Apache License, Version 2.0 or Flora +Source0: %{name}-%{version}.tar.gz +BuildRequires: cmake +BuildRequires: pkgconfig(capi-appfw-application) +BuildRequires: pkgconfig(capi-appfw-app-manager) +BuildRequires: pkgconfig(capi-appfw-package-manager) +BuildRequires: pkgconfig(capi-content-mime-type) +BuildRequires: pkgconfig(capi-location-manager) +BuildRequires: pkgconfig(capi-media-sound-manager) +BuildRequires: pkgconfig(capi-network-connection) +BuildRequires: pkgconfig(capi-network-serial) +BuildRequires: pkgconfig(capi-network-tethering) +BuildRequires: pkgconfig(capi-network-wifi) +BuildRequires: pkgconfig(capi-network-bluetooth) +BuildRequires: pkgconfig(capi-system-device) +BuildRequires: pkgconfig(capi-system-info) +BuildRequires: pkgconfig(capi-system-power) +BuildRequires: pkgconfig(capi-system-sensor) +BuildRequires: pkgconfig(capi-system-system-settings) +BuildRequires: pkgconfig(capi-system-runtime-info) +BuildRequires: pkgconfig(capi-telephony-network-info) +BuildRequires: pkgconfig(capi-telephony-sim) +BuildRequires: pkgconfig(alarm-service) +BuildRequires: pkgconfig(appsvc) +BuildRequires: pkgconfig(aul) +BuildRequires: pkgconfig(bundle) +BuildRequires: pkgconfig(chromium) +BuildRequires: pkgconfig(dbus-1) +BuildRequires: pkgconfig(dbus-glib-1) +BuildRequires: pkgconfig(devman) +BuildRequires: pkgconfig(dlog) +BuildRequires: pkgconfig(ecore) +BuildRequires: pkgconfig(glib-2.0) +BuildRequires: pkgconfig(heynoti) +BuildRequires: pkgconfig(icu-i18n) +BuildRequires: pkgconfig(libcurl) +BuildRequires: pkgconfig(libpcre) +BuildRequires: pkgconfig(libssl) +BuildRequires: pkgconfig(libsoup-2.4) +BuildRequires: pkgconfig(libwbxml2) +BuildRequires: pkgconfig(minizip) +BuildRequires: pkgconfig(notification) +BuildRequires: pkgconfig(openssl) +BuildRequires: pkgconfig(pkgmgr) +BuildRequires: pkgconfig(pkgmgr-info) +BuildRequires: pkgconfig(pmapi) +BuildRequires: pkgconfig(libprivilege-control) +BuildRequires: pkgconfig(sensor) +BuildRequires: pkgconfig(sqlite3) +BuildRequires: pkgconfig(uuid) +BuildRequires: pkgconfig(vconf) +BuildRequires: pkgconfig(wifi-direct) +BuildRequires: pkgconfig(zlib) +BuildRequires: pkgconfig(drm-service-core-intel) +#BuildRequires: drm-service-core-intel-devel +BuildRequires: pkgconfig(tapi) +BuildRequires: pkgconfig(haptic) +BuildRequires: pkgconfig(sysman) +BuildRequires: pkgconfig(x11) +BuildRequires: boost-devel +BuildRequires: gettext-tools +BuildRequires: libcryptsvc-devel +BuildRequires: dukgenerator + +# runtime requires +Requires: capi-appfw-app-manager +Requires: capi-appfw-application +Requires: capi-appfw-package-manager +Requires: capi-content-mime-type +Requires: capi-location-manager +Requires: capi-media-sound-manager +Requires: capi-network-connection +Requires: capi-network-serial +Requires: capi-network-tethering +Requires: capi-network-wifi +Requires: capi-system-device +Requires: capi-system-info +Requires: capi-system-power +Requires: capi-system-sensor +Requires: capi-system-system-settings +Requires: capi-system-runtime-info +Requires: capi-telephony-sim +Requires: chromium +Requires: osp-env-config +#Requires: drm-service-core-intel +Requires: sqlite +Requires: libcryptsvc-devel + +Provides: libosp-appfw.so.1 + +Requires(post): /sbin/ldconfig +Requires(post): coreutils +Requires(postun): /sbin/ldconfig + +%description +The App Framework library of OSP + +%package devel +Summary: The App Framework library of OSP (Development) +Group: TO_BE/FILLED_IN +Requires: %{name} = %{version}-%{release} +Requires: boost-devel +Requires: pkgconfig(pkgmgr-info) + +%description devel +The App Framework library of OSP (DEV) + +%package internal-devel +Summary: osp app framework internel (Internal) +Group: TO_BE/FILLED_IN +Requires: %{name} = %{version}-%{release} + +%description internal-devel +The App Framework library of OSP (Internal-DEV) + +%package debug +Summary: The App Framework library of OSP (Development) +Group: TO_BE/FILLED_IN +Requires: %{name} = %{version}-%{release} + +%description debug +The App Framework library of OSP (DEV) + +%prep +%setup -q + +%build +MAJORVER=`echo %{version} | awk 'BEGIN {FS="."}{print $1}'` +%ifarch %{ix86} +CXXFLAGS="$CXXFLAGS -D_OSP_DEBUG_ -D_OSP_X86_ -D_OSP_EMUL_" cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} -DOBS=1 -DFULLVER=%{version} -DMAJORVER=${MAJORVER} -DARCH=x86 +%else +CXXFLAGS="-O2 -g -pipe -Wall -fno-exceptions -Wformat -Wformat-security -Wl,--as-needed -fmessage-length=0 -march=armv7-a -mtune=cortex-a8 -mlittle-endian -mfpu=neon -mfloat-abi=softfp -D__SOFTFP__ -mthumb -Wa,-mimplicit-it=thumb -funwind-tables -D_OSP_DEBUG_ -D_OSP_ARMEL_" cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} -DOBS=1 -DFULLVER=%{version} -DMAJORVER=${MAJORVER} -DARCH=arm +%endif + +# Call make instruction with smp support +make %{?jobs:-j%jobs} + +%install +rm -rf %{buildroot} +mkdir -p %{buildroot}/usr/share/license +cp %{_builddir}/%{name}-%{version}/LICENSE.Flora %{buildroot}/usr/share/license/%{name} +cp %{_builddir}/%{name}-%{version}/LICENSE.APLv2 %{buildroot}/usr/share/license/%{name} + +%make_install + +%post +/bin/rm -f /etc/ld.so.cache +/sbin/ldconfig + +mkdir -p /opt/usr/share/.osp-compat/share/AppControl +mkdir -p /opt/usr/share/.osp-compat/share2 +mkdir -p /opt/usr/share/certs/rootcert +mkdir -p /opt/usr/share/certs/usercert/key +mkdir -p /opt/usr/etc +mkdir -p /opt/usr/media/Images +mkdir -p /opt/usr/media/Others +mkdir -p /opt/usr/media/Sounds +mkdir -p /opt/usr/media/Videos +mkdir -p /opt/usr/media/Camera + + +mkdir -p /tmp/osp + +if [ -f /usr/lib/rpm-plugins/msm.so ] +then + chsmack -a "osp::compat" /opt/usr/share/.osp-compat/share/AppControl + chsmack -t /opt/usr/share/.osp-compat/share/AppControl + chsmack -a "osp::root-certs" /opt/usr/share/certs/rootcert + chsmack -t /opt/usr/share/certs/rootcert + chsmack -a "osp::root-certs" /opt/usr/share/certs/rootcert + chsmack -t /opt/usr/share/certs/rootcert + chsmack -a "osp::user-certs" /opt/usr/share/certs/usercert + chsmack -t /opt/usr/share/certs/usercert + chsmack -a "osp::user-certs" /opt/usr/share/certs/usercert/key + chsmack -t /opt/usr/share/certs/usercert/key + chsmack -a "*" /opt/usr/media/* + chsmack -t /opt/usr/media/* + chsmack -a "*" /tmp/osp + chsmack -t /tmp/osp +fi + +chmod -R 707 /opt/usr/share/.osp-compat/share/AppControl +chmod -R 705 /opt/usr/share/certs +chmod -R 700 /opt/usr/share/certs/usercert/key +chmod -R 777 /opt/usr/media +chmod -R 777 /tmp/osp + +chown -R 5000:5000 /opt/usr/media + +%postun -p /sbin/ldconfig + +%files +%manifest osp-appfw.manifest +/usr/share/license/%{name} +/etc/* +/opt/usr/share/.osp-compat/share/* +/opt/usr/etc/* +/usr/share/locale/* +/usr/etc/* +%{_libdir}/osp/libosp-appfw.so* + +%files devel +%{_includedir}/osp/*.h +%{_includedir}/osp/*.hpp +%{_libdir}/pkgconfig/osp-appfw.pc + +%files internal-devel +%{_includedir}/osp/app/* +%{_includedir}/osp/base/* +%{_includedir}/osp/io/* +%{_includedir}/osp/locales/* +%{_includedir}/osp/security/* +%{_includedir}/osp/system/* +%{_includedir}/osp/text/* + +%files debug +%{_libdir}/osp/debug/libosp-appfw.so* + diff --git a/res/arm/usr/etc/media-capability.xml b/res/arm/usr/etc/media-capability.xml new file mode 100755 index 0000000..94548e3 --- /dev/null +++ b/res/arm/usr/etc/media-capability.xml @@ -0,0 +1,172 @@ + + + + + 8000 + 11025 + 22050 + 32000 + 44100 + 48000 + + + PCM_U8 + PCM_S16_LE + + + + + 16 + + 8000 + 11025 + 22050 + 32000 + 44100 + 48000 + + + PCM_U8 + PCM_S16_LE + + + + + + AMR + WAV + AAC + 3GP + MP4 + + + LPCM + AMR + AAC + + + WAV + AMR + AAC + 3GP + MP4 + + + + + 2 + + + Back + 90 + + 0 + 90 + 180 + 270 + + + Digital + + + None + Horizontal + Vertical + + + Normal + Macro + ContinuousAuto + + 1 + + + + Front + 270 + + 0 + 90 + 180 + 270 + + + Digital + + + None + Horizontal + Vertical + + + + + 0 + + + + + + MP3 + AAC + AAC+ + EAAC+ + AMR-NB + WMA + MIDI + PCM + + 8 + + RTSP + HTTP + + + MPEG4 + H.263 + H.264 + VC-1 + + 720 + 1280 + + + + + VIDEO_CODEC_MPEG4SP + VIDEO_CODEC_H263 + + + + MP4 + 3GP + + + + AMR + AAC + + + + MPEG4SP + H.263 + + + + AMR + LPCM + AAC + + + + MPG4 + H263 + + + + 3GP + MP4 + + + + diff --git a/res/arm/usr/etc/system-info.ini b/res/arm/usr/etc/system-info.ini new file mode 100644 index 0000000..c129e9d --- /dev/null +++ b/res/arm/usr/etc/system-info.ini @@ -0,0 +1,26 @@ +#SystemInfo +WACVersion= +OverlayRegionHeightUnit=2 +OverlayRegionWidthUnit=2 +MaxOverlayRegionCount=8 +http://tizen.org/feature/screen.size.normal=true +http://tizen.org/feature/screen.size.large=false +http://tizen.org/feature/screen.coordinate_system.size.normal=true +http://tizen.org/feature/screen.coordinate_system.size.large=false +http://tizen.org/feature/screen.coordinate_system.physical.normal_480x800=false +http://tizen.org/feature/screen.coordinate_system.physical.normal_720x1280=true +http://tizen.org/feature/screen.coordinate_system.physical.large_480x800=false +http://tizen.org/feature/screen.coordinate_system.physical.large_720x1280=false +http://tizen.org/feature/screen.coordinate_system.logical.normal=true +http://tizen.org/feature/screen.coordinate_system.logical.large=false +http://tizen.org/feature/platform.native.api.version=2.0 +http://tizen.org/feature/platform.web.api.version=2.0 +#UiControlInfo +OverlayRegionHeightUnit=2 +OverlayRegionWidthUnit=2 +MaxOverlayRegionCount=8 +OverlayRegionBufferPixelFormat=ARGB8888/RGB565/YCbCr420P/NV12/UYVY +OverlayDstMinWidth=16 +OverlayDstMinHeight=8 +OverlaySrcMinWidth=16 +OverlaySrcMinHeight=8 diff --git a/res/common/etc/ld.so.conf.d/osp.conf b/res/common/etc/ld.so.conf.d/osp.conf new file mode 100755 index 0000000..fe57d89 --- /dev/null +++ b/res/common/etc/ld.so.conf.d/osp.conf @@ -0,0 +1 @@ +/usr/lib/osp diff --git a/res/common/opt/usr/etc/system-log.ini b/res/common/opt/usr/etc/system-log.ini new file mode 100755 index 0000000..945462b --- /dev/null +++ b/res/common/opt/usr/etc/system-log.ini @@ -0,0 +1,55 @@ +#Suppression +SUPPRESSION= + +#Application +INFO=YES +DEBUG=YES +EXCEPTION=YES + +#Platform +INFO=YES +EXCEPTION=YES + +#PlatformModules +NID_APP=YES +NID_BASE=YES +NID_BASE_COL=YES +NID_BASE_RT=YES +NID_BASE_UTIL=YES +NID_CNT=YES +NID_CTXT=YES +NID_GRP=YES +NID_IO=YES +NID_LCL=YES +NID_LOC=YES +NID_LOC_CTRL=YES +NID_LOC_SVC=YES +NID_MEDIA=YES +NID_MSG=YES +NID_NET=YES +NID_NET_BT=YES +NID_NET_HTTP=YES +NID_NET_NFC=YES +NID_NET_SOCK=YES +NID_NET_WIFI=YES +NID_SEC=YES +NID_SEC_CERT=YES +NID_SEC_CRYPTO=YES +NID_SCL=YES +NID_SYS=YES +NID_TEL=YES +NID_TEXT=YES +NID_UI=YES +NID_UI_ANIM=YES +NID_UI_CTRL=YES +NID_UI_EFFECT=YES +NID_UI_IME=YES +NID_UI_SCENES=YES +NID_UIX=YES +NID_UIX_SPEECH=YES +NID_WEB=YES +NID_WEB_CTRL=YES +NID_WEB_JSON=YES +NID_TEST=YES +RESERVED=NO + diff --git a/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestEvent.vcs b/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestEvent.vcs new file mode 100755 index 0000000..15eb7e1 --- /dev/null +++ b/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestEvent.vcs @@ -0,0 +1,11 @@ +BEGIN:VCALENDAR +VERSION:1.0 +BEGIN:VEVENT +SUMMARY;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:Event +DESCRIPTION;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:Event Viewer Test +DTSTART:20100120T020000Z +DTEND:20100120T030000Z +LAST-MODIFIED:20100120T022156Z +CATEGORIES:MEETING +END:VEVENT +END:VCALENDAR diff --git a/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestMemo.vnt b/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestMemo.vnt new file mode 100755 index 0000000..ce8bdb7 --- /dev/null +++ b/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestMemo.vnt @@ -0,0 +1,6 @@ +BEGIN:VNOTE +VERSION:1.1 +BODY;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:Memotest +DCREATED:20110102T055700 +LAST-MODIFIED:20110102T055742 +END:VNOTE diff --git a/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestTodo.vcs b/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestTodo.vcs new file mode 100755 index 0000000..5cc8373 --- /dev/null +++ b/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-calendar/TestTodo.vcs @@ -0,0 +1,12 @@ +BEGIN:VCALENDAR +VERSION:1.0 +BEGIN:VTODO +SUMMARY;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:Task +DESCRIPTION;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:Task Viewer Test +DTSTART:20100109T050000Z +DUE:20100110T000000Z +PRIORITY:3 +STATUS:NEEDS ACTION +LAST-MODIFIED:20100110T212057Z +END:VTODO +END:VCALENDAR diff --git a/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-contact/TestContact.vcf b/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-contact/TestContact.vcf new file mode 100755 index 0000000..dbab149 --- /dev/null +++ b/res/common/opt/usr/share/.osp-compat/share/AppControl/ac-contact/TestContact.vcf @@ -0,0 +1,9 @@ +BEGIN:VCARD +N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:Anderson;Thomas;;; +FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:Thomas Anderson +VERSION:2.1 +TEL;CELL; MOBILE; VOICE:01000010001 +TEL;HOME; VOICE:0285634127 +EMAIL;WORK; INTERNET;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:tom@bada.com +REV:20110103T132410 +END:VCARD diff --git a/res/common/usr/etc/content-download.ini b/res/common/usr/etc/content-download.ini new file mode 100644 index 0000000..ac6c21a --- /dev/null +++ b/res/common/usr/etc/content-download.ini @@ -0,0 +1,2 @@ +#DownloadCount +Max=5 diff --git a/res/x86/usr/etc/media-capability.xml b/res/x86/usr/etc/media-capability.xml new file mode 100755 index 0000000..c9f9b2c --- /dev/null +++ b/res/x86/usr/etc/media-capability.xml @@ -0,0 +1,154 @@ + + + + + 8000 + 11025 + 22050 + 32000 + 44100 + 48000 + + + PCM_U8 + PCM_S16_LE + + + + + 16 + + 8000 + 11025 + 22050 + 32000 + 44100 + 48000 + + + PCM_U8 + PCM_S16_LE + + + + + + AMR + WAV + AAC + 3GP + MP4 + + + LPCM + AMR + AAC + + + WAV + AMR + AAC + 3GP + MP4 + + + + + 2 + + + Back + 90 + + + + + + + + + + 0 + + + + Front + 270 + + + + + + + + + + 0 + + + + + + MP3 + AAC + AAC+ + EAAC+ + AMR-NB + WMA + MIDI + PCM + + 8 + + RTSP + HTTP + + + MPEG4 + H.263 + H.264 + VC-1 + + 720 + 1280 + + + + + VIDEO_CODEC_MPEG4SP + VIDEO_CODEC_H263 + + + + MP4 + 3GP + + + + AMR + AAC + + + + MPEG4SP + H.263 + + + + AMR + LPCM + AAC + + + + MPG4 + H263 + + + + 3GP + MP4 + + + + diff --git a/res/x86/usr/etc/system-info.ini b/res/x86/usr/etc/system-info.ini new file mode 100644 index 0000000..024441d --- /dev/null +++ b/res/x86/usr/etc/system-info.ini @@ -0,0 +1,26 @@ +#SystemInfo +WACVersion= +OverlayRegionHeightUnit=1 +OverlayRegionWidthUnit=1 +MaxOverlayRegionCount=8 +http://tizen.org/feature/screen.size.normal=true +http://tizen.org/feature/screen.size.large=false +http://tizen.org/feature/screen.coordinate_system.size.normal=true +http://tizen.org/feature/screen.coordinate_system.size.large=false +http://tizen.org/feature/screen.coordinate_system.physical.normal_480x800=false +http://tizen.org/feature/screen.coordinate_system.physical.normal_720x1280=true +http://tizen.org/feature/screen.coordinate_system.physical.large_480x800=false +http://tizen.org/feature/screen.coordinate_system.physical.large_720x1280=false +http://tizen.org/feature/screen.coordinate_system.logical.normal=true +http://tizen.org/feature/screen.coordinate_system.logical.large=false +http://tizen.org/feature/platform.native.api.version=2.0 +http://tizen.org/feature/platform.web.api.version=2.0 +#UiControlInfo +OverlayRegionHeightUnit=1 +OverlayRegionWidthUnit=1 +MaxOverlayRegionCount=8 +OverlayRegionBufferPixelFormat=ARGB8888/RGB565/YCbCr420P/NV12/UYVY +OverlayDstMinWidth=16 +OverlayDstMinHeight=8 +OverlaySrcMinWidth=16 +OverlaySrcMinHeight=8 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..60e1855 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,51 @@ +SET(SLP_INCLUDE_DIRS + /usr/include + /usr/include/vconf + /usr/include/glib-2.0 + /usr/lib/glib-2.0/include + /usr/include/dbus-1.0 + /usr/lib/dbus-1.0/include + /usr/include/dlog + /usr/include/appfw + /usr/include/aul + /usr/include/notification + /usr/include/heynoti + /usr/include/sensor + /usr/include/media + /usr/include/devman + /usr/include/network + /usr/include/libxml2 + /usr/include/content + /usr/include/system + /usr/include/location + /usr/include/libsoup-2.4 + /usr/include/pkgmgr + /usr/include/telephony + /usr/include/curl + /usr/include/minizip + /usr/include/chromium + /usr/include/wifi-direct + /usr/include/drm-intel + /usr/include/telephony-client + /usr/include/haptic + /usr/include/sysman + /usr/include/ecore-1 + /usr/include/eina-1 + /usr/include/eina-1/eina +) + + +## Add SubModules +ADD_SUBDIRECTORY(osp-string) +ADD_SUBDIRECTORY(newlib-compat) +ADD_SUBDIRECTORY(app) +ADD_SUBDIRECTORY(io) +ADD_SUBDIRECTORY(base) +ADD_SUBDIRECTORY(locales) +ADD_SUBDIRECTORY(security) +ADD_SUBDIRECTORY(system) +ADD_SUBDIRECTORY(text) +ADD_SUBDIRECTORY(appfw) + + + diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt new file mode 100644 index 0000000..dc33998 --- /dev/null +++ b/src/app/CMakeLists.txt @@ -0,0 +1,82 @@ +SET (this_target app) + +INCLUDE_DIRECTORIES ( + ${SLP_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/inc + ${CMAKE_SOURCE_DIR}/src/base/inc + ${CMAKE_SOURCE_DIR}/src/io/inc + ${CMAKE_SOURCE_DIR}/src/system/inc + ${CMAKE_SOURCE_DIR}/src/security/inc + inc + ) + +SET (${this_target}_SOURCE_FILES + package/FAppPkgPackageAppInfo.cpp + package/FAppPkgPackageInfo.cpp + package/FAppPkgPackageManager.cpp + package/FAppPkg_PackageAppInfoImpl.cpp + package/FAppPkg_PackageInfoImpl.cpp + package/FAppPkg_PackageManagerImpl.cpp + FAppApp.cpp + FApp_AppImpl.cpp + FAppServiceApp.cpp + FApp_ServiceAppImpl.cpp + FApp_Aul.cpp + FAppAppManager.cpp + FApp_AppManagerImpl.cpp + FApp_AppManagerProxy.cpp + FApp_ConditionManagerProxy.cpp + FApp_PackageManagerProxy.cpp + FApp_NotificationManagerProxy.cpp + FAppAppRegistry.cpp + FApp_AppRegistryImpl.cpp + FAppAppResource.cpp + FApp_AppResourceImpl.cpp + FApp_AppResourceString.cpp + FAppAppControl.cpp + FApp_AppControlImpl.cpp + FApp_AppControlRegistry.cpp + FApp_AppControlEvent.cpp + FApp_AppControlEventArg.cpp + FApp_AppEntry.cpp + FApp_AppInfo.cpp + FApp_AppArg.cpp + FAppNotificationManager.cpp + FApp_NotificationManagerImpl.cpp + FAppNotificationMessage.cpp + FApp_NotificationMessageImpl.cpp + FApp_AppManagerIpcMessage.cpp + FApp_ConditionManagerIpcMessages.cpp + FApp_PackageManagerIpcMessages.cpp + FApp_NotificationManagerIpcMessages.cpp + FApp_AppLaunchCondition.cpp + FApp_AppLaunchConditionHandlerBase.cpp + FAppSqlDataControl.cpp + FApp_SqlDataControlImpl.cpp + FAppMapDataControl.cpp + FApp_MapDataControlImpl.cpp + FApp_AppManagerEvent.cpp + FAppDataControlProviderManager.cpp + FApp_DataControlProviderManagerImpl.cpp + FAppAppControlProviderManager.cpp + FApp_AppControlProviderManagerImpl.cpp + FApp_AppControlManager.cpp + FApp_AppMessageImpl.cpp + FAppAppSetting.cpp + FApp_AppSettingImpl.cpp + FApp_LongevityManager.cpp + ) + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_SINGLETON_CLEANUP -fvisibility=hidden") +## SET EXTRA COMPILER FLAGS +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fPIC" ) +#SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fstack-protector -Wstack-protector" } + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} STATIC ${${this_target}_SOURCE_FILES}) diff --git a/src/app/FAppApp.cpp b/src/app/FAppApp.cpp new file mode 100644 index 0000000..49d080a --- /dev/null +++ b/src/app/FAppApp.cpp @@ -0,0 +1,192 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppApp.cpp + * @brief This is the implementation for the App class. + */ + +#include +#include +#include +#include +#include + +#include +#include "FApp_AppInfo.h" +#include "FApp_AppImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +App::App(void) +{ + __pAppImpl = new (std::nothrow) _AppImpl(this); + SysAssertf(__pAppImpl != null, "Allocating memory for App instance failed."); + SysTryReturnVoidResult(NID_APP, __pAppImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); +} + +App::~App(void) +{ + delete __pAppImpl; +} + +AppRegistry* +App::GetAppRegistry(void) const +{ + return AppRegistry::GetInstance(); +} + +AppResource* +App::GetAppResource(void) const +{ + return AppResource::GetInstance(); +} + +IList* +App::GetAppArgumentListN(void) const +{ + SysAssertf(__pAppImpl != null, "Getting App instance failed."); + + return __pAppImpl->GetAppArgumentListN(); +} + +AppState +App::GetAppState(void) const +{ + return _AppInfo::GetAppState(); +} + +String +App::GetAppName(void) const +{ + if (_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat()) + { + return _AppInfo::GetAppName(); + } + else + { + return _AppInfo::GetAppExecutableName(); + } +} + +String +App::GetAppDisplayName(void) const +{ + return _AppInfo::GetAppName(); +} + +String +App::GetAppVersion(void) const +{ + return _AppInfo::GetAppVersion(); +} + +AppId +App::GetAppId(void) const +{ + return _AppInfo::GetApplicationId(); +} + +String +App::GetAppRootPath(void) const +{ + return _AppInfo::GetAppRootPath(); +} + +String +App::GetAppDataPath(void) const +{ + static String appDataPath(_AppInfo::GetAppRootPath() + L"data/"); + return appDataPath; +} + +String +App::GetAppResourcePath(void) const +{ + static String appResPath(_AppInfo::GetAppRootPath() + L"res/"); + return appResPath; +} + +result +App::Terminate(void) +{ + SysTryReturnResult(NID_APP, __pAppImpl != null, E_INVALID_STATE, "Getting App instance failed."); + + return __pAppImpl->Terminate(); +} + +bool +App::OnAppInitialized(void) +{ + return true; +} + +bool +App::OnAppWillTerminate(void) +{ + return true; +} + +void +App::OnLowMemory(void) +{ + +} + +void +App::OnBatteryLevelChanged(Tizen::System::BatteryLevel batteryLevel) +{ + +} + +result +App::SendUserEvent(RequestId requestId, const IList* pArgs) +{ + SysAssertf(__pAppImpl != null, "Getting App instance failed."); + + return __pAppImpl->SendUserEvent(requestId, pArgs); +} + +void +App::OnUserEventReceivedN(RequestId requestId, IList* pArgs) +{ + if (pArgs != null) + { + pArgs->RemoveAll(true); + delete pArgs; + } +} + +App* +App::GetInstance(void) +{ + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + + if (pAppImpl != null) + { + return pAppImpl->GetAppInstance(); + } + + return null; +} + +}} //Tizen::App + diff --git a/src/app/FAppAppControl.cpp b/src/app/FAppAppControl.cpp new file mode 100755 index 0000000..0e993e1 --- /dev/null +++ b/src/app/FAppAppControl.cpp @@ -0,0 +1,140 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppControl.cpp + * @brief This is the implementation for the Application Control class. + */ + +#include + +#include +#include + +#include + +#include "FApp_AppControlImpl.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::App; +using namespace Tizen::Security; + +namespace Tizen { namespace App +{ + +const String APPCONTROL_RESULT_SUCCEEDED = L"Succeeded"; + +const String APPCONTROL_RESULT_FAILED = L"Failed"; + +const String APPCONTROL_RESULT_CANCELED = L"Canceled"; + +const String APPCONTROL_RESULT_TERMINATED = L"Terminated"; + + +AppControl::AppControl(void) +: __pAppControlImpl(new (std::nothrow) _AppControlImpl(*this)) +{ + SysTryReturnVoidResult(NID_APP, __pAppControlImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); +} + +AppControl::~AppControl(void) +{ + delete __pAppControlImpl; +} + +result +AppControl::Start(const IList* pDataList, IAppControlEventListener* pListener) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + SysAssertf(__pAppControlImpl != null, "Instance is not constructed properly."); + return __pAppControlImpl->Start(pDataList, pListener); +} + +result +AppControl::Start(const String* pUriData, const String* pDataType, const IMap* pExtraData, IAppControlResponseListener* pListener) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + SysAssertf(__pAppControlImpl != null, "Instance is not constructed properly."); + return __pAppControlImpl->Start(pUriData, pDataType, pExtraData, pListener); +} + +result +AppControl::FindAndStart(const String& operationId, const String* pUriPattern, const String* pDataType, const String* pCategory, + const IMap* pExtraData, IAppControlResponseListener* pListener) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return _AppControlImpl::FindAndStart(operationId, pUriPattern, pDataType, pCategory, pExtraData, pListener); +} + +result +AppControl::Stop(void) +{ + SysAssertf(__pAppControlImpl != null, "Instance is not constructed properly."); + return __pAppControlImpl->Stop(); +} + +String +AppControl::GetAppName(void) const +{ + SysAssertf(__pAppControlImpl != null, "Instance is not constructed properly."); + return __pAppControlImpl->GetAppName(); +} + +AppId +AppControl::GetAppId(void) const +{ + SysTryReturn(NID_APP, __pAppControlImpl != null, L"", E_INVALID_STATE, "[E_INVALID_STATE] __pAppControlImpl instance must not be null."); + return __pAppControlImpl->GetAppId(); +} + +String +AppControl::GetAppControlProviderId(void) const +{ + SysAssertf(__pAppControlImpl != null, "Instance is not constructed properly."); + return __pAppControlImpl->GetAppControlProviderId(); +} + +String +AppControl::GetOperationId(void) const +{ + SysAssertf(__pAppControlImpl != null, "Instance is not constructed properly."); + return __pAppControlImpl->GetOperationId(); +} + +Tizen::Base::Collection::IList* +AppControl::GetCategoryListN(void) const +{ + SysAssertf(__pAppControlImpl != null, "Instance is not constructed properly."); + return __pAppControlImpl->GetCategoryListN(); +} + +void +AppControl::StopAppControlResponseListener(IAppControlResponseListener* pListener) +{ + _AppControlImpl::StopAppControlResponseListener(pListener); +} + +}; +}; //Tizen::App diff --git a/src/app/FAppAppControlProviderManager.cpp b/src/app/FAppAppControlProviderManager.cpp new file mode 100644 index 0000000..6df96e2 --- /dev/null +++ b/src/app/FAppAppControlProviderManager.cpp @@ -0,0 +1,84 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppControlProviderManager.cpp + * @brief This is the implementation for the %AppControlProviderManager class. + */ + +#include + +#include +#include +#include +#include + +#include + +#include "FApp_AppControlProviderManagerImpl.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +AppControlProviderManager::AppControlProviderManager(void) + : __pAppControlProviderManagerImpl(null) +{ + __pAppControlProviderManagerImpl = new (std::nothrow) _AppControlProviderManagerImpl; + SysTryReturnVoidResult(NID_APP, __pAppControlProviderManagerImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory was insufficient."); +} + +AppControlProviderManager::~AppControlProviderManager(void) +{ + delete __pAppControlProviderManagerImpl; +} + +AppControlProviderManager* +AppControlProviderManager::GetInstance(void) +{ + // scott meyers's singleton + static AppControlProviderManager mgr; + + return &mgr; +} + +result +AppControlProviderManager::SetAppControlProviderEventListener(IAppControlProviderEventListener* pListener) +{ + SysTryReturnResult(NID_APP, __pAppControlProviderManagerImpl, E_INVALID_STATE, "This instance has not been properly constructed."); + return __pAppControlProviderManagerImpl->SetAppControlProviderEventListener(pListener); +} + +result +AppControlProviderManager::SendAppControlResult(RequestId reqId, AppCtrlResult appControlResult, const IMap* pResultMap) +{ + SysTryReturnResult(NID_APP, __pAppControlProviderManagerImpl, E_INVALID_STATE, "This instance has not been properly constructed."); + return __pAppControlProviderManagerImpl->SendAppControlResult(reqId, appControlResult, pResultMap); +} + +AppId +AppControlProviderManager::GetClientAppId(RequestId reqId) const +{ + SysTryReturn(NID_APP, __pAppControlProviderManagerImpl, L"", E_INVALID_STATE, "[E_INVALID_STATE] This instance has not been properly constructed."); + return __pAppControlProviderManagerImpl->GetClientAppId(reqId); +} + +}} // Tizen::App + diff --git a/src/app/FAppAppManager.cpp b/src/app/FAppAppManager.cpp new file mode 100644 index 0000000..e9cd615 --- /dev/null +++ b/src/app/FAppAppManager.cpp @@ -0,0 +1,399 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppManager.cpp + * @brief This is the implementation for the AppManager class. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "FApp_Types.h" +#include "FAppPkg_PackageManagerImpl.h" +#include "FApp_AppManagerImpl.h" +#include "FApp_AppImpl.h" +#include "FApp_AppInfo.h" +#include "FApp_AppArg.h" +#include "FApp_Aul.h" +#include "FApp_AppControlProviderManagerImpl.h" +#ifdef _SINGLETON_CLEANUP +#include "FApp_LongevityManager.h" +#endif + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Io; +using namespace Tizen::Security; + +namespace Tizen { namespace App +{ + +const long MAX_ARGUMENTS_SIZE = 1024; + + +AppManager::AppManager(void) +: __pAppManagerImpl(null) +{ +} + + +result +AppManager::Construct(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pAppManagerImpl == null, + "Already constructed. Calling Construct() twice or more on a same in stance is not allowed for this class."); + + __pAppManagerImpl = new (std::nothrow) _AppManagerImpl(); + SysTryReturnResult(NID_APP, __pAppManagerImpl != null, E_OUT_OF_MEMORY, ""); + + r = __pAppManagerImpl->Construct(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; + +CATCH: + delete __pAppManagerImpl; + __pAppManagerImpl = null; + + return r; +} + + +AppManager::~AppManager(void) +{ + delete __pAppManagerImpl; +} + + +AppControl* +AppManager::FindAppControlN(const AppId& appId, const String& operationId) +{ + return _AppManagerImpl::FindAppControlN(appId, operationId); +} + + +IList* +AppManager::FindAppControlsN(const String* pOperationId, const String* pCategory, const String* pDataType, const String* pUriScheme) +{ + return _AppManagerImpl::FindAppControlsN(pOperationId, pCategory, pDataType, pUriScheme); +} + + +result +AppManager::StartAppControl(const String& uri, const String* pOperationId, + const String* pDataType, + IAppControlListener* pListener) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return _AppManagerImpl::StartAppControl(uri, pOperationId, pDataType, pListener); +} + + +result +AppManager::StartAppControl(const String* pOperationId, const String* pCategory, + const String* pDataType, const String* pUriScheme, + const IList* pDataList, + IAppControlListener* pListener) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return _AppManagerImpl::StartAppControl(pOperationId, pCategory, pDataType, pUriScheme, pDataList, pListener); +} + +SqlDataControl* +AppManager::GetSqlDataControlN(const String& providerId) +{ + return _AppManagerImpl::GetSqlDataControlN(providerId); +} + +MapDataControl* +AppManager::GetMapDataControlN(const String& providerId) +{ + return _AppManagerImpl::GetMapDataControlN(providerId); +} + +String +AppManager::GetAppSharedPath(const AppId& appId) +{ + String sharedPath; + + result r = _AppManagerImpl::GetAppRootPath(appId, sharedPath); + SysTryReturn(NID_APP, !IsFailed(r), sharedPath, r, "[%s] Propagating to caller...", + GetErrorMessage(r)); + + sharedPath.Append(L"shared/"); + + SetLastResult(E_SUCCESS); + return sharedPath; +} + +AppManager* +AppManager::GetInstance(void) +{ + result r = E_SUCCESS; + static AppManager* pAppMgr = null; + + if (pAppMgr == null) + { + pAppMgr = new (std::nothrow) AppManager(); + SysTryReturn(NID_APP, pAppMgr != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] AppManager allocation failed."); + + r = pAppMgr->Construct(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] AppManager construction failed.", GetErrorMessage(r)); + +#ifdef _SINGLETON_CLEANUP + // [FIXME] temporary disable to resolve N_SE-23319, ImeApp cleanup issue + //_LongevityManager::GetInstance().RegisterOwnership(*pAppMgr); +#endif + } + + return pAppMgr; + +CATCH: + delete pAppMgr; + pAppMgr = null; + + return null; +} + +result +AppManager::LaunchApplication(const AppId& appId, const IList* pArguments, LaunchOption option) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + SysTryReturnResult(NID_APP, appId.GetLength() <= WIDGET_APP_MAX_APPID_LENGTH, E_MAX_EXCEEDED, + "The length of appid exceeded the limit(%d).", WIDGET_APP_MAX_APPID_LENGTH); + + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pAppManagerImpl->LaunchApplication(appId, pArguments, LAUNCH_OPTION_DEFAULT); +} + +result +AppManager::LaunchApplication(const AppId& appId, LaunchOption option) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + SysTryReturnResult(NID_APP, appId.GetLength() <= WIDGET_APP_MAX_APPID_LENGTH, E_MAX_EXCEEDED, + "The length of appid exceeded the limit(%d).", WIDGET_APP_MAX_APPID_LENGTH); + + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pAppManagerImpl->LaunchApplication(appId, LAUNCH_OPTION_DEFAULT); +} + +result +AppManager::TerminateApplication(const AppId& appId) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + SysTryReturnResult(NID_APP, appId.GetLength() <= WIDGET_APP_MAX_APPID_LENGTH, E_MAX_EXCEEDED, + "The length of appid exceeded the limit(%d).", WIDGET_APP_MAX_APPID_LENGTH); + + String tmpAppId = appId; + String executableName = L""; + + result r = _AppManagerImpl::ExtractValues(appId, tmpAppId, executableName ); + bool hasExecutableName = (r == E_SUCCESS); + + return __pAppManagerImpl->TerminateApplication(tmpAppId, (hasExecutableName) ? &executableName : null); +} + +bool +AppManager::IsRunning(const AppId& appId) const +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + String tmpAppId = appId; + String executableName = L""; + + result r = _AppManagerImpl::ExtractValues(appId, tmpAppId, executableName ); + bool hasExecutableName = (r == E_SUCCESS); + + return __pAppManagerImpl->IsRunning(tmpAppId, (hasExecutableName) ? &executableName : null); +} + +IList* +AppManager::GetRunningAppListN(void) const +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + return __pAppManagerImpl->GetRunningAppListN(); +} + +result +AppManager::RegisterAppLaunch(const String& condition, const IList* pArguments, LaunchOption option) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pAppManagerImpl->RegisterAppLaunch(L"", _AppInfo::GetAppExecutableName(), condition, pArguments, option); +} + +result +AppManager::UnregisterAppLaunch(void) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pAppManagerImpl->UnregisterAppLaunch(L"", _AppInfo::GetAppExecutableName(), null); +} + +result +AppManager::UnregisterAppLaunch(const String& condition) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + result r = _AccessController::CheckUserPrivilege(_PRV_APPLICATION_LAUNCH); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pAppManagerImpl->UnregisterAppLaunch(L"", _AppInfo::GetAppExecutableName(), &condition); +} + +bool +AppManager::IsAppLaunchRegistered(void) const +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + return __pAppManagerImpl->IsAppLaunchRegistered(L"", _AppInfo::GetAppExecutableName(), null); +} + +result +AppManager::RegisterAppLaunch(const AppId& appId, const String& condition, const IList* pArguments, LaunchOption option) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + String tmpAppId = appId; + String executableName = L""; + + _AppManagerImpl::ExtractValues(appId, tmpAppId, executableName ); + SysTryReturnResult(NID_APP, _PackageManagerImpl::GetInstance()->IsPackageInstalled(tmpAppId) == true, E_APP_NOT_INSTALLED, "The application(%ls) is not installed.", appId.GetPointer()); + + return __pAppManagerImpl->RegisterAppLaunch(tmpAppId, executableName, condition, pArguments, option); +} + + +result +AppManager::UnregisterAppLaunch(const AppId& appId, const String* pCondition) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + String tmpAppId = appId; + String executableName = L""; + + _AppManagerImpl::ExtractValues(appId, tmpAppId, executableName ); + SysTryReturnResult(NID_APP, _PackageManagerImpl::GetInstance()->IsPackageInstalled(tmpAppId) == true, E_APP_NOT_INSTALLED, "The application(%ls) is not installed.", appId.GetPointer()); + + return __pAppManagerImpl->UnregisterAppLaunch(tmpAppId, executableName, pCondition); +} + + +bool +AppManager::IsAppLaunchRegistered(const AppId& appId, const String* pCondition) const +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + String tmpAppId = appId; + String executableName = L""; + + _AppManagerImpl::ExtractValues(appId, tmpAppId, executableName ); + SysTryReturn(NID_APP, _PackageManagerImpl::GetInstance()->IsPackageInstalled(tmpAppId) == true, false, E_APP_NOT_INSTALLED, "[E_APP_NOT_INSTALLED] The application(%ls) is not installed.", appId.GetPointer()); + + return __pAppManagerImpl->IsAppLaunchRegistered(tmpAppId, executableName, pCondition); +} + +result +AppManager::SetCheckpointEventListener(IAppCheckpointEventListener& listener) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + Tizen::Base::Runtime::IEventListener* pListener = &listener; + return __pAppManagerImpl->SetEventListener(AE_CHECKPOINT, pListener); +} + +void +AppManager::SetAppLaunchConditionEventListener(IAppLaunchConditionEventListener* pListener) +{ + SysLog(NID_APP, ""); + _AppImpl::GetInstance()->SetAppLaunchConditionEventListener(pListener); +} + + +result +AppManager::SendAppControlResult(const String& appControlRequestId, const IList* pResultList) +{ + int req = _AppArg::GetRequestId(appControlRequestId); + AppControlProviderManager* pInstance = AppControlProviderManager::GetInstance(); + return _AppControlProviderManagerImpl::GetInstance(*pInstance)->SendAppControlResult(req, pResultList); +} + +result +AppManager::AddActiveAppEventListener(IActiveAppEventListener& listener) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + result r = _AccessController::CheckUserPrivilege(_PRV_APPUSAGE); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pAppManagerImpl->AddActiveAppEventListener(listener); +} + +result +AppManager::RemoveActiveAppEventListener(IActiveAppEventListener& listener) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + result r = _AccessController::CheckUserPrivilege(_PRV_APPUSAGE); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pAppManagerImpl->RemoveActiveAppEventListener(listener); +} + +result +AppManager::GetActiveApp(AppId& appId) +{ + SysAssertf(__pAppManagerImpl != null, "Not constructed properly by platform."); + + result r = _AccessController::CheckUserPrivilege(_PRV_APPUSAGE); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pAppManagerImpl->GetActiveApp(appId); +} + +}} // Tizen::App diff --git a/src/app/FAppAppRegistry.cpp b/src/app/FAppAppRegistry.cpp new file mode 100644 index 0000000..f0286ed --- /dev/null +++ b/src/app/FAppAppRegistry.cpp @@ -0,0 +1,185 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppRegistry.cpp + * @brief This is the implementation for the AppRegistry class. + */ + +#include +#include +#include + +#include "FApp_AppRegistryImpl.h" +#include "FAppPkg_PackageInfoImpl.h" +#ifdef _SINGLETON_CLEANUP +#include "FApp_LongevityManager.h" +#endif + +using namespace Tizen::Io; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + + +AppRegistry::AppRegistry(void) + : __pAppRegistryImpl(null) +{ +} + + +AppRegistry::~AppRegistry(void) +{ + delete __pAppRegistryImpl; +} + + +result +AppRegistry::Construct(void) +{ + SysAssertf(__pAppRegistryImpl == null, + "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + __pAppRegistryImpl = new (std::nothrow) _AppRegistryImpl(); + SysTryReturnResult(NID_APP, __pAppRegistryImpl != null, E_OUT_OF_MEMORY, "Allocation failed."); + + return __pAppRegistryImpl->Construct(); +} + + +result +AppRegistry::Add(const String& key, const String& value) +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Add(key, value); +} + + +result +AppRegistry::Add(const String& key, int value) +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Add(key, value); +} + + +result +AppRegistry::Add(const String& key, double value) +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Add(key, value); +} + + +result +AppRegistry::Set(const String& key, const String& value) +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Set(key, value); +} + + +result +AppRegistry::Set(const String& key, int value) +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Set(key, value); +} + + +result +AppRegistry::Set(const String& key, double value) +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Set(key, value); +} + + +result +AppRegistry::Save(void) +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Save(); +} + + +result +AppRegistry::Remove(const String& key) +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Remove(key); +} + + +result +AppRegistry::Get(const String& key, String& value) const +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Get(key, value); +} + + +result +AppRegistry::Get(const String& key, int& value) const +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Get(key, value); +} + + +result +AppRegistry::Get(const String& key, double& value) const +{ + SysAssertf(__pAppRegistryImpl != null, "Not yet constructed. Construct() should be called before use."); + return __pAppRegistryImpl->Get(key, value); +} + + +AppRegistry* +AppRegistry::GetInstance(void) +{ + result r = E_SUCCESS; + static AppRegistry* pAppRegistry = null; + + if (pAppRegistry == null) + { + pAppRegistry = new (std::nothrow) AppRegistry(); + SysTryCatch(NID_APP, pAppRegistry != null, , r = E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] app registry allocation failed."); + + r = pAppRegistry->Construct(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Initialization of app registry failed.", GetErrorMessage(r)); + +#ifdef _SINGLETON_CLEANUP + _LongevityManager::GetInstance().RegisterOwnership(*pAppRegistry); +#endif + } + + SetLastResult(r); + return pAppRegistry; + +CATCH: + delete pAppRegistry; + pAppRegistry = null; + + SetLastResult(r); + return pAppRegistry; +} + + +} } // Tizen::App diff --git a/src/app/FAppAppResource.cpp b/src/app/FAppAppResource.cpp new file mode 100644 index 0000000..833d2f4 --- /dev/null +++ b/src/app/FAppAppResource.cpp @@ -0,0 +1,250 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppAppResource.cpp + * @brief This is the implementation for the AppResource class. + */ + +#include + +#include +#include + +#include +#include "FApp_Aul.h" +#include +#include "FApp_AppResourceImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Graphics; +using namespace Tizen::Security; + +namespace Tizen { namespace App +{ + +Tizen::Base::Collection::HashMap* AppResource::pContainer = null; + +AppResource::AppResource(void) + : __pAppResourceImpl(null) +{ +} + + +AppResource::~AppResource(void) +{ + delete __pAppResourceImpl; +} + + +result +AppResource::Construct(void) +{ + SysAssertf(__pAppResourceImpl == null, + "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + __pAppResourceImpl = new (std::nothrow) _AppResourceImpl(); + SysTryReturnResult(NID_APP, __pAppResourceImpl != null, E_OUT_OF_MEMORY, "Allocation failed."); + + result r = __pAppResourceImpl->Construct(); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return E_SUCCESS; + +} + + +result +AppResource::GetString(const String& resourceId, String& loadedString) const +{ + SysAssertf(__pAppResourceImpl != null, "Not yet constructed. Construct() should be called before use."); + + return __pAppResourceImpl->GetString(resourceId, loadedString); +} + + +Bitmap* +AppResource::GetBitmapN(const String& imgFilePath, BitmapPixelFormat pixelFormat) const +{ + SysAssertf(__pAppResourceImpl != null, "Not yet constructed. Construct() should be called before use."); + + return __pAppResourceImpl->GetBitmapN(imgFilePath, pixelFormat); +} + + +Bitmap* +AppResource::GetBitmapN(const String& imgFilePath) const +{ + SysAssertf(__pAppResourceImpl != null, "Not yet constructed. Construct() should be called before use."); + + return __pAppResourceImpl->GetBitmapN(imgFilePath); +} + + +AppResource* +AppResource::GetInstance(void) +{ + result r = E_SUCCESS; + static AppResource* pAppResource = null; + + if (pAppResource == null) + { + pAppResource = new (std::nothrow) AppResource(); + SysTryCatch(NID_APP, pAppResource != null, , r = E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] app resource allocation failed."); + + r = pAppResource->Construct(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Initialization of app resource failed.", GetErrorMessage(r)); + } + + SetLastResult(r); + return pAppResource; + +CATCH: + delete pAppResource; + pAppResource = null; + + SetLastResult(r); + return pAppResource; +} + +AppResource* +AppResource::GetInstanceByAppId(const AppId& appId) +{ + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_APPSETTING); + SysTryReturn(NID_APP, r == E_SUCCESS, null, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + SysTryReturn(NID_APP, _Aul::IsInstalled(appId) == true, null, E_APP_NOT_INSTALLED, "Application is not installed.", GetErrorMessage(E_APP_NOT_INSTALLED)); + + if (pContainer == null) + { + std::unique_ptr< HashMap > pContainerMap(new (std::nothrow) HashMap()); + SysTryReturn(NID_APP, pContainerMap != null, + null, E_OUT_OF_MEMORY, "[%s] Creating the container is failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pContainerMap->Construct(); + SysTryReturn(NID_APP, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] Creating the container is failed [%s].", GetErrorMessage(r)); + + pContainer = pContainerMap.release(); + } + + String packageId; + r = appId.SubString(0, 10, packageId); + SysTryReturn(NID_APP, !IsFailed(r), null, + E_APP_NOT_INSTALLED, "[%s] Failed to get package info", GetErrorMessage(E_APP_NOT_INSTALLED)); + + bool hasAppResource = false; + r = pContainer->ContainsKey(packageId, hasAppResource); + SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] Checking to contain is failed.", GetErrorMessage(r)); + + if(hasAppResource == true) + { + SetLastResult(r); + return static_cast (pContainer->GetValue(packageId)); + } + else + { + std::unique_ptr< String > pStr(new (std::nothrow) String(packageId)); + SysTryReturn(NID_APP, pStr != null, null, + E_OUT_OF_MEMORY, "[%s] Creating a key is failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + AppResource* pAppResource = new (std::nothrow) AppResource; + SysTryReturn(NID_APP, pAppResource != null, null, + E_OUT_OF_MEMORY, "[%s] Unable to allocate memory for AppResource", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pAppResource->Construct(packageId); + SysTryCatch(NID_APP, !IsFailed(r), , + E_SYSTEM, "[E_SYSTEM] Adding an element to the container is failed [%s].", GetErrorMessage(r)); + + r = pContainer->Add(*pStr, *pAppResource); + SysTryCatch(NID_APP, !IsFailed(r), , + E_SYSTEM, "[E_SYSTEM] Adding an element to the container is failed [%s].", GetErrorMessage(r)); + + SetLastResult(r); + pStr.release(); + return pAppResource; +CATCH: + delete pAppResource; + return null; + } +} + +result +AppResource::ReleaseInstanceByAppId(const AppId& appId) +{ + result r = E_SUCCESS; + AppResource* pAppResource = null; + + r = _AccessController::CheckUserPrivilege(_PRV_APPSETTING); + SysTryReturn(NID_APP, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + SysTryReturnResult(NID_APP, _Aul::IsInstalled(appId) == true, E_OBJ_NOT_FOUND, "Applicationis not installed."); + + if (pContainer != null) + { + String packageId; + r = appId.SubString(0, 10, packageId); + SysTryReturn(NID_APP, !IsFailed(r), E_OBJ_NOT_FOUND, + E_OBJ_NOT_FOUND, "[%s] Failed to get package info", GetErrorMessage(E_OBJ_NOT_FOUND)); + + pAppResource = static_cast (pContainer->GetValue(packageId)); + delete pAppResource; + r = pContainer->Remove(packageId); + } + + return r; +} + +result +AppResource::Construct(const AppId& appId) +{ + SysAssertf(__pAppResourceImpl == null, + "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + __pAppResourceImpl = new (std::nothrow) _AppResourceImpl(); + SysTryReturnResult(NID_APP, __pAppResourceImpl != null, E_OUT_OF_MEMORY, "Allocation failed."); + + result r = __pAppResourceImpl->Construct(appId); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return E_SUCCESS; + +} + +void +AppResource::Reinitialize(void) +{ + if (pContainer != null) + { + IMapEnumerator* pMapEnum = pContainer->GetMapEnumeratorN(); + while(pMapEnum->MoveNext() == E_SUCCESS) + { + AppResource* pAppResource = static_cast (pMapEnum->GetValue()); + String* pStr = static_cast (pMapEnum->GetKey()); + pAppResource->Reinitialize(*pStr); + } + } +} + +void +AppResource::Reinitialize(const AppId& appId) +{ + __pAppResourceImpl->Reinitialize(appId); +} +} } // Tizen::App diff --git a/src/app/FAppAppSetting.cpp b/src/app/FAppAppSetting.cpp new file mode 100644 index 0000000..aac1b2f --- /dev/null +++ b/src/app/FAppAppSetting.cpp @@ -0,0 +1,159 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppAppSetting.h + * @brief This is the implementation file for the %AppSetting class. + * + */ + +#include +#include +#include +#include +#include +#include "FApp_AppSettingImpl.h" + +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +AppSetting* AppSetting::__pAppSettingInstance = null; + +AppSetting::AppSetting(void) + : __pAppSettingImpl(null) +{ + +} + +AppSetting::~AppSetting(void) +{ + delete __pAppSettingImpl; +} + +AppSetting* +AppSetting::GetInstance(void) +{ + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + if (!__pAppSettingInstance) + { + ClearLastResult(); + pthread_once(&onceBlock, InitSingleton); + result r = GetLastResult(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + __pAppSettingInstance->__pAppSettingImpl = _AppSettingImpl::GetInstance(); + SysTryCatch(NID_APP, __pAppSettingInstance->__pAppSettingImpl != null, , E_OUT_OF_MEMORY, + "[%s] Memory allocation failed."); + } + + return __pAppSettingInstance; + +CATCH: + delete __pAppSettingInstance; + __pAppSettingInstance = null; + onceBlock = PTHREAD_ONCE_INIT; + return null; +} + +AppSetting* +AppSetting::GetInstance(const Tizen::Base::String& version) +{ + return _AppSettingImpl::GetInstance(version); +} + +AppSetting* +AppSetting::GetInstanceByAppId(const AppId& appId) +{ + //TODO: Add privilege checking code + return _AppSettingImpl::GetInstanceByAppId(appId); +} + +result +AppSetting::ReleaseInstanceByAppId(const AppId& appId) +{ + return _AppSettingImpl::ReleaseInstanceByAppId(appId); +} + +Tizen::Base::Collection::IList* +AppSetting::GetAppSettingVersionListN(void) +{ + return _AppSettingImpl::GetAppSettingVersionListN(); +} + +result +AppSetting::GetValue(const Tizen::Base::String& id, bool& value) const +{ + return __pAppSettingImpl->GetValue(id, value); +} + +result +AppSetting::GetValue(const Tizen::Base::String& id, int& value) const +{ + return __pAppSettingImpl->GetValue(id, value); +} + +result +AppSetting::GetValue(const Tizen::Base::String& id, Tizen::Base::String& value) const +{ + return __pAppSettingImpl->GetValue(id, value); +} + +result +AppSetting::SetValue(const Tizen::Base::String& id, bool value) +{ + return __pAppSettingImpl->SetValue(id, value); +} + +result +AppSetting::SetValue(const Tizen::Base::String& id, int value) +{ + return __pAppSettingImpl->SetValue(id, value); +} + +result +AppSetting::SetValue(const Tizen::Base::String& id, const Tizen::Base::String& value) +{ + return __pAppSettingImpl->SetValue(id, value); +} + +result +AppSetting::SetAppSettingEventListener(IAppSettingEventListener* pListener) +{ + return __pAppSettingImpl->SetAppSettingEventListener(pListener); +} + +void +AppSetting::InitSingleton(void) +{ + AppSetting* pInst = new (std::nothrow) AppSetting(); + SysTryReturnVoidResult(NID_UI_SCENES, pInst, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + __pAppSettingInstance = pInst; + std::atexit(DestroySingleton); +} + +void +AppSetting::DestroySingleton(void) +{ + delete __pAppSettingInstance; +} + + +} } // Tizen::App diff --git a/src/app/FAppDataControlProviderManager.cpp b/src/app/FAppDataControlProviderManager.cpp new file mode 100644 index 0000000..265c8df --- /dev/null +++ b/src/app/FAppDataControlProviderManager.cpp @@ -0,0 +1,116 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppDataControlProviderManager.cpp + * @brief This is the implementation for the %DataControlProviderManager class. + */ + +#include + +#include +#include +#include +#include +#include + +#include + +#include "FApp_DataControlProviderManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +namespace Tizen { namespace App +{ + +result +DataControlProviderManager::SetSqlDataControlProviderEventListener(ISqlDataControlProviderEventListener* pListener) +{ + SysTryReturnResult(NID_APP, __pDataControlProviderManagerImpl, E_INVALID_STATE, "This instance has not been properly constructed."); + return __pDataControlProviderManagerImpl->SetSqlDataControlProviderEventListener(pListener); +} + +result +DataControlProviderManager::SetMapDataControlProviderEventListener(IMapDataControlProviderEventListener* pListener) +{ + SysTryReturnResult(NID_APP, __pDataControlProviderManagerImpl, E_INVALID_STATE, "This instance has not been properly constructed."); + return __pDataControlProviderManagerImpl->SetMapDataControlProviderEventListener(pListener); +} + +result +DataControlProviderManager::SendSqlDataControlSelectResult(RequestId reqId, IDbEnumerator* pDbEnum) +{ + SysTryReturnResult(NID_APP, __pDataControlProviderManagerImpl, E_INVALID_STATE, + "This instance has not been properly constructed."); + return __pDataControlProviderManagerImpl->SendSqlDataControlSelectResult(reqId, pDbEnum); +} + +result +DataControlProviderManager::SendSqlDataControlInsertResult(RequestId reqId, long long insertRowId) +{ + SysTryReturnResult(NID_APP, __pDataControlProviderManagerImpl, E_INVALID_STATE, + "This instance has not been properly constructed."); + return __pDataControlProviderManagerImpl->SendSqlDataControlInsertResult(reqId, insertRowId); +} + +result +DataControlProviderManager::SendSqlDataControlUpdateDeleteResult(RequestId reqId) +{ + SysTryReturnResult(NID_APP, __pDataControlProviderManagerImpl, E_INVALID_STATE, + "This instance has not been properly constructed."); + return __pDataControlProviderManagerImpl->SendSqlDataControlUpdateDeleteResult(reqId); +} + +result +DataControlProviderManager::SendMapDataControlResult(RequestId reqId, IList* pResultValueList) +{ + SysTryReturnResult(NID_APP, __pDataControlProviderManagerImpl, E_INVALID_STATE, + "This instance has not been properly constructed."); + return __pDataControlProviderManagerImpl->SendMapDataControlResult(reqId, pResultValueList); +} + +result +DataControlProviderManager::SendDataControlError(RequestId reqId, const String& errorMsg) +{ + SysTryReturnResult(NID_APP, __pDataControlProviderManagerImpl, E_INVALID_STATE, + "This instance has not been properly constructed."); + return __pDataControlProviderManagerImpl->SendDataControlError(reqId, errorMsg); +} + +DataControlProviderManager* +DataControlProviderManager::GetInstance(void) +{ + return _DataControlProviderManagerImpl::GetInstance(); +} + +// private +DataControlProviderManager::DataControlProviderManager(void) + : __pDataControlProviderManagerImpl(null) +{ + __pDataControlProviderManagerImpl = new (std::nothrow) _DataControlProviderManagerImpl; + SysTryReturnVoidResult(NID_APP, __pDataControlProviderManagerImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory was insufficient."); +} + +DataControlProviderManager::~DataControlProviderManager(void) +{ + delete __pDataControlProviderManagerImpl; +} + +}} // Tizen::App + diff --git a/src/app/FAppMapDataControl.cpp b/src/app/FAppMapDataControl.cpp new file mode 100644 index 0000000..2d2ef60 --- /dev/null +++ b/src/app/FAppMapDataControl.cpp @@ -0,0 +1,97 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppMapDataControl.cpp + * @brief This is the implementation for the %MapDataControl class. + */ + +#include + +#include +#include + +#include "FApp_MapDataControlImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::App; + +namespace Tizen { namespace App { + +MapDataControl::MapDataControl(void) + : __pMapDataControlImpl(null) +{ + __pMapDataControlImpl = new _MapDataControlImpl; +} + +MapDataControl::~MapDataControl(void) +{ + delete __pMapDataControlImpl; +} + +result +MapDataControl::GetValue(const String& dataId, const String& key, + RequestId& reqId, int pageNo, int countPerPage) +{ + SysTryReturnResult(NID_APP, __pMapDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed yet."); + + return __pMapDataControlImpl->GetValue(dataId, key, reqId, pageNo, countPerPage); +} + +result +MapDataControl::AddValue(const String& dataId, const String& key, + const String& value, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, __pMapDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed yet."); + + return __pMapDataControlImpl->AddValue(dataId, key, value, reqId); +} + +result +MapDataControl::SetValue(const String& dataId, const String& key, + const String& oldValue, const String& newValue, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, __pMapDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed yet."); + + return __pMapDataControlImpl->SetValue(dataId, key, oldValue, newValue, reqId); +} + +result +MapDataControl::RemoveValue(const String& dataId, const String& key, + const String& value, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, __pMapDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed yet."); + + return __pMapDataControlImpl->RemoveValue(dataId, key, value, reqId); +} + +result +MapDataControl::SetMapDataControlResponseListener(IMapDataControlResponseListener* pListener) +{ + SysTryReturnResult(NID_APP, __pMapDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed yet."); + + return __pMapDataControlImpl->SetMapDataControlResponseListener(pListener); +} + +}} // Tizen::App + diff --git a/src/app/FAppNotificationManager.cpp b/src/app/FAppNotificationManager.cpp new file mode 100644 index 0000000..a24746e --- /dev/null +++ b/src/app/FAppNotificationManager.cpp @@ -0,0 +1,262 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppNotificationManager.cpp + * @brief This is the placeholder for NotificationManager class. + */ + +#include + +#include + +#include +#include +#include "FApp_NotificationManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + +namespace Tizen { namespace App +{ + +NotificationManager::NotificationManager() + : __pNotificationManagerImpl(null) +{ + //default constructor +} + +NotificationManager::~NotificationManager() +{ + delete __pNotificationManagerImpl; +} + +result +NotificationManager::Construct(void) +{ + SysAssertf(__pNotificationManagerImpl == null, + "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + __pNotificationManagerImpl = new (std::nothrow) _NotificationManagerImpl(); + SysTryReturnResult(NID_APP, __pNotificationManagerImpl != null, E_OUT_OF_MEMORY, "Allocation failed."); + + return __pNotificationManagerImpl->Construct(); +} + +int +NotificationManager::GetBadgeNumber(void) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->GetBadgeNumber(); +} + +result +NotificationManager::Notify(int badgeNumber) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->Notify(badgeNumber); +} + +result +NotificationManager::Notify(const String& messageText) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->Notify(messageText); +} + +result +NotificationManager::Notify(const String& messageText, int badgeNumber) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->Notify(messageText, badgeNumber); +} + +result +NotificationManager::Notify(const String& messageText, int badgeNumber, const String& launchArguments) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->Notify(messageText, badgeNumber, launchArguments); +} + +int +NotificationManager::GetBadgeNumber(const AppId& appId) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->GetBadgeNumber(appId); +} + + +result +NotificationManager::NotifyOnBehalf(const AppId& appId, int badgeNumber) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATIONMANAGER); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->NotifyOnBehalf(appId, badgeNumber); +} + +result +NotificationManager::NotifyOnBehalf(const AppId& appId, const String& messageText) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATIONMANAGER); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->NotifyOnBehalf(appId, messageText); +} + +result +NotificationManager::NotifyOnBehalf(const AppId& appId, const String& messageText, int badgeNumber) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATIONMANAGER); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->NotifyOnBehalf(appId, messageText, badgeNumber); +} + +result +NotificationManager::NotifyOnBehalf(const AppId& appId, const String& messageText, const String& launchArguments) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATIONMANAGER); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->NotifyOnBehalf(appId, messageText, launchArguments); +} + +result +NotificationManager::NotifyOngoingActivity(const String& messageText) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->NotifyOngoingActivity(messageText); +} + +result +NotificationManager::NotifyOngoingActivity(const String& messageText, const String& launchArguments) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + + return __pNotificationManagerImpl->NotifyOngoingActivity(messageText, launchArguments); +} + +result +NotificationManager::NotifyOngoingActivityOnBehalf(const AppId& appId, const String& messageText) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATIONMANAGER); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + + return __pNotificationManagerImpl->NotifyOngoingActivityOnBehalf(appId, messageText); +} + +result +NotificationManager::NotifyOngoingActivityOnBehalf(const AppId& appId, const String& messageText, const String& launchArguments) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATIONMANAGER); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->NotifyOngoingActivityOnBehalf(appId, messageText, launchArguments); +} + +result +NotificationManager::RemoveOngoingActivityNotification(void) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->RemoveOngoingActivityNotification(); +} + +result +NotificationManager::RemoveOngoingActivityNotificationOnBehalf(const AppId& appId) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATIONMANAGER); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->RemoveOngoingActivityNotificationOnBehalf(appId); +} + +result +NotificationManager::RemoveNotification(void) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATION); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->RemoveNotification(); +} + +result +NotificationManager::RemoveNotificationOnBehalf(const AppId& appId) +{ + SysAssertf(__pNotificationManagerImpl != null, "Not yet constructed. Construct() should be called before use."); + + result r = _AccessController::CheckUserPrivilege(_PRV_NOTIFICATIONMANAGER); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, "The application does not have the privilege to call this method."); + + return __pNotificationManagerImpl->RemoveNotificationOnBehalf(appId); +} + +}; +}; // Tizen::App diff --git a/src/app/FAppNotificationMessage.cpp b/src/app/FAppNotificationMessage.cpp new file mode 100644 index 0000000..8a612cc --- /dev/null +++ b/src/app/FAppNotificationMessage.cpp @@ -0,0 +1,229 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppNotificationMessage.cpp + * @brief This is the placeholder for NotificationMessage class. + */ + +#include + +#include + +#include +#include "FApp_NotificationMessageImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + + +namespace Tizen { namespace App +{ + +NotificationMessage::NotificationMessage(bool appBinding) + : __pNotificationMessageImpl(null) +{ + __pNotificationMessageImpl = new (std::nothrow) _NotificationMessageImpl(appBinding); + SysTryReturnVoidResult(NID_APP, __pNotificationMessageImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); +} + +NotificationMessage::~NotificationMessage() +{ + delete __pNotificationMessageImpl; +} + +NotificationMessage::NotificationMessage(const NotificationMessage& rhs) +{ + __pNotificationMessageImpl = new (std::nothrow) _NotificationMessageImpl(*rhs.__pNotificationMessageImpl); + SysTryReturnVoidResult(NID_APP, __pNotificationMessageImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); +} + +NotificationMessage& +NotificationMessage::operator =(const NotificationMessage& rhs) +{ + if (&rhs != this) + { + delete __pNotificationMessageImpl; + + __pNotificationMessageImpl = new (std::nothrow) _NotificationMessageImpl(*rhs.__pNotificationMessageImpl); + SysTryReturn(NID_APP, __pNotificationMessageImpl, *this, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + } + + return(*this); +} + +bool +NotificationMessage::Equals(const Object& rhs) const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + return __pNotificationMessageImpl->Equals(rhs); +} + +int +NotificationMessage::GetHashCode(void) const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + return __pNotificationMessageImpl->GetHashCode(); +} + +int +NotificationMessage::GetBadgeNumber(void) const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetBadgeNumber(); +} + +result +NotificationMessage::SetBadgeNumber(int badgeNumber) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetBadgeNumber(badgeNumber); +} + +int +NotificationMessage::GetBadgeOffset() const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetBadgeOffset(); +} + +result +NotificationMessage::SetBadgeOffset(int badgeOffset) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetBadgeOffset(badgeOffset); +} + +String +NotificationMessage::GetAlertText() const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetAlertText(); +} + +result +NotificationMessage::SetAlertText(const String& alertText) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetAlertText(alertText); +} + +String +NotificationMessage::GetAppMessage() const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetAppMessage(); +} + + +result +NotificationMessage::SetAppMessage(const String& appMessage) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetAppMessage(appMessage); +} + +String +NotificationMessage::GetTitleText() const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetTitleText(); +} + +result +NotificationMessage::SetTitleText(const String& titleText) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetTitleText(titleText); +} + +String +NotificationMessage::GetIconFilePath() const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetIconFilePath(); +} + +result +NotificationMessage::SetIconFilePath(const String& iconFilePath) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetIconFilePath(iconFilePath); +} + +String +NotificationMessage::GetSoundFilePath() const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetSoundFilePath(); +} + +result +NotificationMessage::SetSoundFilePath(const String& soundFilePath) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetSoundFilePath(soundFilePath); +} + +OngoingActivityType +NotificationMessage::GetOngoingActivityType() const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetOngoingActivityType(); +} + +result +NotificationMessage::SetOngoingActivityType(OngoingActivityType activityType) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetOngoingActivityType(activityType); +} + +int +NotificationMessage::GetOngoingActivityProgressValue() const +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->GetOngoingActivityProgressValue(); +} + +result +NotificationMessage::SetOngoingActivityProgressValue(int progressValue) +{ + SysAssertf(__pNotificationMessageImpl != null, "Instance is not constructed properly."); + + return __pNotificationMessageImpl->SetOngoingActivityProgressValue(progressValue); +} + +}; +}; // Tizen::App diff --git a/src/app/FAppServiceApp.cpp b/src/app/FAppServiceApp.cpp new file mode 100644 index 0000000..b30052e --- /dev/null +++ b/src/app/FAppServiceApp.cpp @@ -0,0 +1,100 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppServiceApp.cpp + * @brief This is the implementation for the ServiceApp class. + */ + +#include +#include +#include + +#include +#include "FApp_AppImpl.h" +#include "FApp_ServiceAppImpl.h" +#include "FApp_AppInfo.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +ServiceApp::ServiceApp(void) +{ + __pServiceAppImpl = new (std::nothrow) _ServiceAppImpl(this); + SysAssertf(__pServiceAppImpl != null, "Allocating memory for ServiceApp instance failed."); + SysTryReturnVoidResult(NID_APP, __pServiceAppImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); +} + + +ServiceApp::~ServiceApp(void) +{ + delete __pServiceAppImpl; +} + + +ServiceApp* +ServiceApp::GetInstance(void) +{ + _ServiceAppImpl* pServiceAppImpl = _ServiceAppImpl::GetInstance(); + if (pServiceAppImpl == null) + { + return null; + } + + return pServiceAppImpl->GetServiceAppInstance(); +} + + +result +ServiceApp::Execute(ServiceAppInstanceFactory pServiceAppFactory, const IList* pArguments) +{ + result r = E_SUCCESS; + ServiceApp* pServiceApp = null; + _AppImpl* pAppImpl = null; + + SysTryReturnResult(NID_APP, pServiceAppFactory != null, E_INVALID_ARG, "pServiceAppFactory must not be null."); + SysTryReturnResult(NID_APP, pArguments != null, E_INVALID_ARG, "pArguments must not be null."); + _AppInfo::SetAppType(_APP_TYPE_SERVICE_APP); + + ClearLastResult(); + pServiceApp = pServiceAppFactory(); + SysTryReturnResult(NID_APP, pServiceApp != null, E_OUT_OF_MEMORY, "App allocation failed."); + SysTryReturnResult(NID_APP, !IsFailed(GetLastResult()), E_OUT_OF_MEMORY, "App allocation failed."); + + pAppImpl = _AppImpl::GetInstance(); + SysTryReturnResult(NID_APP, pAppImpl != null, E_SYSTEM, "application instance is not available."); + + _ServiceAppImpl* pServiceAppImpl = _ServiceAppImpl::GetInstance(); + SysTryReturnResult(NID_APP, pServiceAppImpl != null, E_INVALID_STATE, "Getting UiApp instance failed."); + + r = pAppImpl->Construct(pArguments); + SysTryCatch(NID_APP, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] %s.", GetErrorMessage(r)); + + r = pAppImpl->Execute(pServiceAppImpl); + SysTryCatch(NID_APP, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] %s.", GetErrorMessage(r)); + +CATCH: + delete pServiceApp; + + return r; +} + + +} } //Tizen::App diff --git a/src/app/FAppSqlDataControl.cpp b/src/app/FAppSqlDataControl.cpp new file mode 100644 index 0000000..fb0b206 --- /dev/null +++ b/src/app/FAppSqlDataControl.cpp @@ -0,0 +1,95 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppSqlDataControl.cpp + * @brief This is the implementation for the %SqlDataControl class. + */ + +#include + +#include +#include + +#include "FApp_SqlDataControlImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +SqlDataControl::SqlDataControl(void) + : __pSqlDataControlImpl(null) +{ + __pSqlDataControlImpl = new _SqlDataControlImpl; +} + +SqlDataControl::~SqlDataControl(void) +{ + delete __pSqlDataControlImpl; +} + +result +SqlDataControl::Select(const String& dataId, const IList* pColumnList, const String* pWhere, + const String *pOrder, RequestId& reqId, int pageNo, int countPerPage) +{ + SysTryReturnResult(NID_APP, __pSqlDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed."); + + return __pSqlDataControlImpl->Select(dataId, pColumnList, pWhere, pOrder, reqId, pageNo, countPerPage); +} + +result +SqlDataControl::Insert(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& insertMap, + RequestId& reqId) +{ + SysTryReturnResult(NID_APP, __pSqlDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed."); + + return __pSqlDataControlImpl->Insert(dataId, insertMap, reqId); +} + +result +SqlDataControl::Update(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& updateMap, + const Tizen::Base::String* pWhere, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, __pSqlDataControlImpl, E_INVALID_STATE, "This instance has not been properly constructed."); + + return __pSqlDataControlImpl->Update(dataId, updateMap, pWhere, reqId); +} + +result +SqlDataControl::Delete(const Tizen::Base::String& dataId, const Tizen::Base::String* pWhere, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, __pSqlDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed."); + + return __pSqlDataControlImpl->Delete(dataId, pWhere, reqId); +} + +result +SqlDataControl::SetSqlDataControlResponseListener(ISqlDataControlResponseListener* pListener) +{ + SysTryReturnResult(NID_APP, __pSqlDataControlImpl, E_INVALID_STATE, + "This instance has not been properly constructed yet."); + + return __pSqlDataControlImpl->SetSqlDataControlResponseListener(pListener); +} + +}} // Tizen::App + diff --git a/src/app/FApp_AppArg.cpp b/src/app/FApp_AppArg.cpp new file mode 100644 index 0000000..83824ad --- /dev/null +++ b/src/app/FApp_AppArg.cpp @@ -0,0 +1,1321 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FApp_AppArg.cpp +* @brief This is the implementation for the _AppArg.cpp class. +*/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "FApp_MapDataControlImpl.h" +#include "FApp_AppControlImpl.h" +#include "FApp_SqlDataControlImpl.h" +#include "FApp_AppControlEventArg.h" +#include "FApp_AppArg.h" +#include "FApp_AppMessageImpl.h" +#include "FAppPkg_PackageManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; +using namespace Tizen::App::Package; + +namespace Tizen { namespace App +{ + +static const char OSP_V_LAUNCH_TYPE_LAUNCH[] = "launch"; +static const char OSP_V_LAUNCH_TYPE_APPCONTROL[] = "appcontrol"; +static const char OSP_V_LAUNCH_TYPE_DATACONTROL[] = "datacontrol"; +static const char OSP_V_LAUNCH_TYPE_CONDTION[] = "condition"; +static const char OSP_V_REQUEST_TYPE_SQL_QUERY[] = "sql_query"; +static const char OSP_V_REQUEST_TYPE_SQL_INSERT[] = "sql_insert"; +static const char OSP_V_REQUEST_TYPE_SQL_UPDATE[] = "sql_update"; +static const char OSP_V_REQUEST_TYPE_SQL_DELETE[] = "sql_delete"; +static const char OSP_V_REQUEST_TYPE_MAP_QEURY[] = "map_query"; +static const char OSP_V_REQUEST_TYPE_MAP_INSERT[] = "map_insert"; +static const char OSP_V_REQUEST_TYPE_MAP_UPDATE[] = "map_update"; +static const char OSP_V_REQUEST_TYPE_MAP_DELETE[] = "map_delete"; +static const char BUNDLE_KEY_WINDOW[] = "__APP_SVC_K_WIN_ID__"; +static const char BUNDLE_KEY_PREFIX_AUL[] = "__AUL_"; +static const char BUNDLE_KEY_PREFIX_SERVICE[] = "__APP_SVC_"; +static const char BUNDLE_KEY_PREFIX_OSP[] = "__OSP_"; +const char TIZEN_NOTIFICATION_DATA[] = "http://tizen.org/appcontrol/data/notification"; + +static const char SAMSUNG_ACCOUNT_KEY_CLIENT_ID[] = "client_id"; +static const char SAMSUNG_ACCOUNT_KEY_CLIENT_SECRET[] = "client_secret"; +static const char SAMSUNG_ACCOUNT_KEY_SERVICE_CATEGORY[] = "service_category"; + +static const char SMS_KEY_SERVICE_CALLER[] = "service_caller"; +static const char SMS_KEY_SERVICE_DATA[] = "service_data"; + + +_AppArg::_AppArg(void) + : __pBundle(null) +{ +} + + +_AppArg::~_AppArg(void) +{ + if (__pBundle) + { + bundle_free(__pBundle); + } +} + + +result +_AppArg::Construct(const String& argText) +{ + __pBundle = bundle_create(); + SysTryReturnResult(NID_APP, __pBundle != null, E_OUT_OF_MEMORY, "Bundle creation failure."); + + return CreateLaunchArg(__pBundle, argText); +} + + +result +_AppArg::Construct(const IList* pList) +{ + __pBundle = bundle_create(); + SysTryReturnResult(NID_APP, __pBundle != null, E_OUT_OF_MEMORY, "Bundle creation failure."); + + return CreateLaunchArg(__pBundle, pList); +} + + +result +_AppArg::Construct(const _AppControlImpl& ac, const IList* pList) +{ + __pBundle = bundle_create(); + SysTryReturnResult(NID_APP, __pBundle != null, E_OUT_OF_MEMORY, "Bundle creation failure."); + + return CreateAppControlArg(__pBundle, ac, pList); +} + + +result +_AppArg::Construct(const _AppControlImpl& ac, const String* pUri, const String* pMime, const IMap* pList) +{ + __pBundle = bundle_create(); + SysTryReturnResult(NID_APP, __pBundle != null, E_OUT_OF_MEMORY, "Bundle creation failure."); + + return CreateAppControlArg(__pBundle, ac, pUri, pMime, pList); +} + + +result +_AppArg::Construct(const _SqlDataControlImpl& dc, _DataControlRequestType requestType, const IList* pList) +{ + __pBundle = bundle_create(); + SysTryReturnResult(NID_APP, __pBundle != null, E_OUT_OF_MEMORY, "Bundle creation failure."); + + return CreateSqlDataControlArg(__pBundle, dc, requestType, pList); +} + + +result +_AppArg::Construct(const _MapDataControlImpl& dc, _DataControlRequestType requestType, const IList* pList) +{ + __pBundle = bundle_create(); + SysTryReturnResult(NID_APP, __pBundle != null, E_OUT_OF_MEMORY, "Bundle creation failure."); + + return CreateMapDataControlArg(__pBundle, dc, requestType, pList); +} + + +result +_AppArg::ConstructResult(const _AppArg& arg, const IList* pList) +{ + int ret = aul_create_result_bundle(arg.GetBundle(), &__pBundle); + SysTryReturnResult(NID_APP, __pBundle != null, E_INVALID_STATE, "Bundle creatioin from service handle failure : %d.", ret); + + return CreateResultArg(__pBundle, pList); +} + + +result +_AppArg::ConstructResult(const _AppArg& arg, const IMap* pMap) +{ + int ret = aul_create_result_bundle(arg.GetBundle(), &__pBundle); + SysTryReturnResult(NID_APP, __pBundle != null, E_INVALID_STATE, "Bundle creatioin from service handle failure : %d.", ret); + + return CreateResultArg(__pBundle, pMap); +} + + +result +_AppArg::Construct(bundle* b) +{ + __pBundle = bundle_dup(b); + SysTryReturnResult(NID_APP, __pBundle != null, E_INVALID_STATE, "Bundle creatioin from service handle failure."); + + return E_SUCCESS; +} + + +result +_AppArg::ConstructForAppLaunchCondition(const String& condition, const IList* pList) +{ + __pBundle = bundle_create(); + SysTryReturnResult(NID_APP, __pBundle != null, E_OUT_OF_MEMORY, "Bundle creation failure."); + + return CreateAppLaunchConditionArg(__pBundle, condition, pList); +} + + +ArrayList* +_AppArg::GetArgListN(int num) const +{ + bundle* pBundle = __pBundle; + SysTryReturn(NID_APP, pBundle != null, null, E_INVALID_STATE, "[E_INVALID_STATE] Improper bundle state."); + + ArrayList* pList = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + + pList->Construct(); + + const char* p = NULL; + _AppHandler launch_type = GetHandler(pBundle); + + switch (launch_type) + { + case _APP_HANDLER_APPCONTROL: + // request Id + // [FIXME] proper request Id required + pList->Add(*new (std::nothrow) String(GetRequestId(num))); + + // category + p = appsvc_get_category(pBundle); + if (p) + { + pList->Add(*new (std::nothrow) String(p)); + } + else + { + pList->Add(*new (std::nothrow) String(L"")); + } + + // MIME type + p = appsvc_get_mime(pBundle); + if (p) + { + pList->Add(*new (std::nothrow) String(p)); + } + else + { + pList->Add(*new (std::nothrow) String(L"")); + } + + // URI scheme + p = appsvc_get_uri(pBundle); + if (p) + { + pList->Add(*new (std::nothrow) String(p)); + } + else + { + pList->Add(*new (std::nothrow) String(L"")); + } + + break; + + case _APP_HANDLER_DATACONTROL: + // appId + AddListFromBundle(pList, pBundle, OSP_K_APPID); + // request type + AddListFromBundle(pList, pBundle, OSP_K_DATACONTROL_REQUEST_TYPE); + // reqId + AddListFromBundle(pList, pBundle, OSP_K_REQUEST_ID); + // providerId + AddListFromBundle(pList, pBundle, OSP_K_DATACONTROL_PROVIDER); + break; + + case _APP_HANDLER_LAUNCH_COND: + pList->Add(*new (std::nothrow) String(LEGACY_LAUNCH_REASON_CONDITIONAL)); + AddListFromBundle(pList, pBundle, OSP_K_COND); + break; + + case _APP_HANDLER_LAUNCH_NORMAL: + pList->Add(*new (std::nothrow) String(LEGACY_LAUNCH_REASON_NORMAL)); + pList->Add(*new (std::nothrow) String(L"osp.operation.MAIN")); + break; + + default: + SysLog(NID_APP, "Invalid handler type"); + break; + } + + SetArgList(__pBundle, pList); + + return pList; +} + + +ArrayList* +_AppArg::GetArgListN(void) const +{ + SysTryReturn(NID_APP, __pBundle != null, null, E_INVALID_STATE, "[E_INVALID_STATE] Improper bundle state."); + + ArrayList* pList = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + + pList->Construct(); + + SetArgList(__pBundle, pList); + + return pList; +} + +// the returned map is allocated using SingleObjectDeleter +HashMap* +_AppArg::GetArgMapN(void) const +{ + SysTryReturn(NID_APP, __pBundle != null, null, E_INVALID_STATE, "[E_INVALID_STATE] Improper bundle state."); + + HashMap* pHashMap = new (std::nothrow) HashMap(SingleObjectDeleter); + SysTryReturn(NID_APP, pHashMap != null, null, E_OUT_OF_MEMORY, "HashMap creation failure."); + + pHashMap->Construct(); + + SetArgMap(__pBundle, pHashMap); + + if (pHashMap->GetCount() == 0) + { + // [FIXME] temporary resolution for PolarisOffice + const char* p = appsvc_get_uri(__pBundle); + if (p == null) + { + delete pHashMap; + return null; + } + else + { + pHashMap->Add(new (std::nothrow) String(L"reqId"), new (std::nothrow) String(L"-1")); + pHashMap->Add(new (std::nothrow) String(L"path1"), new (std::nothrow) String(L"")); + pHashMap->Add(new (std::nothrow) String(L"path2"), new (std::nothrow) String(L"")); + pHashMap->Add(new (std::nothrow) String(L"path3"), new (std::nothrow) String(L"")); + pHashMap->Add(new (std::nothrow) String(L"path"), new (std::nothrow) String(p)); + + return pHashMap; + } + } + + ArrayList* pList = _AppMessageImpl::GetValueArray(__pBundle, OSP_K_ARG); + if (pList) + { + pHashMap->Add(new (std::nothrow) String(TIZEN_APPCONTROL_DATA_LEGACY), pList); + } + return pHashMap; +} + +static bool +IsInternalKey(const char* pKey) +{ + if (strncmp(BUNDLE_KEY_PREFIX_AUL, pKey, strlen(BUNDLE_KEY_PREFIX_AUL)) == 0) + { + return true; + } + + if (strncmp(BUNDLE_KEY_PREFIX_SERVICE, pKey, strlen(BUNDLE_KEY_PREFIX_SERVICE)) == 0) + { + return true; + } + + if (strncmp(BUNDLE_KEY_PREFIX_OSP, pKey, strlen(BUNDLE_KEY_PREFIX_OSP)) == 0) + { + return true; + } + + return false; +} + +static void +BundleIterFnCb(const char* pKey, const int type, const bundle_keyval_t* pVal, void* pData) +{ + HashMap* pMap = static_cast(pData); + + if (pKey && pVal && pMap) + { + if (IsInternalKey(pKey)) + { + //SysLog(NID_APP, "(%s)", pKey); + return; + } + + size_t size = 0; + char* pStr = NULL; + switch (type) + { + case BUNDLE_TYPE_STR: + bundle_keyval_get_basic_val(const_cast(pVal), reinterpret_cast(&pStr), &size); + if (pStr) + { + SysLog(NID_APP, "(%s, %s)", pKey, pStr); + pMap->Add(new (std::nothrow) String(pKey), new (std::nothrow) String(pStr)); + } + break; + case BUNDLE_TYPE_STR_ARRAY: + { + void** pArr = NULL; + bundle_keyval_get_array_val(const_cast(pVal), &pArr, &size, NULL); + if (pArr && size > 0) + { + String str = static_cast(*pArr); + for (size_t i = 1; i < size; i++) + { + str += L';'; + str += static_cast(*(pArr + i)); + } + + SysLog(NID_APP, "(%s, %ls)", pKey, str.GetPointer()); + pMap->Add(new (std::nothrow) String(pKey), new (std::nothrow) String(str)); + } + else + { + SysLog(NID_APP, "No entry for str array %s(%d)", pKey, size); + } + } + break; + default: + SysLog(NID_APP, "Invalid type for %s : %d", pKey, type); + break; + } + } +} + +result +_AppArg::SetArgMap(bundle* pBundle, HashMap* pMap) +{ + bundle_foreach(pBundle, BundleIterFnCb, reinterpret_cast(pMap)); + + return E_SUCCESS; +} + +result +_AppArg::SetArgList(bundle* pBundle, ArrayList* pList) +{ + // actual argument below + int len = 0; + const char** pa = appsvc_get_data_array(pBundle, OSP_K_ARG, &len); + if (pa) + { + for (int i = 0; i < len; i++) + { + if (pa[i]) + { + //SysLog(NID_APP, "%d/%dth arg [%s]", i, len, pa[i]); + pList->Add(*new (std::nothrow) String(pa[i])); + } + } + } + + const char* p = appsvc_get_uri(pBundle); + if (p) + { + pList->Add(*new (std::nothrow) String(p)); + SysLog(NID_APP, "argument is %s", p); + } + + String tmp; + p = appsvc_get_data(pBundle, SMS_KEY_SERVICE_CALLER); + if (p) + { + tmp.Format(60, L"%s:%s", SMS_KEY_SERVICE_CALLER, p); + pList->Add(*new (std::nothrow) String(tmp)); + SysLog(NID_APP, "service_caller is %s", p); + } + + p = appsvc_get_data(pBundle, SMS_KEY_SERVICE_DATA); + if (p) + { + tmp.Format(60, L"%s:%s", SMS_KEY_SERVICE_DATA, p); + pList->Add(*new (std::nothrow) String(tmp)); + SysLog(NID_APP, "service_data is set"); + } + + p = appsvc_get_data(pBundle, SAMSUNG_ACCOUNT_KEY_CLIENT_ID); + if (p) + { + tmp.Format(60, L"%s:%s", SAMSUNG_ACCOUNT_KEY_CLIENT_ID, p); + pList->Add(*new (std::nothrow) String(tmp)); + SysLog(NID_APP, "client_id is %s", p); + } + + p = appsvc_get_data(pBundle, SAMSUNG_ACCOUNT_KEY_CLIENT_SECRET); + if (p) + { + tmp.Format(60, L"%s:%s", SAMSUNG_ACCOUNT_KEY_CLIENT_SECRET, p); + pList->Add(*new (std::nothrow) String(tmp)); + SysLog(NID_APP, "client_secret is %s", p); + } + + p = appsvc_get_data(pBundle, SAMSUNG_ACCOUNT_KEY_SERVICE_CATEGORY); + if (p) + { + tmp.Format(60, L"%s:%s", SAMSUNG_ACCOUNT_KEY_SERVICE_CATEGORY, p); + pList->Add(*new (std::nothrow) String(tmp)); + SysLog(NID_APP, "service_category is %s", p); + } + + return E_SUCCESS; +} + + +String +_AppArg::GetValue(const char* key) const +{ + const char* p = appsvc_get_data(__pBundle, key); + return String(p); +} + + +_AppHandler +_AppArg::GetHandler(bundle* b) +{ + SysTryReturn(NID_APP, b != null, _APP_HANDLER_NONE, E_INVALID_STATE, "[E_INVALID_STATE] Improper bundle state."); + + const char* p = null; + + p = appsvc_get_data(b, OSP_K_LAUNCH_TYPE); + + if (p) + { + if (strcmp(p, OSP_V_LAUNCH_TYPE_DATACONTROL) == 0) + { + return _APP_HANDLER_DATACONTROL; + } + + if (strcmp(p, OSP_V_LAUNCH_TYPE_APPCONTROL) == 0) + { + SysLog(NID_APP, "Building AppControl arguments."); + + return _APP_HANDLER_APPCONTROL; + } + else + { + // not appcontrol nor datacontrol => normal launch or condlaunch + p = appsvc_get_data(b, OSP_K_COND); + if (p) + { + SysLog(NID_APP, "Building Conditional AppLaunch arguments."); + return _APP_HANDLER_LAUNCH_COND; + } + else + { + SysLog(NID_APP, "Building Normal AppLaunch arguments."); + return _APP_HANDLER_LAUNCH_NORMAL; + } + } + } + + // fallback + return _APP_HANDLER_APPCONTROL; +} + + +int +_AppArg::GetCallerPid(bundle* pBundle) +{ + const char* pBundleValue = bundle_get_val(pBundle, AUL_K_ORG_CALLER_PID); + if (pBundleValue == NULL) + { + pBundleValue = bundle_get_val(pBundle, AUL_K_CALLER_PID); + } + + SysTryReturn(NID_APP, pBundleValue != null, -1, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Object not found."); + + return atoi(pBundleValue); +} + + +AppId +_AppArg::GetCallerAppId(void) const +{ + pid_t callerPid = GetCallerPid(); + SysTryReturn(NID_APP, callerPid > 0, L"", E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Wrong process id: %d.", callerPid); + + char appId[PATH_MAX] = {0, }; + SysTryReturn(NID_APP, aul_app_get_appid_bypid(callerPid, appId, sizeof(appId)) == AUL_R_OK, L"", E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Object not found for %d.", callerPid); + + return String(appId); +} + + +AppId +_AppArg::GetCalleeAppId(void) const +{ + const char* pBundleValue = bundle_get_val(__pBundle, AUL_K_CALLEE_PID); + + SysTryReturn(NID_APP, pBundleValue != null, L"", E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Object not found."); + + pid_t calleePid = atoi(pBundleValue); + SysTryReturn(NID_APP, calleePid > 0, L"", E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Wrong process id: %d.", calleePid); + + char appId[PATH_MAX] = {0, }; + SysTryReturn(NID_APP, aul_app_get_appid_bypid(calleePid, appId, sizeof(appId)) == AUL_R_OK, L"", E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Object not found for %d.", calleePid); + + String temp; + String retVal = appId; + // [INFO] ugly code for submode callee + retVal.SubString(11, temp); + if (temp == L"_AppControl") + { + String id; + retVal.SubString(0, 10, id); + const String& name = _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(id); + + retVal = id + L'.' + name; + SysLog(NID_APP, "Converted caller Id is %ls", retVal.GetPointer()); + } + + return retVal; +} + + +void +_AppArg::AddListFromBundle(ArrayList* pList, bundle* bk, const char* key) +{ + bundle* pBundle = bk; + + const char* p = appsvc_get_data(pBundle, key); + if (p) + { + pList->Add(*new (std::nothrow) String(p)); + } + else + { + pList->Add(*new (std::nothrow) String(L"")); + } +} + + +result +_AppArg::AddStrArray(bundle* b, const String& key, const IList* pList) +{ + std::unique_ptr pKey(_StringConverter::CopyToCharArrayN(key)); + + return AddStrArray(b, pKey.get(), pList); +} + + +result +_AppArg::AddStrArray(bundle* b, const char* key, const IList* pList) +{ + bundle* pb = b; + SysTryReturnResult(NID_APP, pb != NULL, E_INVALID_ARG, "Empty bundle."); + + if (pList == null || pList->GetCount() == 0) + { + SysLog(NID_APP, "No element added for bundle."); + return E_SUCCESS; + } + + int i = 0; + const int count = pList->GetCount(); + + const char** pSa = new (std::nothrow) const char*[count]; + SysTryReturnResult(NID_APP, pSa != null, E_OUT_OF_MEMORY, "Memory allocation failure with cound %d.", count); + + for (i = 0; i < count; i++) + { + pSa[i] = null; + + const String* pStr = static_cast(pList->GetAt(i)); + if (pStr) + { + pSa[i] = _StringConverter::CopyToCharArrayN(*pStr); + } + } + + result r = E_SUCCESS; + + int ret = bundle_add_str_array(pb, key, pSa, count); + if (ret >= 0) + { + _AppMessageImpl::AddData(pb, pList); + } + else + { + SysLog(NID_APP, "Bundle add failre :%d.", ret); + r = E_SYSTEM; + } + + _AppMessageImpl::AddData(pb, pList); + +//CATCH: + for (i = 0; i < count; i++) + { + delete[] pSa[i]; + } + + delete[] pSa; + + return r; +} + + +result +_AppArg::AddStrMap(bundle* b, const IMap* pMap) +{ + bundle* pb = b; + SysTryReturnResult(NID_APP, pb != NULL, E_INVALID_ARG, "Empty bundle."); + + if (pMap == null || pMap->GetCount() == 0) + { + SysLog(NID_APP, "No element added for bundle."); + return E_SUCCESS; + } + + std::unique_ptr pEnum (pMap->GetMapEnumeratorN()); + while(pEnum->MoveNext() == E_SUCCESS) + { + const String* pKey = static_cast(pEnum->GetKey()); + const Object* pObj = pEnum->GetValue(); + + if (pKey && pObj) + { + if (typeid(*pObj) == typeid(const String)) + { + const String* pVal = static_cast(pEnum->GetValue()); + if (pVal) + { + _AppMessageImpl::AddData(pb, *pKey, *pVal); + } + } + else if (typeid(*pObj) == typeid(const ArrayList)) + { + const ArrayList* pList = static_cast(pEnum->GetValue()); + if (pList && *pKey == TIZEN_APPCONTROL_DATA_LEGACY) + { + SysLog(NID_APP, "Legacy AppControl argument"); + _AppArg::AddStrArray(pb, OSP_K_ARG, pList); + _AppMessageImpl::AddData(pb, pList); + } + } + else if (typeid(*pObj) == typeid(const ByteBuffer)) + { + SysLog(NID_APP, "ByteBuffer type"); + } + } + } + + return E_SUCCESS; +} + + +result +_AppArg::FillMapFromList(IMap* pMap, const IList* pList) +{ + if (pMap == null || pList == null) + { + return E_SUCCESS; + } + + std::unique_ptr pEnum(pList->GetEnumeratorN()); + SysTryReturnResult(NID_APP, pEnum != null, E_OUT_OF_MEMORY, "Getting enumerator failed."); + + String key; + String value; + while (pEnum->MoveNext() == E_SUCCESS) + { + String* pStr = dynamic_cast(pEnum->GetCurrent()); + + int index = -1; + if (pStr == null || pStr->IndexOf(L':', 0, index) != E_SUCCESS) + { + continue; + } + pStr->SubString(0, index, key); + if (key.IsEmpty()) + { + continue; + } + + pStr->SubString(index + 1, value); + + pMap->Add(new String(key), new String(value)); + + SysLog(NID_APP, "Added (%ls, %ls).", key.GetPointer(), value.GetPointer()); + } + + return E_SUCCESS; +} + + +result +_AppArg::FillLegacyAppControlResult(IList& list, int res, const IMap* pArgs, const Tizen::Base::String& aId) +{ + switch (res) + { + case APP_CTRL_RESULT_SUCCEEDED: + list.Add(* new (std::nothrow) String(APPCONTROL_RESULT_SUCCEEDED)); + break; + case APP_CTRL_RESULT_CANCELED: + list.Add(* new (std::nothrow) String(APPCONTROL_RESULT_CANCELED)); + return E_SUCCESS; + case APP_CTRL_RESULT_TERMINATED: + list.Add(* new (std::nothrow) String(APPCONTROL_RESULT_TERMINATED)); + return E_SUCCESS; + case APP_CTRL_RESULT_ABORTED: + list.Add(* new (std::nothrow) String("aborted")); + return E_SUCCESS; + //case APP_CTRL_RESULT_FAILED: + default: + list.Add(* new (std::nothrow) String(APPCONTROL_RESULT_FAILED)); + return E_SUCCESS; + } + + if (pArgs == null) + { + return E_SUCCESS; + } + + bool isPathRegistered = false; + // handle APP_CTRL_RESULT_SUCCEEDED only + std::unique_ptr pMapEnum(pArgs->GetMapEnumeratorN()); + + while(pMapEnum->MoveNext() == E_SUCCESS) + { + String* pKey = static_cast(pMapEnum->GetKey()); + if (pKey == null) + { + SysLog(NID_APP, "Invalid entry."); + continue; + } + + if (*pKey == L"path" || *pKey == L"http://tizen.org/appcontrol/data/selected") + { + if (!isPathRegistered) + { + isPathRegistered = true; + } + else + { + SysLog(NID_APP, "Selected path key is already registered."); + continue; + } + } + + String* pVal = dynamic_cast(pMapEnum->GetValue()); + if (pVal) + { + SysLog(NID_APP, "Adding value (%ls).", pVal->GetPointer()); + + StringTokenizer strTok(*pVal, L';'); + if (strTok.GetTokenCount() == 0) + { + list.Add(* new (std::nothrow) String(*pVal)); + } + else + { + String token; + while(strTok.HasMoreTokens()) + { + strTok.GetNextToken(token); + list.Add(* new (std::nothrow) String(token)); + SysLog(NID_APP, "Adding tokenized value (%ls).", token.GetPointer()); + } + } + } + } + + return E_SUCCESS; +} + + +ArrayList* +_AppArg::GetListN(bundle* b, const char* key) +{ + bundle* pb = b; + if (pb == null) + { + return null; + } + + const char** pValArray = null; + int len = 0; + + pValArray = appsvc_get_data_array(b, key, &len); + if (len == 0 || pValArray == null) + { + return null; + } + + ArrayList* pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); + + pList->Construct(); + + for (int i = 0; i < len; i++) + { + pList->Add(*new (std::nothrow) String(pValArray[i])); + } + + return pList; +} + + +result +_AppArg::CreateLaunchArg(bundle* b, const String& arg) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + + bundle* pb = b; + + if (!arg.IsEmpty()) + { + const char** pSa = new (std::nothrow) const char*[1]; + SysTryReturnResult(NID_APP, pSa != null, E_OUT_OF_MEMORY, "Insufficient memory."); + pSa[0] = _StringConverter::CopyToCharArrayN(arg); + bundle_add_str_array(pb, OSP_K_ARG, pSa, 1); + + bundle_add(pb, TIZEN_NOTIFICATION_DATA, pSa[0]); + + delete[] pSa[0]; + delete[] pSa; + } + + bundle_add(pb, OSP_K_LAUNCH_TYPE, OSP_V_LAUNCH_TYPE_LAUNCH); + + return E_SUCCESS; +} + + +result +_AppArg::CreateLaunchArg(bundle* b, const IList* pList) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + + bundle* pb = b; + + AddStrArray(pb, OSP_K_ARG, pList); + + bundle_add(pb, OSP_K_LAUNCH_TYPE, OSP_V_LAUNCH_TYPE_LAUNCH); + + return E_SUCCESS; +} + + +result +_AppArg::CreateAppLaunchConditionArg(bundle* b, const String& condition, const IList* pList) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + SysLog(NID_APP, ""); + + bundle* pb = b; + + AddStrArray(pb, OSP_K_ARG, pList); + + std::unique_ptr p(_StringConverter::CopyToCharArrayN(condition)); + if (p) + { + bundle_add(pb, OSP_K_COND, p.get()); + } + + bundle_add(pb, OSP_K_LAUNCH_TYPE, OSP_V_LAUNCH_TYPE_CONDTION); + + return E_SUCCESS; +} + + +result +_AppArg::CreateAppControlArg(bundle* b, const _AppControlImpl& ac, const IList* pList) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + + bundle* pb = b; + + AddStrArray(pb, OSP_K_ARG, pList); + + std::unique_ptr pOperation(_StringConverter::CopyToCharArrayN(ac._opId)); + if (pOperation) + { + appsvc_set_operation(pb, pOperation.get()); + } + + bundle_add(pb, OSP_K_LAUNCH_TYPE, OSP_V_LAUNCH_TYPE_APPCONTROL); + + return E_SUCCESS; +} + + +result +_AppArg::CreateAppControlArg(bundle* b, const _AppControlImpl& ac, const String* pUriData, const String* pMimeType, const IMap* pList) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + + bundle* pb = b; + + std::unique_ptr pOperation(_StringConverter::CopyToCharArrayN(ac._opId)); + if (pOperation.get()) + { + appsvc_set_operation(pb, pOperation.get()); + } + + if (pUriData) + { + std::unique_ptr pUri(_StringConverter::CopyToCharArrayN(*pUriData)); + if (pUri.get()) + { + appsvc_set_uri(pb, pUri.get()); + } + } + + if (pMimeType) + { + std::unique_ptr pMime(_StringConverter::CopyToCharArrayN(*pMimeType)); + if (pMime.get()) + { + appsvc_set_mime(pb, pMime.get()); + } + } + + AddStrMap(pb, pList); + + bundle_add(pb, OSP_K_LAUNCH_TYPE, OSP_V_LAUNCH_TYPE_APPCONTROL); + + return E_SUCCESS; +} + + +namespace +{ +const int MAX_LEN_DATA_CONTROL_REQ_TYPE = 8; +} +result +_AppArg::CreateSqlDataControlArg(bundle* b, const _SqlDataControlImpl& dc, _DataControlRequestType requestType, + const IList* pArgList) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + + bundle_add(b, OSP_K_LAUNCH_TYPE, OSP_V_LAUNCH_TYPE_DATACONTROL); + + char dataControlRequestType[MAX_LEN_DATA_CONTROL_REQ_TYPE] = {0, }; + snprintf(dataControlRequestType, MAX_LEN_DATA_CONTROL_REQ_TYPE, "%d", static_cast(requestType)); + bundle_add(b, OSP_K_DATACONTROL_REQUEST_TYPE, dataControlRequestType); + + std::unique_ptr pProvider(_StringConverter::CopyToCharArrayN(dc.__providerId)); + if (pProvider) + { + bundle_add(b, OSP_K_DATACONTROL_PROVIDER, pProvider.get()); + } + + AddStrArray(b, OSP_K_ARG, pArgList); + + return E_SUCCESS; +} + + +result +_AppArg::CreateMapDataControlArg(bundle* b, const _MapDataControlImpl& dc, _DataControlRequestType requestType, + const IList* pArgList) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + + bundle_add(b, OSP_K_LAUNCH_TYPE, OSP_V_LAUNCH_TYPE_DATACONTROL); + + char dataControlRequestType[MAX_LEN_DATA_CONTROL_REQ_TYPE] = {0, }; + snprintf(dataControlRequestType, MAX_LEN_DATA_CONTROL_REQ_TYPE, "%d", static_cast < int >(requestType)); + bundle_add(b, OSP_K_DATACONTROL_REQUEST_TYPE, dataControlRequestType); + + std::unique_ptr pProvider(_StringConverter::CopyToCharArrayN(dc.__providerId)); + if (pProvider) + { + bundle_add(b, OSP_K_DATACONTROL_PROVIDER, pProvider.get()); + } + + AddStrArray(b, OSP_K_ARG, pArgList); + + return E_SUCCESS; +} + + +result +_AppArg::CreateResultArg(bundle* b, const IList* pList) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + + bundle* pb = b; + + AddStrArray(pb, OSP_K_ARG, pList); + + _AppMessageImpl::AddData(pb, pList); + + return E_SUCCESS; +} + + +result +_AppArg::CreateResultArg(bundle* b, const IMap* pMap) +{ + SysAssertf(b != null, "Valid bundle should be supplied"); + + bundle* pb = b; + + AddStrMap(pb, pMap); + + return E_SUCCESS; +} + + +bundle* +_AppArg::CreateBundleFromSvc(void* svc) +{ + bundle* pBundle = GetBundleFromSvc(svc); + if (pBundle) + { + return bundle_dup(pBundle); + } + + return null; +} + + +bundle* +_AppArg::GetBundleFromSvc(void* svc) +{ + struct DummyS + { + int dummy1; + int dummy2; + bundle* pData; + }; + + DummyS* pDummy = static_cast(svc); + + if (pDummy && pDummy->pData) + { + return pDummy->pData; + } + + return NULL; +} + + +String +_AppArg::GetRequestId(int num) +{ + String str; + str.Format(10, L"req%05d", num); + return str; +} + + +int +_AppArg::GetRequestId(const String& str) +{ + int i = 0; + String sub; + + result r = str.SubString(3, sub); + SysTryReturn(NID_APP, !IsFailed(r), -1, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = Integer::Parse(sub, i); + SysTryReturn(NID_APP, !IsFailed(r), -1, r, "[%s] Propagating.", GetErrorMessage(r)); + + return i; +} + + +void +_AppArg::UpdateAppId(bundle* b, const AppId& appId) +{ + SysTryReturnVoidResult(NID_APP, b != null, E_INVALID_STATE, "[E_INVALID_STATE] Improper bundle state."); + + std::unique_ptr pId(_StringConverter::CopyToCharArrayN(appId)); + SysTryReturnVoidResult(NID_APP, pId != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Converting %ls failed.", appId.GetPointer()); + + bundle_add(b, OSP_K_APPID, pId.get()); + + appsvc_set_appid(b, pId.get()); +} + + +void +_AppArg::UpdateRequestId(bundle* pBundle, int reqId) +{ + SysTryReturnVoidResult(NID_APP, pBundle != null, E_INVALID_STATE, "[E_INVALID_STATE] Improper bundle state."); + + if (reqId < 0) + { + //SysLog(NID_APP, "Requested ID is %d", reqId); + return; + } + + char buffer[32] = {0, }; + snprintf(buffer, 32, "%d", reqId); + bundle_add(pBundle, OSP_K_REQUEST_ID, buffer); +} + + +int +_AppArg::GetRequestIdFromBundle(bundle* pBundle) +{ + const char* p = appsvc_get_data(pBundle, OSP_K_REQUEST_ID); + if (p == NULL) + { + return -1; + } + + int i = atoi(p); + return (i < 0) ? -1 : i; +} + + +result +_AppArg::UpdateWindowHandle(bundle* pBundle, long handle) +{ + if (handle == -1) + { + SysLog(NID_APP, "Invalid window handle."); + return E_SUCCESS; + } + + char handleName[32] = {0, }; + snprintf(handleName, 32, "%ld", handle); + + bundle_add(pBundle, BUNDLE_KEY_WINDOW, handleName); + SysLog(NID_APP, "Window Handle 0x%x added.", handle); + + return E_SUCCESS; +} + + +void +_AppArg::PrintSvcHandle(void* svc) +{ + service_h service = static_cast(svc); + + if (service == null) + { + return; + } + + Print(GetBundleFromSvc(service)); +} + + +static void +BundlePrintIterFnCb(const char* pKey, const int type, const bundle_keyval_t* pVal, void* pData) +{ + if (pKey && pVal) + { + size_t size = 0; + char* pStr = NULL; + switch (type) + { + case BUNDLE_TYPE_STR: + bundle_keyval_get_basic_val(const_cast(pVal), reinterpret_cast(&pStr), &size); + if (pStr) + { + SysLog(NID_APP, "(%s, %s)", pKey, pStr); + } + break; + default: + SysLog(NID_APP, "Invalid type for %s : %d", pKey, type); + break; + } + } +} + +void +_AppArg::Print(bundle* b) +{ + if (b == null) + { + return; + } + + const char* p = null; + p = appsvc_get_data(b, AUL_K_CALLER_PID); + if (p) + { + SysLog(NID_APP, "CallerPId[%s]", p); + } + + p = appsvc_get_data(b, AUL_K_WAIT_RESULT); + if (p) + { + SysLog(NID_APP, "WaitResult[%s]", p); + } + + p = appsvc_get_data(b, OSP_K_COND); + if (p) + { + SysLog(NID_APP, "Condition[%s]", p); + } + + p = appsvc_get_operation(b); + if (p) + { + SysLog(NID_APP, "operation[%s]", p); + } + + p = appsvc_get_uri(b); + if (p) + { + SysLog(NID_APP, "uri[%s]", p); + } + + p = appsvc_get_mime(b); + if (p) + { + SysLog(NID_APP, "mime[%s]", p); + } + + p = appsvc_get_category(b); + if (p) + { + SysLog(NID_APP, "Category[%s]", p); + } + + bundle_foreach(b, BundlePrintIterFnCb, NULL); + + int len = 0; + const char** pa = appsvc_get_data_array(b, OSP_K_ARG, &len); + if (pa) + { + for (int i = 0; i < len; i++) + { + if (pa[i]) + { + SysLog(NID_APP, "%dth arg [%s]", i, pa[i]); + } + } + } +} + +} } // Tizen::App diff --git a/src/app/FApp_AppControlEvent.cpp b/src/app/FApp_AppControlEvent.cpp new file mode 100644 index 0000000..89dd2b5 --- /dev/null +++ b/src/app/FApp_AppControlEvent.cpp @@ -0,0 +1,77 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlEvent.cpp + * @brief This is the implementation for the _AppControlEvent.cpp class. + */ + +#include + +#include "FApp_AppControlEvent.h" +#include "FApp_AppControlEventArg.h" +#include "FApp_IAppControlSysEventListener.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace App +{ + +void +_AppControlEvent::FireImpl(IEventListener& listener, const IEventArg& arg) +{ + _IAppControlSysEventListener* pListener = dynamic_cast<_IAppControlSysEventListener*>(&listener); + + if (pListener) + { + const _AppControlEventArg* pEventArg = dynamic_cast(&arg); + + if (pEventArg != null) + { + pListener->OnAppControlEventReceivedN(pEventArg->GetRequestId(), pEventArg->GetAppArg(), pEventArg->GetResult()); + + return; + } + + const _NativeAppControlEventArg* pNativeArg = dynamic_cast(&arg); + + if (pNativeArg != null) + { + pListener->OnAppControlEventReceivedN(pNativeArg->GetRequestId(), pNativeArg->GetResult(), pNativeArg->GetArgs()); + + return; + } + + const _AppControlStartEventArg* pStartEventArg = dynamic_cast(&arg); + + if (pStartEventArg != null) + { + pListener->OnAppControlEventReceivedN(pStartEventArg->GetRequestId(), pStartEventArg->GetAppId(), pStartEventArg->GetOperationId()); + + return; + } + + SysLog(NID_APP, "Invalid AppControl arguments : listener(0x%x), arg(0x%x)", pListener, &arg); + } + else + { + SysLog(NID_APP, "Invalid AppControl listener : listener(0x%x), arg(0x%x)", pListener, &arg); + } +} + +} } // Tizen::App diff --git a/src/app/FApp_AppControlEventArg.cpp b/src/app/FApp_AppControlEventArg.cpp new file mode 100644 index 0000000..bfbec6b --- /dev/null +++ b/src/app/FApp_AppControlEventArg.cpp @@ -0,0 +1,89 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlEventArg.cpp + * @brief This is the implementation for the _AppControlEventArg.cpp class. + */ + +#include + +#include +#include +#include +#include + +#include "FApp_AppControlEventArg.h" +#include "FApp_AppArg.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +_AppControlEventArg::~_AppControlEventArg(void) +{ + SysLog(NID_APP, "Deleting launch argument..."); + delete __pArg; +} + +_NativeAppControlEventArg::_NativeAppControlEventArg(int reqId, int res, const IMap* pArg) + : __reqId(reqId) + , __result(res) + , __pArgs(null) +{ + if (pArg == null) + { + return; + } + + HashMap* pMap = new (std::nothrow) HashMap(SingleObjectDeleter); + SysTryReturnVoidResult(NID_APP, pMap, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); + + pMap->Construct(); + + std::unique_ptr pMapEnum(pArg->GetMapEnumeratorN()); + + while(pMapEnum->MoveNext() == E_SUCCESS) + { + String* pKey = dynamic_cast(pMapEnum->GetKey()); + String* pVal = dynamic_cast(pMapEnum->GetValue()); + + if (pKey == null || pVal == null) + { + continue; + } + + pMap->Add(new (std::nothrow) String(*pKey), new (std::nothrow) String(*pVal)); + } + + __pArgs = pMap; + + return; +} + +_NativeAppControlEventArg::~_NativeAppControlEventArg(void) +{ + if (__pArgs) + { + SysLog(NID_APP, "Deleting native AppControl argument."); + delete __pArgs; + } +} + +} } // Tizen::App diff --git a/src/app/FApp_AppControlEventArg.h b/src/app/FApp_AppControlEventArg.h new file mode 100644 index 0000000..ec1212f --- /dev/null +++ b/src/app/FApp_AppControlEventArg.h @@ -0,0 +1,167 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlEventArg.h + * @brief This is the header file of _AppControlEventArg class. + */ + +#ifndef _FAPP_INTERNAL_APP_CONTROL_EVENT_ARG_H_ +#define _FAPP_INTERNAL_APP_CONTROL_EVENT_ARG_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Base { namespace Collection { +class IList; +class IMap; +}}} + +namespace Tizen { namespace App +{ + +class _AppArg; + +/** + * @class _AppControlEventArg + * @brief + */ +class _AppControlEventArg + : public Tizen::Base::Object + , public Tizen::Base::Runtime::IEventArg +{ +public: + _AppControlEventArg(int reqId, _AppArg* p, int res) + : __reqId(reqId) + , __pArg(p) + , __result(res) + { + } + + virtual ~_AppControlEventArg(void); + + int GetRequestId(void) const + { + return __reqId; + } + + _AppArg* GetAppArg(void) const + { + return __pArg; + } + + int GetResult(void) const + { + return __result; + } + +private: + _AppControlEventArg(const _AppControlEventArg& rhs); + + _AppControlEventArg& operator =(const _AppControlEventArg& rhs); + +private: + int __reqId; + _AppArg* __pArg; + int __result; +}; // _AppControlEventArg + +/** + * @class _NativeAppControlEventArg + * @brief + */ +class _NativeAppControlEventArg + : public Tizen::Base::Object + , public Tizen::Base::Runtime::IEventArg +{ +public: + _NativeAppControlEventArg(int reqId, int res, const Tizen::Base::Collection::IMap* pArgs); + + virtual ~_NativeAppControlEventArg(void); + + int GetRequestId(void) const + { + return __reqId; + } + + int GetResult(void) const + { + return __result; + } + + const Tizen::Base::Collection::IMap* GetArgs(void) const + { + return __pArgs; + } + +private: + int __reqId; + int __result; + Tizen::Base::Collection::IMap* __pArgs; +}; // _NativeAppControlEventArg + +/** + * @class _AppControlStartEventArg + * @brief + */ +class _AppControlStartEventArg + : public Tizen::Base::Object + , public Tizen::Base::Runtime::IEventArg +{ +public: + _AppControlStartEventArg(int reqId, const AppId& appId, const Tizen::Base::String& operationId) + : __reqId(reqId) + , __appId(appId) + , __operationId(operationId) + { + } + + virtual ~_AppControlStartEventArg(void) + { + } + + int GetRequestId(void) const + { + return __reqId; + } + + AppId GetAppId(void) const + { + return __appId; + } + + Tizen::Base::String GetOperationId(void) const + { + return __operationId; + } + +private: + _AppControlStartEventArg(const _AppControlStartEventArg& rhs); + + _AppControlStartEventArg& operator =(const _AppControlStartEventArg& rhs); + +private: + int __reqId; + AppId __appId; + Tizen::Base::String __operationId; +}; // _AppControlStartEventArg + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_CONTROL_EVENT_ARG_H_ diff --git a/src/app/FApp_AppControlImpl.cpp b/src/app/FApp_AppControlImpl.cpp new file mode 100755 index 0000000..a7287c2 --- /dev/null +++ b/src/app/FApp_AppControlImpl.cpp @@ -0,0 +1,885 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlImpl.cpp + * @brief This is the implementation for the Application Control class. + */ + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "FApp_AppControlImpl.h" +#include "FApp_AppManagerProxy.h" +#include "FApp_AppControlManager.h" +#include "FApp_AppArg.h" +#include "FApp_AppImpl.h" +#include "FApp_AppControlRegistry.h" +#include "FApp_AppMessageImpl.h" +#include "FApp_AppInfo.h" +#include "FAppPkg_PackageManagerImpl.h" +#include "FApp_Aul.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Io; + +namespace +{ + +static const int _REQ_ID_INVALID = -1; + +} + +namespace Tizen { namespace App +{ + +const wchar_t TIZEN_OPERATION_MAIN[] = L"http://tizen.org/appcontrol/operation/main"; +const char TIZEN_APPCONTROL_DATA_LEGACY[] = "http://tizen.org/appcontrol/data/legacyresult"; + +_AppControlImpl::_AppControlImpl(const AppControl& value) + : _appControl(value) + , _reqId(_REQ_ID_INVALID) + , _property(_APPCONTROL_PROPERTY_NONE) + , _processId(_REQ_ID_INVALID) +{ +} + +_AppControlImpl::~_AppControlImpl(void) +{ +} + +AppControl* +_AppControlImpl::CreateN(const String& path, const String& aId, const String& oId, const String& name, int prop) +{ + SysTryReturn(NID_APP, !path.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] Path is empty."); + SysTryReturn(NID_APP, !aId.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] Provider Id is empty."); + SysTryReturn(NID_APP, !oId.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] Operation Id is empty."); + + AppControl* pAc = new (std::nothrow) AppControl; + SysTryReturn(NID_APP, pAc != null, null, E_OUT_OF_MEMORY, "AppControl allocation failure."); + + _AppControlImpl* pImpl = pAc->__pAppControlImpl; + SysTryReturn(NID_APP, pImpl != null, null, E_OUT_OF_MEMORY, "AppControlImpl instance must not be null."); + + pImpl->_path = path; + pImpl->_provider = aId; + pImpl->_opId = oId; + // [FIXME] Proper App name setting + pImpl->_appName = name; + pImpl->_property = prop; + + return pAc; +} + +AppControl* +_AppControlImpl::CreateN(const AppId& appId, const String& operationId, bool changeAppId) +{ + SysTryReturn(NID_APP, !appId.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] appId is empty."); + + AppControl* pAc = new (std::nothrow) AppControl; + SysTryReturn(NID_APP, pAc != null, null, E_OUT_OF_MEMORY, "AppControl allocation failure."); + + _AppControlImpl* pImpl = pAc->__pAppControlImpl; + SysTryReturn(NID_APP, pImpl != null, null, E_OUT_OF_MEMORY, "AppControlImpl instance must not be null."); + + pImpl->_path = appId; + pImpl->_provider = appId; + pImpl->_opId = operationId; + //pImpl->_appName = appId; + pImpl->_property |= (_APPCONTROL_PROPERTY_OSP | _APPCONTROL_PROPERTY_PUBLIC); + + if (changeAppId) + { + pImpl->_property |= _APPCONTROL_PROPERTY_APPID_CHANGE; + } + + return pAc; +} + +AppControl* +_AppControlImpl::CreateN(const AppControl& ac) +{ + const _AppControlImpl* pImpl = GetInstance(ac); + SysTryReturn(NID_APP, pImpl != null, null, E_INVALID_STATE, "AppControlImpl instance must not be null."); + + return CreateN(pImpl->_path, pImpl->_provider, pImpl->_opId, pImpl->_appName, pImpl->_property); +} + +const _AppControlImpl* +_AppControlImpl::GetInstance(const AppControl& ac) +{ + return ac.__pAppControlImpl; +} + +_AppControlImpl* +_AppControlImpl::GetInstance(AppControl& ac) +{ + return ac.__pAppControlImpl; +} + +result +_AppControlImpl::Start(const IList* pDataList, IAppControlEventListener* pListener) +{ + result r = E_SYSTEM; + + if (_property & _APPCONTROL_PROPERTY_SLP) + { + r = StartNative(pDataList, pListener); + } + else if (_property & _APPCONTROL_PROPERTY_OSP) + { + r = StartOsp(pDataList, pListener); + } + else + { + SysLogException(NID_APP, E_SYSTEM, "[E_SYSTEM] Invalid AppControl type(property %d)", _property); + } + + return r; +} + +result +_AppControlImpl::Start(const String* pUriData, const String* pDataType, const IMap* pExtraData, IAppControlResponseListener* pListener) +{ + result r = E_SYSTEM; + + if (_property & _APPCONTROL_PROPERTY_SLP) + { + r = StartNative(pUriData, pDataType, pExtraData, pListener); + } + else if (_property & _APPCONTROL_PROPERTY_OSP) + { + r = StartOsp(pUriData, pDataType, pExtraData, pListener); + } + else + { + SysLogException(NID_APP, E_SYSTEM, "[E_SYSTEM] Invalid AppControl type(property %d)", _property); + } + + return r; +} + +result +_AppControlImpl::FindAndStart(const String& operationId, const String* pUriPattern, const String* pDataType, const String* pCategory, const IMap* pExtraData, IAppControlResponseListener* pListener) +{ + // [FIXME] valid argument size checking required + + std::unique_ptr pBundle(bundle_create()); + SysTryReturnResult(NID_APP, pBundle.get(), E_OUT_OF_MEMORY, "Bundle creation failure."); + + _AppMessageImpl::SetOperation(pBundle.get(), operationId); + + if (pUriPattern) + { + _AppMessageImpl::SetUri(pBundle.get(), *pUriPattern); + } + + if (pDataType) + { + String mimeType = *pDataType; + + if ((*pDataType)[0] == L'.') + { + SysLog(NID_APP, "Extension to MIME conversion for %ls", pDataType->GetPointer()); + +#if 0 + String ext; + pDataType->SubString(1, ext); + + result r = _AppControlManager::GetMimeFromExt(ext, mimeType); + + SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] MIME type conversion failure for %ls.", GetErrorMessage(r), ext.GetPointer()); + + pMimeType = &mimeType; + + SysLog(NID_APP, "Conversion : %ls -> %ls.", pDataType->GetPointer(), pMimeType->GetPointer()); +#endif + } + + _AppMessageImpl::SetMime(pBundle.get(), mimeType); + } + + if (pCategory) + { + _AppMessageImpl::SetCategory(pBundle.get(), *pCategory); + } + + return StartImplicit(pBundle.get(), pExtraData, pListener); +} + +result +_AppControlImpl::StartOsp(const IList* pDataList, IAppControlEventListener* pListener) +{ + result r = E_SUCCESS; + + _AppArg* pArg = new (std::nothrow) _AppArg; + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "Argument allocation failure."); + + pArg->Construct(*this, pDataList); + + _AppControlManager* pImpl = _AppControlManager::GetInstance(); + int req = _REQ_ID_INVALID; + + if (pListener) + { + _AppControlManager::_RequestGuard reqObj = _AppControlManager::_RequestGuard(*pImpl, pArg, AppControlCbLegacy, pListener, _property); + req = reqObj.GetRequestNumber(); + + _processId = pImpl->Launch(_path, pArg, req); + SysTryCatch(NID_APP, r == E_SUCCESS, reqObj.Invalidate(), r, "[%s] Propagating." , GetErrorMessage(r)); + } + else + { + _processId = pImpl->Launch(_path, pArg); + delete pArg; + } + + { + // registers to server + _IAppManager* pMgr = _AppManagerProxy::GetService(); + + // actually register, not launch + if (pMgr) + { + const int MAX_PACKAGE_ID = 10; + + String appId; + String execName; + r = _path.SubString(0, MAX_PACKAGE_ID, appId); + if (r == E_SUCCESS) + { + r = _path.SubString(MAX_PACKAGE_ID + 1, execName); + if (r == E_SUCCESS) + { + pMgr->LaunchApplication(appId, execName, req); + } + } + } + } + +CATCH: + + return r; +} + +result +_AppControlImpl::StartOsp(const String* pUriData, const String* pMimeType, const IMap* pDataList, IAppControlResponseListener* pListener) +{ + result r = E_SUCCESS; + + _AppArg* pArg = new (std::nothrow) _AppArg; + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "Argument allocation failure."); + + pArg->Construct(*this, pUriData, pMimeType, pDataList); + + _AppControlManager* pImpl = _AppControlManager::GetInstance(); + int req = _REQ_ID_INVALID; + + if (pListener) + { + _AppControlManager::_RequestGuard reqObj = _AppControlManager::_RequestGuard(*pImpl, pArg, AppControlCb, pListener, _property); + req = reqObj.GetRequestNumber(); + + _processId = pImpl->Launch(_path, pArg, req); + SysTryCatch(NID_APP, r == E_SUCCESS, reqObj.Invalidate(), r, "[%s] Propagating." , GetErrorMessage(r)); + } + else + { + _processId = pImpl->Launch(_path, pArg); + delete pArg; + } + + { + // registers to server + _IAppManager* pMgr = _AppManagerProxy::GetService(); + + // actually register, not launch + if (pMgr) + { + const int MAX_PACKAGE_ID = 10; + + String appId; + String execName; + r = _path.SubString(0, MAX_PACKAGE_ID, appId); + if (r == E_SUCCESS) + { + r = _path.SubString(MAX_PACKAGE_ID + 1, execName); + if (r == E_SUCCESS) + { + pMgr->LaunchApplication(appId, execName, req); + } + } + } + } + +CATCH: + + return r; +} + +result +_AppControlImpl::StartImplicit(bundle* pBundle, const IList* pDataList, IAppControlEventListener* pListener) +{ + result r = E_SUCCESS; + + _AppArg* pArg = new (std::nothrow) _AppArg; + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "Argument allocation failure."); + + pArg->Construct(pBundle); + + _AppMessageImpl::AddData(pArg->GetBundle(), pDataList); + + _AppControlManager* pImpl = _AppControlManager::GetInstance(); + int req = _REQ_ID_INVALID; + + if (pListener) + { + _AppControlManager::_RequestGuard reqObj = _AppControlManager::_RequestGuard(*pImpl, pArg, AppControlCbLegacy, pListener, _APPCONTROL_PROPERTY_NONE); + req = reqObj.GetRequestNumber(); + + r = pImpl->LaunchAppImplicit(pArg, req); + SysTryCatch(NID_APP, r == E_SUCCESS, reqObj.Invalidate(), r, "[%s] Propagating." , GetErrorMessage(r)); + } + else + { + r = pImpl->LaunchAppImplicit(pArg, -1); + delete pArg; + } + + // [FIXME] launch registration is not working correctly + +CATCH: + + return r; +} + +result +_AppControlImpl::StartImplicit(bundle* pBundle, const IMap* pData, IAppControlResponseListener* pListener) +{ + result r = E_SUCCESS; + + _AppArg* pArg = new (std::nothrow) _AppArg; + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "Argument allocation failure."); + + pArg->Construct(pBundle); + + _AppArg::AddStrMap(pArg->GetBundle(), pData); + + _AppControlManager* pImpl = _AppControlManager::GetInstance(); + int req = _REQ_ID_INVALID; + + if (pListener) + { + _AppControlManager::_RequestGuard reqObj = _AppControlManager::_RequestGuard(*pImpl, pArg, AppControlCb, pListener, _APPCONTROL_PROPERTY_NONE); + req = reqObj.GetRequestNumber(); + + r = pImpl->LaunchAppImplicit(pArg, req); + SysTryCatch(NID_APP, r == E_SUCCESS, reqObj.Invalidate(), r, "[%s] Propagating." , GetErrorMessage(r)); + } + else + { + r = pImpl->LaunchAppImplicit(pArg, -1); + delete pArg; + } + + // [FIXME] launch registration is not working correctly + +CATCH: + + return r; +} + +result +_AppControlImpl::AppControlCbLegacy(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop) +{ + SysLog(NID_APP, "Result value %d", res); + + SysTryReturnResult(NID_APP, data && pResArg && pArg, E_SYSTEM, "Invalid result (callback, result, arg) = (0x%x, 0x%x, 0x%x).", + data, pResArg, + pArg); + + bundle* b = pResArg->GetBundle(); + SysTryReturnResult(NID_APP, b != NULL, E_SYSTEM, "Invalid result bundle."); + + IAppControlEventListener* pListener = static_cast(data); + SysTryReturnResult(NID_APP, typeid(pListener) == typeid(IAppControlEventListener*), E_SYSTEM, "Invalid result callback"); + + bundle* inb = pArg->GetBundle(); + SysTryReturnResult(NID_APP, inb != NULL, E_SYSTEM, "Empty caller bundle."); + + String oId; + + AppId provider = pResArg->GetCalleeAppId(); + + const char* p = appsvc_get_operation(inb); + if (p) + { + oId = p; + } + + SysLog(NID_APP, "Invoking callback with (%ls, %ls)", provider.GetPointer(), oId.GetPointer()); + + if (prop & _APPCONTROL_PROPERTY_ALIAS) + { + _AppControlRegistry::_AppControlAliasEntry* pEntry = null; + pEntry = _AppControlRegistry::GetInstance()->GetReverseAppControlAliasEntry(provider, oId); + if (pEntry) + { + provider = pEntry->provider; + oId = pEntry->operation; + + SysLog(NID_APP, "Legacy AppControl name (%ls, %ls).", provider.GetPointer(), oId.GetPointer()); + } + } + + if (prop & _APPCONTROL_PROPERTY_APPID_CHANGE) + { + String tmp = _AppControlRegistry::GetInstance()->GetReverseAliasAppId(provider); + if (!tmp.IsEmpty()) + { + SysLog(NID_APP, "AppId change (%ls -> %ls).", provider.GetPointer(), tmp.GetPointer()); + + provider = tmp; + } + } + + std::unique_ptr pMap(pResArg->GetArgMapN()); + + ArrayList list(SingleObjectDeleter); + _AppArg::FillLegacyAppControlResult(list, res, pMap.get(), provider); + + // proper callback invokation + pListener->OnAppControlCompleted(provider, oId, &list); + + return E_SUCCESS; +} + +result +_AppControlImpl::AppControlCb(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop) +{ + SysLog(NID_APP, "Result value %d", res); + + SysTryReturnResult(NID_APP, data && pResArg && pArg, E_SYSTEM, "Invalid result (callback, result, arg) = (0x%x, 0x%x, 0x%x).", + data, pResArg, + pArg); + + bundle* b = pResArg->GetBundle(); + SysTryReturnResult(NID_APP, b != NULL, E_SYSTEM, "Invalid result bundle."); + + IAppControlResponseListener* pListener = static_cast(data); + SysTryReturnResult(NID_APP, typeid(pListener) == typeid(IAppControlResponseListener*), E_SYSTEM, "Invalid result callback"); + + bundle* inb = pArg->GetBundle(); + SysTryReturnResult(NID_APP, inb != NULL, E_SYSTEM, "Empty caller bundle."); + + String oId; + + AppId provider = pResArg->GetCalleeAppId(); + + const char* p = appsvc_get_operation(inb); + if (p) + { + oId = p; + } + + SysLog(NID_APP, "Invoking callback with (%ls, %ls)", provider.GetPointer(), oId.GetPointer()); + + if (prop & _APPCONTROL_PROPERTY_ALIAS) + { + _AppControlRegistry::_AppControlAliasEntry* pEntry = null; + pEntry = _AppControlRegistry::GetInstance()->GetReverseAppControlAliasEntry(provider, oId); + if (pEntry) + { + provider = pEntry->provider; + oId = pEntry->operation; + + SysLog(NID_APP, "Legacy AppControl name (%ls, %ls).", provider.GetPointer(), oId.GetPointer()); + } + } + + if (prop & _APPCONTROL_PROPERTY_APPID_CHANGE) + { + String tmp = _AppControlRegistry::GetInstance()->GetReverseAliasAppId(provider); + if (!tmp.IsEmpty()) + { + SysLog(NID_APP, "AppId change (%ls -> %ls).", provider.GetPointer(), tmp.GetPointer()); + + provider = tmp; + } + } + + std::unique_ptr pMap(pResArg->GetArgMapN()); + + AppCtrlResult ret = APP_CTRL_RESULT_FAILED; + // to prevent enum overflow; + int resCode = res; + switch(resCode) + { + case SERVICE_RESULT_SUCCEEDED: + ret = APP_CTRL_RESULT_SUCCEEDED; + break; + case SERVICE_RESULT_FAILED: + ret = APP_CTRL_RESULT_CANCELED; + break; + case SERVICE_RESULT_CANCELED: + ret = APP_CTRL_RESULT_ABORTED; + break; + case APPSVC_OSP_RES_FAIL: + ret = APP_CTRL_RESULT_FAILED; + break; + case APPSVC_OSP_RES_TERMINATE: + ret = APP_CTRL_RESULT_TERMINATED; + break; + default: + ret = APP_CTRL_RESULT_FAILED; + break; + } + + SysLog(NID_APP, "Result code : 0x%x.", ret); + + // proper callback invokation + pListener->OnAppControlCompleteResponseReceived(provider, oId, ret, pMap.get()); + + return E_SUCCESS; +} + +result +_AppControlImpl::StartNative(const IList* pDataList, IAppControlEventListener* pListener) +{ + _InProcessInfo* pInfo = _AppControlManager::GetInstance()->__inAppManager.FindItem(_reqId); + SysTryReturnResult(NID_APP, pInfo == null, E_IN_PROGRESS, "Request ID %d is already in progress.", _reqId); + + int req = _REQ_ID_INVALID; + _LibraryImpl* pLib = null; + + pLib = new (std::nothrow) _LibraryImpl; + SysTryReturnResult(NID_APP, pLib != null, E_OUT_OF_MEMORY, "Failed to allocate libraryimpl."); + + result r = pLib->Construct(_path); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + if (pListener) + { + _InProcessInfo* pItem = new (std::nothrow) _InProcessInfo(_provider, _opId, _property, true, *pLib, pListener); + if (pItem) + { + req = _AppControlManager::GetInstance()->__inAppManager.InsertItem(pItem); + } + } + r = InvokeStartAppControl(*pLib, req, _provider, _opId, pDataList); + + if (pListener == null) + { + delete pLib; + } + + // after acquring request number, pLib should be managed from the list, not CATCH + if (IsFailed(r)) + { + SetLastResult(E_SYSTEM); + _AppControlManager::GetInstance()->__inAppManager.RemoveItem(req); + SysLog(NID_APP, "[E_SYSTEM] A system error has occurred with %s.", GetErrorMessage(r)); + + return E_SYSTEM; + } + + _reqId = req; + + return E_SUCCESS; + +CATCH: + delete pLib; + + switch (r) + { + case E_LIBRARY_NOT_FOUND: + r = E_OBJ_NOT_FOUND; + break; + default: + r = E_SYSTEM; + break; + } + + return r; +} + +result +_AppControlImpl::StartNative(const String* pUriData, const String* pMimeType, const IMap* pDataList, IAppControlResponseListener* pListener) +{ + _InProcessInfo* pInfo = _AppControlManager::GetInstance()->__inAppManager.FindItem(_reqId); + SysTryReturnResult(NID_APP, pInfo == null, E_IN_PROGRESS, "Request ID %d is already in progress.", _reqId); + + int req = _REQ_ID_INVALID; + _LibraryImpl* pLib = null; + + pLib = new (std::nothrow) _LibraryImpl; + SysTryReturnResult(NID_APP, pLib != null, E_OUT_OF_MEMORY, "Failed to allocate libraryimpl."); + + result r = pLib->Construct(_path); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + if (pListener) + { + _InProcessInfo* pItem = new (std::nothrow) _InProcessInfo(_provider, _opId, _property, false, *pLib, pListener); + if (pItem) + { + req = _AppControlManager::GetInstance()->__inAppManager.InsertItem(pItem); + } + } + r = InvokeStartAppControl(*pLib, req, _provider, _opId, null, null, pDataList); + + if (pListener == null) + { + delete pLib; + } + + // after acquring request number, pLib should be managed from the list, not CATCH + if (IsFailed(r)) + { + SetLastResult(E_SYSTEM); + _AppControlManager::GetInstance()->__inAppManager.RemoveItem(req); + SysLog(NID_APP, "[E_SYSTEM] A system error has occurred with %s.", GetErrorMessage(r)); + + return E_SYSTEM; + } + + _reqId = req; + + return E_SUCCESS; + +CATCH: + delete pLib; + + switch (r) + { + case E_LIBRARY_NOT_FOUND: + r = E_OBJ_NOT_FOUND; + break; + default: + r = E_SYSTEM; + break; + } + + return r; +} + +result +_AppControlImpl::InvokeStartAppControl(_LibraryImpl& lib, int req, const String& appId, const String& oId, const IList* pList) +{ + SysLog(NID_APP, "Legacy stuff for converting argument"); + + HashMap map(SingleObjectDeleter); + HashMap* pMap = null; + if (pList) + { + map.Construct(); + + _AppArg::FillMapFromList(&map, pList); + + pMap = ↦ + } + + return InvokeStartAppControl(lib, req, appId, oId, null, null, pMap); +} + + +result +_AppControlImpl::InvokeStartAppControl(_LibraryImpl& lib, int req, const String& appId, const String& oId, const String* pUri, const String* pMime, const IMap* pMap) +{ + result (*pFunc)(int req, const String&, const String&, const String*, const String*, const IMap*) = null; + + pFunc = + reinterpret_cast(lib.GetProcAddress(L"StartAppControl")); + SysTryReturnResult(NID_APP, pFunc != null, E_OBJ_NOT_FOUND, "Entry \"StartAppControl\" not found for %ls", appId.GetPointer()); + return (*pFunc)(req, appId, oId, pUri, pMime, pMap); +} + +static bool +IsValidAppControl(const String& appcontrolID) +{ + return ((appcontrolID == L"osp.appcontrol.provider.audio") + || (appcontrolID == L"osp.appcontrol.provider.bluetooth") + || (appcontrolID == L"osp.appcontrol.provider.calendar") + || (appcontrolID == L"osp.appcontrol.provider.camera") + || (appcontrolID == L"osp.appcontrol.provider.contact") + || (appcontrolID == L"osp.appcontrol.provider.certificatemanager") + || (appcontrolID == L"osp.appcontrol.provider.email") + || (appcontrolID == L"osp.appcontrol.provider.image") + || (appcontrolID == L"osp.appcontrol.provider.media") + || (appcontrolID == L"osp.appcontrol.provider.message") + || (appcontrolID == L"osp.appcontrol.provider.video") + || (appcontrolID == L"osp.appcontrol.provider.imageeditor") + || (appcontrolID == L"osp.appcontrol.provider.allshare") + || (appcontrolID == L"tizen.filemanager") + || (appcontrolID == L"tizen.camera") + || (appcontrolID == L"tizen.gallery") + || (appcontrolID == L"tizen.imageviewer") + || (appcontrolID == L"tizen.videoplayer") + || (appcontrolID == L"tizen.memo") + || (appcontrolID == L"tizen.contacts") + || (appcontrolID == L"tizen.calendar") + || (appcontrolID == L"tizen.events") + || (appcontrolID == L"tizen.email") + || (appcontrolID == L"tizen.settings") + || (appcontrolID == L"tizen.messages") + || (appcontrolID == L"tizen.musicplayer") + || (appcontrolID == L"tizen.bluetooth") + || (appcontrolID == L"samsung.snote") + || (appcontrolID == L"0pnxz8hbsr.MyFiles") + || (appcontrolID == L"hdufar9ycj.Camera") + || (appcontrolID == L"ijudt7w61q.Gallery") + || (appcontrolID == L"jysyv9o1dc.ImageViewer") + || (appcontrolID == L"npwf0scb88.VideoPlayer") + || (appcontrolID == L"zunqjlsnce.Memo") + || (appcontrolID == L"f9uev8hsyo.Contacts") + || (appcontrolID == L"ph1vq2phrp.Calendar") + || (appcontrolID == L"vxqbrefica.Email") + || (appcontrolID == L"kto5jikgul.Settings") + || (appcontrolID == L"8r4r5ddzzn.Messages") + || (appcontrolID == L"dhrul6qzj3.MusicPlayer") + || (appcontrolID == L"smemo-efl")); +} + +result +_AppControlImpl::Stop(void) +{ + const String appcontrolID(GetAppControlProviderId()); + SysTryReturnResult(NID_APP, IsValidAppControl(appcontrolID), E_INVALID_OPERATION, "Invalid appcontrolID(%ls)", appcontrolID.GetPointer()); + + if (_property & _APPCONTROL_PROPERTY_SLP) + { + SysTryReturnResult(NID_APP, _reqId != _REQ_ID_INVALID, E_INVALID_OPERATION, "Invalid request ID ."); + + _InProcessInfo* pInfo = _AppControlManager::GetInstance()->__inAppManager.FindItem(_reqId); + SysTryReturnResult(NID_APP, pInfo != null, E_INVALID_OPERATION, "Request ID %d is not found.", _reqId); + + result (*pStop)(int req) = null; + pStop = reinterpret_cast(pInfo->pLib->GetProcAddress(L"TerminateAppControl")); + SysTryReturnResult(NID_APP, pStop != null, E_SYSTEM, "No TerminateAppControl() function."); + + (*pStop)(_reqId); + + _AppControlManager::GetInstance()->__inAppManager.RemoveItem(_reqId); + + _reqId = _REQ_ID_INVALID; + } + else if (_property & _APPCONTROL_PROPERTY_OSP) + { + _Aul::TerminateApplicationByPid(_processId); + } + + return E_SUCCESS; +} + +String +_AppControlImpl::GetAppName(void) +{ + if ((_property & _APPCONTROL_PROPERTY_OSP) && _appName.IsEmpty()) + { + const AppId& appId = _path; + + std::unique_ptr pInfo(_PackageManagerImpl::GetInstance()->GetPackageAppInfoN(appId)); + + if (pInfo.get()) + { + const String& name = pInfo->GetAppName(); + if (name == L"_AppControl") + { + // workaround for special case: requery with actual appId + const PackageId& packageId = _PackageManagerImpl::GetPackageIdByAppId(appId); + const String& defaultName = _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(packageId); + + const String& convertedAppId = packageId + L'.' + defaultName; + + std::unique_ptr pNewInfo(_PackageManagerImpl::GetInstance()->GetPackageAppInfoN(convertedAppId)); + + if (pNewInfo.get()) + { + _appName = pNewInfo->GetAppName(); + } + else + { + SysLog(NID_APP, "No default applicaiton information, possible database error."); + } + } + else + { + _appName = pInfo->GetAppName(); + } + SysLog(NID_APP, "Initializing AppName(%ls) for %ls.", _appName.GetPointer(), appId.GetPointer()); + } + } + + return _appName; +} + +String +_AppControlImpl::GetAppId(void) const +{ + return (_property & _APPCONTROL_PROPERTY_OSP) ? _path : _provider; +} + +const String& +_AppControlImpl::GetAppControlProviderId(void) const +{ + return _provider; +} + +const String& +_AppControlImpl::GetOperationId(void) const +{ + return _opId; +} + +IList* +_AppControlImpl::GetCategoryListN(void) const +{ + const AppId& appId = GetAppId(); + SysTryReturn(NID_APP, !appId.IsEmpty(), null, E_SYSTEM, "[E_SYSTEM] Empty appId."); + + SysLog(NID_APP, "Acquiring category for appId %ls.", appId.GetPointer()); + + std::unique_ptr pAppInfo(_PackageManagerImpl::GetInstance()->GetPackageAppInfoN(appId)); + SysTryReturn(NID_APP, pAppInfo.get() != null, null, E_SYSTEM, "[E_SYSTEM] Getting PackageAppInfo failed."); + + return pAppInfo->GetAppCategoryListN(); +} + +void +_AppControlImpl::StopAppControlResponseListener(IAppControlResponseListener* pListener) +{ +} + +}} //Tizen::App diff --git a/src/app/FApp_AppControlManager.cpp b/src/app/FApp_AppControlManager.cpp new file mode 100755 index 0000000..a109998 --- /dev/null +++ b/src/app/FApp_AppControlManager.cpp @@ -0,0 +1,677 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlManager.cpp + * @brief This is the implementation for the _AppControlManager class. + */ + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "FApp_AppArg.h" +#include "FApp_AppControlEventArg.h" +#include "FApp_AppControlRegistry.h" +#include "FApp_AppControlImpl.h" +#include "FApp_AppImpl.h" +#include "FApp_AppInfo.h" +#include "FApp_AppManagerEventArg.h" +#include "FApp_Aul.h" +#include "FApp_AppControlManager.h" +#include "FApp_AppManagerProxy.h" +#include "FApp_ConditionManagerProxy.h" +#include "FApp_IAppManagerEventListener.h" +#include "FApp_MapDataControlImpl.h" +#include "FApp_SqlDataControlImpl.h" +#include "FAppPkg_PackageManagerImpl.h" +#include "FAppPkg_PackageInfoImpl.h" +#include "FApp_AppMessageImpl.h" +#include "FApp_AppManagerImpl.h" + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Utility; +using namespace Tizen::Io; + +//extern const char* _DATACONTROL_RESULTSET_DIR; + +namespace Tizen { namespace App +{ + +const wchar_t TIZEN_OPERATION_PICK[] = L"http://tizen.org/appcontrol/operation/pick"; +const wchar_t SELECTOR_NOTI_KEY[] = L"__APP_SVC_CALLER_NOTI__"; +const int _MAX_PACKAGE_ID_LENGTH = 10; + +_InProcessInfo::~_InProcessInfo(void) +{ + delete pLib; +} + +_LaunchInfo::~_LaunchInfo(void) +{ + delete pArg; +} + + +_AppControlManager::_AppControlManager(void) +{ + SysLog(NID_APP, ""); + + // AppControl event handling is expected to be performed in the main thread. + __appControlEvent.Construct(); + __appControlEvent.AddListener(*dynamic_cast<_IAppControlSysEventListener*>(this)); +} + +_AppControlManager::~_AppControlManager(void) +{ + SysLog(NID_APP, ""); + __appControlEvent.RemoveListener(*dynamic_cast<_IAppControlSysEventListener*>(this)); +} + +_AppControlManager* +_AppControlManager::GetInstance(void) +{ + static _AppControlManager inst; + + return &inst; +} + +result +_AppControlManager::GetMimeFromExt(const String& ext, String& out) +{ + std::unique_ptr pExtension(_StringConverter::CopyToCharArrayN(ext)); + SysTryReturnResult(NID_APP, pExtension != null, E_OUT_OF_MEMORY, "String allocation failure."); + + char* mime = NULL; + mime_type_get_mime_type(pExtension.get(), &mime); + + SysTryReturnResult(NID_APP, mime != NULL, E_UNSUPPORTED_FORMAT, "MIME type conversion failure for %ls.", ext.GetPointer()); + + out = mime; + free(mime); + + return E_SUCCESS; +} + +void +_AppControlManager::OnAppControlEventReceivedN(int reqId, _AppArg* pAppArg, int res) +{ + SysLog(NID_APP, "Received request Id %d, arg 0x%x", reqId, pAppArg); + + //_AppArg::Print(b); + // get launch info from request Id + _LaunchInfo* pInfo = __launchManager.FindItem(reqId); + SysTryReturnVoidResult(NID_APP, pInfo != null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] request Id %d not found with response %d", reqId, + res); + + // invoke callback + if (pInfo->launchCb) + { + if (pInfo->magic == LAUNCH_INFO_MAGIC) + { + SysLog(NID_APP, "Invoking callback 0x%x", pInfo->launchCb); + + (*pInfo->launchCb)(pInfo->pUserData, pInfo->pArg, pAppArg, static_cast(res), pInfo->property); + } + else + { + SysLogException(NID_APP, E_SYSTEM, "Corrupted data structure."); + } + } + + // clean up argument + __launchManager.RemoveItem(reqId); +} + + +// callback for out-of-process AppControl start event +void +_AppControlManager::OnAppControlEventReceivedN(int reqId, const AppId& appId, const String& operationId) +{ + SysLog(NID_APP, "Received request Id %d, appId %ls, operationId %ls", reqId, appId.GetPointer(), operationId.GetPointer()); + + // get launch info from request Id + _LaunchInfo* pInfo = __launchManager.FindItem(reqId); + SysTryReturnVoidResult(NID_APP, pInfo != null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] request Id %d not found.", reqId); + + // at least listener + IAppControlResponseListener* pListener = static_cast(pInfo->pUserData); + SysTryReturnVoidResult(NID_APP, typeid(pListener) == typeid(IAppControlResponseListener*), E_SYSTEM, "[E_SYSTEM] Invalid result callback."); + + if (pListener) + { + result r = E_SUCCESS; + AppId actualAppId = appId; + if (appId == L'c') + { + actualAppId.Clear(); + r = E_OPERATION_CANCELED; + } + SysLog(NID_APP, "Invoking callback 0x%x.", pListener); + pListener->OnAppControlStartResponseReceived(actualAppId, operationId, r); + } + else + { + SysLog(NID_APP, "No listener registered."); + } +} + + +// callback for in-process event handling +void +_AppControlManager::OnAppControlEventReceivedN(int reqId, int res, const IMap* pArgs) +{ + SysLog(NID_APP, "Received request Id %d, args 0x%x", reqId, pArgs); + + // process proper callback + _InProcessInfo* pInfo = __inAppManager.FindItem(reqId); + SysTryReturnVoidResult(NID_APP, pInfo != null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] request Id %d not found with args 0x%x", reqId, + pArgs); + + if (pInfo->pListener) + { + String aId = pInfo->providerId; + String oId = pInfo->operationId; + + SysLog(NID_APP, "Invoking callback 0x%x for (%ls, %ls).", pInfo->pListener, aId.GetPointer(), oId.GetPointer()); + + if (pInfo->property & _APPCONTROL_PROPERTY_ALIAS) + { + _AppControlRegistry::_AppControlAliasEntry* pEntry = null; + pEntry = _AppControlRegistry::GetInstance()->GetReverseAppControlAliasEntry(aId, oId); + if (pEntry) + { + aId = pEntry->provider; + oId = pEntry->operation; + + SysLog(NID_APP, "Legacy AppControl name (%ls, %ls).", aId.GetPointer(), oId.GetPointer()); + } + } + + if (pInfo->isLegacy) + { + IAppControlEventListener* pListener = dynamic_cast(pInfo->pListener); + if (pListener) + { + ArrayList list(SingleObjectDeleter); + _AppArg::FillLegacyAppControlResult(list, res, pArgs, aId); + + pListener->OnAppControlCompleted(aId, oId, &list); + } + else + { + SysLog(NID_APP, "Wrong AppControl listener type."); + } + } + else + { + IAppControlResponseListener* pListener = dynamic_cast(pInfo->pListener); + if (pListener) + { + pListener->OnAppControlCompleteResponseReceived(aId, oId, static_cast(res), pArgs); + } + else + { + SysLog(NID_APP, "Wrong AppControl listener type."); + } + } + } + else + { + SysLogException(NID_APP, E_SYSTEM, "Invalid AppControl listener."); + } + + // call TerminateAppControl + result (* pFunc)(int req) = null; + pFunc = reinterpret_cast(pInfo->pLib->GetProcAddress(L"TerminateAppControl")); + if (pFunc) + { + (*pFunc)(pInfo->reqId); + } + else + { + SysLogException(NID_APP, E_SYSTEM, "No TerminateAppControl() function."); + } + + // remove from list and unload dll + __inAppManager.RemoveItem(reqId); +} + + +result +_AppControlManager::SendAppControlEvent(IEventArg& arg) +{ + return __appControlEvent.FireAsync(arg); +} + +// generic launch callback +static void +LaunchResultCb(bundle* b, int request_code, appsvc_result_val res, void* data) +{ + SysLog(NID_APP, "SLP callee result: %d", res); + + _AppControlManager* pImpl = static_cast<_AppControlManager*>(data); + if (pImpl == null) + { + return; + } + + _AppArg* pAppArg = new (std::nothrow) _AppArg; + SysTryReturnVoidResult(NID_APP, pAppArg != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] AppControl event argument creation failure."); + + _AppControlEventArg* pArg = null; + result r = pAppArg->Construct(b); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] AppControl event argument creation failure.", GetErrorMessage(r)); + + pArg = new (std::nothrow) _AppControlEventArg(request_code, pAppArg, res); + SysTryCatch(NID_APP, pArg != null, r = E_OUT_OF_MEMORY, r, "[E_OUT_OF_MEMORY] AppControl event argument creation failure."); + + //_AppArg::Print(b); + pImpl->SendAppControlEvent(*pArg); + + return; + +CATCH: + delete pAppArg; +} + + +result +_AppControlManager::SendAppControlStartResponse(int req, const char* pValue, const char* pOp) +{ + _AppControlStartEventArg* pArg = new (std::nothrow) _AppControlStartEventArg(req, AppId(pValue), String(pOp)); + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "AppControl start event creation failure."); + + SendAppControlEvent(*pArg); + + return E_SUCCESS; +} + + +result +_AppControlManager::LaunchPkg(_AppMessageImpl& msg, const char* pkg_name, const char* op, const char* mime, const char* uri, AppSvcResFn pCb, void* data) +{ + bundle* kb = msg.GetBundle(); + SysTryReturnResult(NID_APP, kb != NULL, E_OUT_OF_MEMORY, "Bundle allocation failure."); + + if (pkg_name) + { + appsvc_set_pkgname(kb, pkg_name); + } + + appsvc_set_operation(kb, (op) ? op : APPSVC_OPERATION_DEFAULT); + + if (mime) + { + appsvc_set_mime(kb, mime); + } + + if (uri) + { + appsvc_set_uri(kb, uri); + } + + const long handle = _AppImpl::GetInstance()->GetWindowHandle(); + _AppArg::UpdateWindowHandle(kb, handle); + + SysLog(NID_APP, "MIME(%s), URI(%s).", appsvc_get_mime(kb), appsvc_get_uri(kb)); + int pid = appsvc_run_service(kb, 0, reinterpret_cast(pCb), this); + + SysTryReturnResult(NID_APP, pid >= 0, E_SYSTEM, "Launching service %s failure with %d", pkg_name, pid); + + return E_SUCCESS; +} +int +_AppControlManager::Launch(_AppMessageImpl& msg, const char* pkg_name, const char* op, const char* mime, const char* uri, AppSvcResFn pCb, void* data) +{ + bundle* kb = msg.GetBundle(); + SysTryReturn(NID_APP, kb != NULL, -1, E_OUT_OF_MEMORY, "Bundle allocation failure."); + + if (pkg_name) + { + appsvc_set_pkgname(kb, pkg_name); + } + + appsvc_set_operation(kb, (op) ? op : APPSVC_OPERATION_DEFAULT); + + if (mime) + { + appsvc_set_mime(kb, mime); + } + + if (uri) + { + appsvc_set_uri(kb, uri); + } + + const long handle = _AppImpl::GetInstance()->GetWindowHandle(); + _AppArg::UpdateWindowHandle(kb, handle); + + SysLog(NID_APP, "MIME(%s), URI(%s).", appsvc_get_mime(kb), appsvc_get_uri(kb)); + int pid = appsvc_run_service(kb, 0, reinterpret_cast(pCb), this); + + SysTryReturn(NID_APP, pid >= 0, -1, E_SYSTEM, "Launching service %s failure with %d", pkg_name, pid); + + return pid; +} + + +result +_AppControlManager::LaunchPkg(const char* pkg_name, const char* op, const char* mime, const char* uri, AppSvcResFn pCb, void* data) +{ + _AppMessageImpl msg; + + return LaunchPkg(msg, pkg_name, op, mime, uri, pCb, data); +} + +result +_AppControlManager::LaunchAppWithCondition(const AppId& appId, const String& executableName, const String& condition, IList* pArrayArgs) +{ + result r = E_SUCCESS; + const String& actualAppId = appId + L'.' + executableName; + _AppArg * pArg = new (std::nothrow) _AppArg(); + SysTryCatch(NID_APP, pArg != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]"); + + r = pArg->ConstructForAppLaunchCondition(condition, pArrayArgs); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] ConstructForAppLaunchCondition(%ls, .. ) fails", GetErrorMessage(r), condition.GetPointer()); + + r = _AppControlManager::LaunchApp(actualAppId, pArg); + +CATCH: + delete pArg; + return r; +} + +result +_AppControlManager::LaunchApp(const AppId& appId, _AppArg* pArg, int req) +{ + SysTryReturnResult(NID_APP, pArg != null, E_INVALID_ARG, "Invalid launch argument"); + SysLog(NID_APP, "AppId: %ls.", appId.GetPointer()); + + String actualAppId = appId; + if (appId.GetLength() == 10) + { + const String& name = _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(appId); + + if (!name.IsEmpty()) + { + actualAppId.Append(L'.'); + actualAppId.Append(name); + } + } + + pArg->UpdateRequestId(req); + + const long handle = _AppImpl::GetInstance()->GetWindowHandle(); + pArg->UpdateWindowHandle(handle); + + int pid = -1; + bundle* kb = NULL; + String tempId; + actualAppId.SubString(0, 10, tempId); + tempId += L'.'; + tempId += L"_AppControl"; + + // [INFO] Ugly solution for submode support + pArg->UpdateAppId(tempId); + kb = pArg->GetBundle(); + + pid = appsvc_run_service(kb, req, LaunchResultCb, this); + if (pid > 0) + { + SysLog(NID_APP, "Submode launch successful"); + return E_SUCCESS; + } + + pArg->UpdateAppId(actualAppId); + + // retry for possible failure + int count = 0; + const int TRY_COUNT = 3; + const int TRY_SLEEP_TIME = 65; + do + { + kb = pArg->GetBundle(); + pid = appsvc_run_service(kb, req, LaunchResultCb, this); + if (pid > 0) + { + SysLog(NID_APP, "Application(%d) launched with reqId(%d) and arg(0x%x).", pid, req, pArg); + return E_SUCCESS; + } + count++; + SysLog(NID_APP, "Waiting %dth time.", count); + Thread::Sleep(TRY_SLEEP_TIME); + } + while (count < TRY_COUNT); + + SysLogException(NID_APP, E_SYSTEM, "[E_SYSTEM] Launching service failure for %ls with %d", appId.GetPointer(), pid); + + return E_SYSTEM; +} + +int +_AppControlManager::Launch(const AppId& appId, _AppArg* pArg, int req) +{ + SysTryReturn(NID_APP, pArg != null, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid launch argument"); + SysLog(NID_APP, "AppId: %ls.", appId.GetPointer()); + + String actualAppId = appId; + if (appId.GetLength() == 10) + { + const String& name = _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(appId); + + if (!name.IsEmpty()) + { + actualAppId.Append(L'.'); + actualAppId.Append(name); + } + } + + pArg->UpdateRequestId(req); + + const long handle = _AppImpl::GetInstance()->GetWindowHandle(); + pArg->UpdateWindowHandle(handle); + + int pid = -1; + bundle* kb = NULL; + String tempId; + actualAppId.SubString(0, 10, tempId); + tempId += L'.'; + tempId += L"_AppControl"; + + // [INFO] Ugly solution for submode support + pArg->UpdateAppId(tempId); + kb = pArg->GetBundle(); + + pid = appsvc_run_service(kb, req, LaunchResultCb, this); + if (pid > 0) + { + SysLog(NID_APP, "Submode launch successful"); + return pid; + } + + pArg->UpdateAppId(actualAppId); + + // retry for possible failure + int count = 0; + const int TRY_COUNT = 3; + const int TRY_SLEEP_TIME = 65; + do + { + kb = pArg->GetBundle(); + pid = appsvc_run_service(kb, req, LaunchResultCb, this); + if (pid > 0) + { + SysLog(NID_APP, "Application(%d) launched with reqId(%d) and arg(0x%x).", pid, req, pArg); + return pid; + } + count++; + SysLog(NID_APP, "Waiting %dth time.", count); + Thread::Sleep(TRY_SLEEP_TIME); + } + while (count < TRY_COUNT); + + SysLogException(NID_APP, E_SYSTEM, "[E_SYSTEM] Launching service failure for %ls with %d", appId.GetPointer(), pid); + + return pid; +} + +result +_AppControlManager::LaunchAppImplicit(_AppArg* pArg, int req) +{ + SysTryReturnResult(NID_APP, pArg != null, E_INVALID_ARG, "Invalid launch argument"); + + result r = E_SUCCESS; + bundle* kb = pArg->GetBundle(); + + if (req >= 0) + { + pArg->UpdateRequestId(req); + _AppMessageImpl::AddData(kb, SELECTOR_NOTI_KEY, _AppInfo::GetApplicationId()); + } + + int pid = appsvc_run_service(kb, req, LaunchResultCb, this); + switch (pid) + { + case APPSVC_RET_EINVAL: + r = E_OBJ_NOT_FOUND; + break; + case APPSVC_RET_ENOMATCH: + r = E_OBJ_NOT_FOUND; + break; + case APPSVC_RET_ERROR: + // fall through + case APPSVC_RET_ELAUNCH: + r = E_SYSTEM; + break; + default: + break; + } + + SysLog(NID_APP, "[%s] Application(%d) launched with reqId(%d) and arg(0x%x).", GetErrorMessage(r), pid, req, pArg); + + return r; +} + +void +_AppControlManager::FinishAppControl(int reqId, int res, const IMap* pMap) +{ + _NativeAppControlEventArg* pArg = new (std::nothrow) _NativeAppControlEventArg(reqId, res, pMap); + SysTryReturnVoidResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Return argument allocation failure."); + + SendAppControlEvent(*pArg); +} + +const _AppArg* +_AppControlManager::FindResultRequest(int reqId) const +{ + const _ResultInfo* pInfo = __resultManager.FindItem(reqId); + return (pInfo) ? &(pInfo->arg) : null; +} + +int +_AppControlManager::AddLaunchRequest(_AppArg* pArg, LaunchCbType pCb, void* pData, int prop) +{ + SysTryReturn(NID_APP, pArg != null, -1, E_INVALID_ARG, "[E_INVALID_ARG] Empty argument."); + + _LaunchInfo* pItem = new (std::nothrow) _LaunchInfo(pArg, pCb, pData, prop); + SysTryReturn(NID_APP, pItem != null, -1, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Empty argument."); + + SysLog(NID_APP, "Registering callback 0x%x, 0x%x", pCb, pData); + + return __launchManager.InsertItem(pItem); +} + +void +_AppControlManager::RemoveLaunchRequest(int req) +{ + __launchManager.RemoveItem(req); +} + +result +_AppControlManager::RegisterRequest(service_s* service, int& req, _AppHandler& handler) +{ + bundle* b = _AppArg::GetBundleFromSvc(service); + + _AppArg* pArg = new (std::nothrow) _AppArg(); + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "rrayList creation failure."); + pArg->Construct(b); + + result r = E_SUCCESS; + + // ownership is transfered to RequestManager + _ResultInfo* pItem = new (std::nothrow) _ResultInfo(*pArg); + SysTryCatch(NID_APP, pItem != null, , r = E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Empty argument."); + + req = __resultManager.InsertItem(pItem); + SysTryCatch(NID_APP, req != -1, , r = E_INVALID_STATE, "[E_INVALID_STATE] Invalid argument handling state."); + + handler = _AppArg::GetHandler(b); + + return E_SUCCESS; + +CATCH: + delete pArg; + + return r; +} + + +bool +_AppControlManager::IsAllowedAppControl(const wchar_t aTable[][2][64], int count, const String& aId, const String& oId) +{ + for (int i = 0; i < count; i++) + { + if (aId == aTable[i][0] && oId == aTable[i][1]) + { + SysLog(NID_APP, "Found entry (%ls, %ls)", aTable[i][0], aTable[i][1]); + return true; + } + } + + return false; +} + +}} // Tizen::App diff --git a/src/app/FApp_AppControlProviderManagerImpl.cpp b/src/app/FApp_AppControlProviderManagerImpl.cpp new file mode 100644 index 0000000..84a4fef --- /dev/null +++ b/src/app/FApp_AppControlProviderManagerImpl.cpp @@ -0,0 +1,167 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlProviderManagerImpl.cpp + * @brief This is the implementation for the %_AppControlProviderManagerImpl class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "FApp_Aul.h" +#include "FApp_AppArg.h" +#include "FApp_AppImpl.h" +#include "FApp_AppControlManager.h" +#include "FApp_AppControlProviderManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + + +namespace Tizen { namespace App +{ + +_AppControlProviderManagerImpl::_AppControlProviderManagerImpl(void) +{ +} + +_AppControlProviderManagerImpl::~_AppControlProviderManagerImpl(void) +{ +} + +result +_AppControlProviderManagerImpl::SetAppControlProviderEventListener(IAppControlProviderEventListener* pListener) +{ + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturn(NID_APP, pAppImpl, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting _AppImpl instance failed."); + + return pAppImpl->SetAppControlProviderEventListener(pListener); +} + +result +_AppControlProviderManagerImpl::SendAppControlResult(RequestId reqId, const IList* pResultList) +{ + SysTryReturnResult(NID_APP, reqId != -1, E_OBJ_NOT_FOUND, "The application request %d is not found.", reqId); + + _AppControlManager* pAppMgr = _AppControlManager::GetInstance(); + + _ResultInfo* pInfo = pAppMgr->__resultManager.FindItem(reqId); + SysTryReturnResult(NID_APP, pInfo != null, E_OBJ_NOT_FOUND, "The application request %d is not found.", reqId); + + const _AppArg& arg = pInfo->arg; + + _AppArg resArg; + result r = resArg.ConstructResult(arg, pResultList); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + //resArg.Print(); + r = _Aul::SendResult(resArg.GetBundle(), static_cast(0)); + SysLog(NID_APP, "Sent AppControl event for %d.", reqId); + + // erase _AppArg after sending the result back to the caller + pAppMgr->__resultManager.RemoveItem(reqId); + + return r; +} + +result +_AppControlProviderManagerImpl::SendAppControlResult(RequestId reqId, AppCtrlResult appControlResult, const IMap* pResultMap) +{ + SysTryReturnResult(NID_APP, reqId != -1, E_OBJ_NOT_FOUND, "The application request %d is not found.", reqId); + + _AppControlManager* pAppMgr = _AppControlManager::GetInstance(); + + _ResultInfo* pInfo = pAppMgr->__resultManager.FindItem(reqId); + SysTryReturnResult(NID_APP, pInfo != null, E_OBJ_NOT_FOUND, "The application request %d is not found.", reqId); + + const _AppArg& arg = pInfo->arg; + + _AppArg resArg; + result r = resArg.ConstructResult(arg, pResultMap); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + const int code = appControlResult; + int res = APPSVC_RES_NOT_OK; + switch (code) + { + case APP_CTRL_RESULT_SUCCEEDED: + res = APPSVC_RES_OK; + break; + case APP_CTRL_RESULT_FAILED: + res = APPSVC_OSP_RES_FAIL; + break; + case APP_CTRL_RESULT_CANCELED: + res = APPSVC_RES_NOT_OK; + break; + case APP_CTRL_RESULT_TERMINATED: + res = APPSVC_OSP_RES_TERMINATE; + break; + case APP_CTRL_RESULT_ABORTED: + res = APPSVC_RES_CANCEL; + break; + default: + res = APPSVC_RES_NOT_OK; + break; + } + + //resArg.Print(); + r = _Aul::SendResult(resArg.GetBundle(), static_cast(res)); + SysLog(NID_APP, "Sent AppControl event for %d.", reqId); + + // erase _AppArg after sending the result back to the caller + pAppMgr->__resultManager.RemoveItem(reqId); + + return r; +} + +AppId +_AppControlProviderManagerImpl::GetClientAppId(RequestId reqId) const +{ + SysTryReturn(NID_APP, reqId != -1, L"", E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The application control request %d is not found.", reqId); + + _ResultInfo* pInfo = _AppControlManager::GetInstance()->__resultManager.FindItem(reqId); + SysTryReturn(NID_APP, pInfo != null, L"", E_OBJ_NOT_FOUND, "[E_OB_NOT_FOUND] The application control request %d is not found.", reqId); + + const _AppArg& arg = pInfo->arg; + + return arg.GetCallerAppId(); +} + +const _AppControlProviderManagerImpl* +_AppControlProviderManagerImpl::GetInstance(const AppControlProviderManager& ac) +{ + return ac.__pAppControlProviderManagerImpl; +} + +_AppControlProviderManagerImpl* +_AppControlProviderManagerImpl::GetInstance(AppControlProviderManager& ac) +{ + return ac.__pAppControlProviderManagerImpl; +} + +} } // Tizen::App + diff --git a/src/app/FApp_AppControlProviderManagerImpl.h b/src/app/FApp_AppControlProviderManagerImpl.h new file mode 100644 index 0000000..c14c87a --- /dev/null +++ b/src/app/FApp_AppControlProviderManagerImpl.h @@ -0,0 +1,104 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlProviderManagerImpl.h + * @brief This is the header file for the %_AppControlProviderManagerImpl class. + * + * This header file contains the declarations of the %_AppControlProviderManagerImpl class. + */ + +#ifndef _FAPP_INTERNAL_APPCONTROL_PROVIDER_MANAGER_IMPL_H_ +#define _FAPP_INTERNAL_APPCONTROL_PROVIDER_MANAGER_IMPL_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +}} + +namespace Tizen { namespace Base { namespace Collection { class IList; } } } + +namespace Tizen { namespace App +{ + +class AppControlProviderManager; +class IAppControlProviderEventListener; + +/** + * @class _AppControlProviderManagerImpl + * @brief This class manages all the application controls. + * @since 2.1 + * + * The %_AppControlProviderManagerImpl class manages all the application controls. + */ +class _AppControlProviderManagerImpl + : public Tizen::Base::Object +{ + +public: + result SetAppControlProviderEventListener(IAppControlProviderEventListener* pListener); + + result SendAppControlResult(RequestId reqId, const Tizen::Base::Collection::IList* pResultList); + + result SendAppControlResult(RequestId reqId, AppCtrlResult appControlResult, const Tizen::Base::Collection::IMap* pResultMap); + + AppId GetClientAppId(RequestId reqId) const; + + /** + * Internal GetImpl() method. + */ + static const _AppControlProviderManagerImpl* GetInstance(const AppControlProviderManager& ac); + + /** + * Internal GetImpl() method. + */ + static _AppControlProviderManagerImpl* GetInstance(AppControlProviderManager& ac); + +private: + /** + * This is the default constructor for this class. + */ + _AppControlProviderManagerImpl(void); + + /** + * This is the destructor for this class. + */ + virtual ~_AppControlProviderManagerImpl(void); + + /** + * This is the default copy constructor for this class. + */ + _AppControlProviderManagerImpl(const _AppControlProviderManagerImpl& rhs); + + /** + * This is the assignment operator for this class. + */ + _AppControlProviderManagerImpl& operator =(const _AppControlProviderManagerImpl& rhs); + + friend class AppControlProviderManager; +}; + +}} // Tizen::App + +#endif // _FAPP_INTERNAL_APPCONTROL_PROVIDER_MANAGER_IMPL_H_ + diff --git a/src/app/FApp_AppControlRegistry.cpp b/src/app/FApp_AppControlRegistry.cpp new file mode 100644 index 0000000..34725d1 --- /dev/null +++ b/src/app/FApp_AppControlRegistry.cpp @@ -0,0 +1,694 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlRegistry.cpp + * @brief This is the implementation for the _AppControlRegistry.cpp class. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "FAppPkg_PackageManagerImpl.h" +#include "FApp_AppControlImpl.h" +#include "FApp_Aul.h" +#include "FApp_AppControlRegistry.h" +#include "FApp_AppMessageImpl.h" +#include "FApp_TemplateUtil.h" +#ifdef _SINGLETON_CLEANUP +#include "FApp_LongevityManager.h" +#endif + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +namespace +{ + +const wchar_t ACTL_PRIVATE_FILE[] = L"/usr/etc/app-control-system.ini"; +const wchar_t ACTL_DEFAULT_FILE[] = L"/usr/etc/app-control-info.ini"; +const wchar_t ACTL_LEGACY_FILE[] = L"/usr/etc/app-control-alias.ini"; +const wchar_t ACTL_ALIAS_FILE[] = L"/usr/etc/app-control-appid.ini"; +const wchar_t ACTL_PRIVATE_ALIAS_FILE[] = L"/usr/etc/app-control-private-appid.ini"; + +const wchar_t TIZEN_ALIAS_APPID_PREFIX[] = L"tizen."; + +const String ACTL_REGISTRY_OP_NUM = L"OPID_Count"; +const String ACTL_REGISTRY_PUBLIC = L"Public"; +const String ACTL_REGISTRY_LAUNCH_TYPE = L"LaunchType"; +const String ACTL_REGISTRY_PATH = L"Path"; +const String ACTL_REGISTRY_CATEGORY = L"Category"; +const String ACTL_REGISTRY_TITLE = L"Title"; +const String ACTL_REGISTRY_ALIAS_PROVIDER = L"PROVIDER_ALIAS"; + +const int PKG_CATEGORY_LEN = 256; +const int PKG_APPID_LEN = 256; +const int REG_VALUE_BUFFER_LEN = 256; + +} + + +namespace Tizen { namespace App +{ + +_AppControlRegistry* _AppControlRegistry::__pSelf = null; + +_AppControlRegistry::_AppControlRegistry(void) +{ + __nativeList.Construct(); + + __aliasList.Construct(); + + __aliasOperation.Construct(); + + __aliasAppId.Construct(); +} + +_AppControlRegistry::~_AppControlRegistry(void) +{ + _DeleteCollection(__nativeList); + + _DeleteCollectionMapValue(__aliasList); +} + +_AppControlRegistry* +_AppControlRegistry::GetInstance(void) +{ + if (__pSelf == null) + { + SysLog(NID_APP, "Create new instance"); + __pSelf = new (std::nothrow) _AppControlRegistry(); + SysTryReturn(NID_APP, __pSelf != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); + SysAssertf(__pSelf != null, "AppControl registry instance creation failure"); + + __pSelf->LoadRegistry(); + + __pSelf->LoadLegacyList(); + + __pSelf->LoadAliasList(); + +#ifdef _SINGLETON_CLEANUP + _LongevityManager::GetInstance().RegisterOwnership(*__pSelf); +#endif + } + + return __pSelf; +} + +result +_AppControlRegistry::LoadRegistry(void) +{ + _RegistryImpl reg; + + String regPath = ACTL_PRIVATE_FILE; + + // if ACTL_SYSTEM does not exist, then use default name + if (!File::IsFileExist(regPath)) + { + regPath = ACTL_DEFAULT_FILE; + } + + result r = reg.Construct(regPath, REG_OPEN_READ_ONLY, null); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + const int sec_count = reg.GetAllSectionCount(); + SysTryReturnResult(NID_APP, !(sec_count <= 0), E_OBJ_NOT_FOUND, "Registry contains no data."); + + SysLog(NID_APP, "Loading %d sections from %ls", sec_count, regPath.GetPointer()); + + int index = 0; + int size = 0; + int num = 0; + String actl_path; + String actl_name; + + + // actual parameter manipulation + for (int i = 0; i < sec_count; i++) + { + /////////////////////////////////////////////////////////////////////// + // appcontrol Id + String sec_name(reg.GetSectionName(i)); + sec_name.Trim(); + + if (sec_name.IsEmpty()) + { + continue; + } + + int public_open = 0; + int launch_type = 0; + + /////////////////////////////////////////////////////////////////////// + // Plubic + index = reg.GetEntryIndex(i, ACTL_REGISTRY_PUBLIC); + if (index >= 0) + { + size = sizeof(size); + num = 0; + + reg.GetEntryValue(i, index, REG_VALUE_TYPE_INT, &num, &size); + if (num == 1) + { + // public + public_open = 1; + } + } + + /////////////////////////////////////////////////////////////////////// + // Launch type + index = reg.GetEntryIndex(i, ACTL_REGISTRY_LAUNCH_TYPE); + if (index >= 0) + { + size = sizeof(size); + + reg.GetEntryValue(i, index, REG_VALUE_TYPE_INT, &launch_type, &size); + } + + /////////////////////////////////////////////////////////////////////// + // Path + index = reg.GetEntryIndex(i, ACTL_REGISTRY_PATH); + if (index >= 0) + { + size = REG_VALUE_BUFFER_LEN; + reg.GetEntryValue(i, index, REG_VALUE_TYPE_STRING, &actl_path, &size); + + if (launch_type == _APPCONTROL_TYPE_OSP) + { + if (!_Aul::IsInstalled(actl_path)) + { + SysLog(NID_APP, "Osp app %ls not installed.", actl_path.GetPointer()); + continue; + } + // [FIXME] retrieve from package info here + } + } + + /////////////////////////////////////////////////////////////////////// + // Name + // [FIXME] SLP localized name here + index = reg.GetEntryIndex(i, ACTL_REGISTRY_TITLE); + if (index >= 0) + { + size = REG_VALUE_BUFFER_LEN; + reg.GetEntryValue(i, index, REG_VALUE_TYPE_STRING, &actl_name, &size); + } + + //SysLog(NID_APP, "%dth iteration : %ls", i, sec_name.GetPointer()); + + /////////////////////////////////////////////////////////////////////// + // Number of operation Id + index = reg.GetEntryIndex(i, ACTL_REGISTRY_OP_NUM); + if (index >= 0) + { + size = sizeof(size); + reg.GetEntryValue(i, index, REG_VALUE_TYPE_INT, &num, &size); + + String tagName; + String actl_opId; + + //SysLog(NID_APP, "number of operation %d for index %d", num, index); + + for (int j = 0; j < num; j++) + { + size = REG_VALUE_BUFFER_LEN; + + /////////////////////////////////////////////////////////////// + // operation Id + tagName.Format(10, L"OPID_%d", j); + + index = reg.GetEntryIndex(i, tagName); + if (index >= 0) + { + reg.GetEntryValue(i, index, REG_VALUE_TYPE_STRING, &actl_opId, &size); + actl_opId.Trim(); + } + //SysLog(NID_APP, "Operation(%d) %ls", index, actl_opId.GetPointer()); + + /////////////////////////////////////////////////////////////// + // AppControl allocation + + int prop = 0; + if (public_open == 1) + { + prop |= _APPCONTROL_PROPERTY_PUBLIC; + } + + switch (launch_type) + { + case _APPCONTROL_TYPE_NATIVE: + prop |= _APPCONTROL_PROPERTY_SLP; + break; + case _APPCONTROL_TYPE_OSP: + prop |= _APPCONTROL_PROPERTY_OSP; + break; + default: + SysLog(NID_APP, "Invalid launch type %d", launch_type); + break; + } + + //SysLog(NID_APP, "(%ls, %ls)", sec_name.GetPointer(), actl_opId.GetPointer()); + AppControl* pAc = _AppControlImpl::CreateN(actl_path, sec_name, actl_opId, actl_name, prop); + + if (pAc) + { + __nativeList.Add(pAc); + } + else + { + SysLog(NID_APP, "Failed to create AppControl instance (%ls, %ls, %d, %d)", + sec_name.GetPointer(), actl_opId.GetPointer(), public_open, launch_type); + } + } + } + + } + + SysLog(NID_APP, "Finished loading %d entries", __nativeList.GetCount()); + + return E_SUCCESS; +} + +result +_AppControlRegistry::LoadLegacyList(void) +{ + _RegistryImpl reg; + + const String& regPath(ACTL_LEGACY_FILE); + + result r = reg.Construct(regPath, REG_OPEN_READ_ONLY, null); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + const int sec_count = reg.GetAllSectionCount(); + SysTryReturnResult(NID_APP, !(sec_count <= 0), E_OBJ_NOT_FOUND, "Registry contains no data."); + + SysLog(NID_APP, "Loading %d sections from %ls", sec_count, regPath.GetPointer()); + + String aliasProvider; + String value; + + + // actual parameter manipulation + for (int i = 0; i < sec_count; i++) + { + /////////////////////////////////////////////////////////////////////// + // appcontrol Id + const String& secName(reg.GetSectionName(i)); + + /////////////////////////////////////////////////////////////////////// + // aliased appcontrol name + const int index = reg.GetEntryIndex(i, ACTL_REGISTRY_ALIAS_PROVIDER); + if (index >= 0) + { + int size = REG_VALUE_BUFFER_LEN; + reg.GetEntryValue(i, index, REG_VALUE_TYPE_STRING, &aliasProvider, &size); + } + + /////////////////////////////////////////////////////////////////////// + // Operations + IList* pList = reg.GetAllEntryNamesN(secName); + if (pList == null) + { + continue; + } + + std::unique_ptr pEnum(pList->GetEnumeratorN()); + + while (pEnum->MoveNext() == E_SUCCESS) + { + String* pStr = dynamic_cast(pEnum->GetCurrent()); + + if (pStr == null || pStr->IsEmpty() || pStr->Equals(ACTL_REGISTRY_ALIAS_PROVIDER, false)) + { + continue; + } + + r = reg.GetValue(secName, *pStr, value); + if (IsFailed(r)) + { + SysLog(NID_APP, "[%s] Propagating.", GetErrorMessage(r)); + continue; + } + + bool b = false; + __aliasOperation.ContainsKey(*pStr, b); + if (b) + { + __aliasOperation.SetValue(*pStr, value); + } + else + { + __aliasOperation.Add(*pStr, value); + } + + // add entry to aliasList + _AppControlAliasEntry* pEntry = new (std::nothrow) _AppControlAliasEntry(secName, *pStr, aliasProvider, value); + SysTryReturnResult(NID_APP, pEntry != null, E_OUT_OF_MEMORY, "Insufficient memory."); + + if (pEntry) + { + SysLog(NID_APP, "(%ls, %ls)", secName.GetPointer(), aliasProvider.GetPointer()); + __aliasList.Add(secName, pEntry); + } + } + + pList->RemoveAll(true); + delete pList; + } + + SysLog(NID_APP, "Finished loading %d entries with %d operation aliases.", __aliasList.GetCount(), __aliasOperation.GetCount()); + + return E_SUCCESS; +} + +result +_AppControlRegistry::LoadAliasList(void) +{ + _RegistryImpl reg; + + String regPath = ACTL_PRIVATE_ALIAS_FILE; + + // if ACTL_SYSTEM does not exist, then use default name + if (!File::IsFileExist(regPath)) + { + regPath = ACTL_ALIAS_FILE; + } + + result r = reg.Construct(regPath, REG_OPEN_READ_ONLY, null); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + HashMap* pMap = null; + r = reg.GetEntryListN(L"Alias", &pMap); + if (r != E_SUCCESS) + { + SysLog(NID_APP, "[%s] Propagating.", GetErrorMessage(r)); + delete pMap; + return r; + } + + String* pKey = null; + String* pVal = null; + std::unique_ptr pEnum(pMap->GetMapEnumeratorN()); + SysTryCatch(NID_APP, pEnum.get(), r = E_OUT_OF_MEMORY , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory error."); + + while(pEnum->MoveNext() == E_SUCCESS) + { + pKey = static_cast(pEnum->GetKey()); + pVal = static_cast(pEnum->GetValue()); + + __aliasAppId.Add(*pKey, *pVal); + //SysLog(NID_APP, "(%ls, %ls)", pKey->GetPointer(), pVal->GetPointer()); + } + + SysLog(NID_APP, "Loading %d alias sections", __aliasAppId.GetCount()); + +CATCH: + delete pMap; + + return r; +} + + +AppControl* +_AppControlRegistry::GetNativeAppControlN(const String& aId, const String& oId) const +{ + std::unique_ptr< IEnumeratorT > pEnum(__nativeList.GetEnumeratorN()); + + while (pEnum->MoveNext() == E_SUCCESS) + { + AppControl* pAc = null; + pEnum->GetCurrent(pAc); + + if (pAc->GetAppControlProviderId() == aId && pAc->GetOperationId() == oId) + { + SysLog(NID_APP, "Found matching AppControl (%ls, %ls)", aId.GetPointer(), oId.GetPointer()); + return _AppControlImpl::CreateN(*pAc); + } + } + + SysLog(NID_APP, "No matching AppControl (%ls, %ls)", aId.GetPointer(), oId.GetPointer()); + + return null; +} + +// +// data structure for _AppControlRegistry::GetAppControlListN() only +// +struct AppSvcIterData +{ +public: + AppSvcIterData(ArrayList* pArr, const String& op) : pArray(pArr), operation(op) {} + + ArrayList* pArray; + const String& operation; +}; + +// +// callback function for _AppControlRegistry::GetAppControlListN() +// +static int +AppSvcIterFnCb(const char* pAppId, void* pData) +{ + SysAssert(pData != null); + + AppSvcIterData* pAppSvcIterData = static_cast(pData); + ArrayList* pList = pAppSvcIterData->pArray; + SysAssert(pList != null); + const String& operation = pAppSvcIterData->operation; + + if (pAppId == NULL) + { + SysLog(NID_APP, "Empty appId received."); + return -1; + } + + String appId = pAppId; + AppControl* pAc = _AppControlImpl::CreateN(appId, operation, false); + if (pAc == null) + { + SysLog(NID_APP, "AppControl allocation failure for %ls.", appId.GetPointer()); + return -1; + } + + pList->Add(pAc); + + return 0; +} + +Tizen::Base::Collection::ArrayList* +_AppControlRegistry::FindAppControlListN(const String* pOid, const String* pUri, const String* pMimeType, const String* pCategory) const +{ + String operation = (pOid) ? *pOid : TIZEN_OPERATION_MAIN; + + std::unique_ptr pBundle(bundle_create()); + SysTryReturn(NID_APP, pBundle.get(), null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Bundle creation failure."); + + _AppMessageImpl::SetOperation(pBundle.get(), operation); + + if (pUri) + { + _AppMessageImpl::SetUri(pBundle.get(), *pUri); + } + + if (pMimeType) + { + _AppMessageImpl::SetMime(pBundle.get(), *pMimeType); + } + + if (pCategory) + { + _AppMessageImpl::SetCategory(pBundle.get(), *pCategory); + } + + ArrayList* pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] ArrayList creation failure."); + pList->Construct(); + + AppSvcIterData data(pList, operation); + + appsvc_get_list(pBundle.get(), AppSvcIterFnCb, reinterpret_cast(&data)); + + if (pList->GetCount() == 0) + { + SysLog(NID_APP, "Found no AppControl entry for operation %ls.", operation.GetPointer()); + + delete pList; + pList = null; + } + + return pList; +} + +_AppControlRegistry::_AppControlAliasEntry* +_AppControlRegistry::GetAppControlAliasEntry(const String& aId, const String& oId) const +{ + std::unique_ptr< IEnumeratorT<_AppControlAliasEntry*> > pEnum(__aliasList.GetValuesN(aId)); + if (pEnum.get() == null) + { + SysLog(NID_APP, "[E_OBJ_NOT_FOUND] No alias entry for %ls.", aId.GetPointer()); + return null; + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + _AppControlAliasEntry* pEntry = null; + pEnum->GetCurrent(pEntry); + if (pEntry->provider == aId && pEntry->operation == oId) + { + SysLog(NID_APP, "Found matching AppControl (%ls, %ls)->(%ls, %ls)", aId.GetPointer(), oId.GetPointer(), pEntry->provider2.GetPointer(), pEntry->operation2.GetPointer()); + + return pEntry; + } + } + + return null; +} + +_AppControlRegistry::_AppControlAliasEntry* +_AppControlRegistry::GetReverseAppControlAliasEntry(const String& aId, const String& oId) const +{ + std::unique_ptr< IMapEnumeratorT > pEnum(__aliasList.GetMapEnumeratorN()); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _AppControlAliasEntry* pEntry = null; + pEnum->GetValue(pEntry); + if (pEntry->provider2 == aId && pEntry->operation2 == oId) + { + SysLog(NID_APP, "Found matching AppControl (%ls, %ls)<-(%ls, %ls)", aId.GetPointer(), oId.GetPointer(), pEntry->provider.GetPointer(), pEntry->operation.GetPointer()); + + return pEntry; + } + } + + return null; +} + +AppControl* +_AppControlRegistry::GetAliasAppControlN(const String& aId, const String& oId) const +{ + _AppControlAliasEntry* pEntry = GetAppControlAliasEntry(aId, oId); + + if (pEntry) + { + AppControl* pAc = GetNativeAppControlN(pEntry->provider2, pEntry->operation2); + if (pAc) + { + _AppControlImpl* pImpl = _AppControlImpl::GetInstance(*pAc); + pImpl->SetProperty(_APPCONTROL_PROPERTY_ALIAS); + } + else + { + pAc = GetAppControlN(pEntry->provider2, pEntry->operation2); + if (pAc) + { + _AppControlImpl* pImpl = _AppControlImpl::GetInstance(*pAc); + pImpl->SetProperty(_APPCONTROL_PROPERTY_ALIAS); + } + else + { + SysLog(NID_APP, "No matching AppControl found."); + } + } + + return pAc; + } + + SysLog(NID_APP, "No matching AppControl found."); + return null; +} + +AppControl* +_AppControlRegistry::GetAppControlN(const String& appId, const String& operationId) const +{ + bool changeAppId = false; + + String actualAppId = appId; + if (appId.StartsWith(TIZEN_ALIAS_APPID_PREFIX, 0)) + { + String tmp; + result r = __aliasAppId.GetValue(appId, tmp); + if (r == E_SUCCESS) + { + actualAppId = tmp; + SysLog(NID_APP, "Found alias appId (%ls -> %ls).", appId.GetPointer(), tmp.GetPointer()); + + changeAppId = true; + } + } + + bool b = _Aul::IsInstalled(actualAppId); + SysTryReturn(NID_APP, b == true, null, E_APP_NOT_INSTALLED, "[E_APP_NOT_INSTALLED] %ls not installed.", actualAppId.GetPointer()); + + return _AppControlImpl::CreateN(actualAppId, operationId, changeAppId); +} + +AppId +_AppControlRegistry::GetReverseAliasAppId(const AppId& appId) const +{ + std::unique_ptr< IMapEnumeratorT > pEnum(__aliasAppId.GetMapEnumeratorN()); + + String key; + String value; + while (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetKey(key); + pEnum->GetValue(value); + if (value == appId) + { + return key; + } + } + + SysLog(NID_APP, "No entry found for %ls", appId.GetPointer()); + return L""; +} + +String +_AppControlRegistry::GetAliasedOperation(const String& operation) const +{ + bool b = false; + __aliasOperation.ContainsKey(operation, b); + + if (b) + { + String tmp; + __aliasOperation.GetValue(operation, tmp); + return tmp; + } + else + { + return String(); + } +} + +} } // Tizen::App diff --git a/src/app/FApp_AppControlRegistry.h b/src/app/FApp_AppControlRegistry.h new file mode 100644 index 0000000..12d9d33 --- /dev/null +++ b/src/app/FApp_AppControlRegistry.h @@ -0,0 +1,132 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlRegistry.h + * @brief This is the header file of the _AppControlRegistry class. + */ + +#ifndef _FAPP_INTERNAL_APP_CONTROL_REGISTRY_H_ +#define _FAPP_INTERNAL_APP_CONTROL_REGISTRY_H_ + +#include + +#include +#include +#include +#include +#include + +namespace Tizen { namespace App +{ + +class AppControl; + +struct BundleDeleter +{ + void operator()(bundle* pBundle) + { + if (pBundle) + { + bundle_free(pBundle); + } + } +}; + +/** + * @class _AppControlRegistry + * @brief load & store AppControl information + * @since 2.1 + */ +class _AppControlRegistry + : public Tizen::Base::Object +{ +public: + class _AppControlAliasEntry + { + public: + _AppControlAliasEntry(const Tizen::Base::String& aId1, + const Tizen::Base::String& oId1, + const Tizen::Base::String& aId2, + const Tizen::Base::String& oId2) + : provider(aId1) + , operation(oId1) + , provider2(aId2) + , operation2(oId2) + { + } + + const Tizen::Base::String provider; + const Tizen::Base::String operation; + const Tizen::Base::String provider2; + const Tizen::Base::String operation2; + }; + + typedef Tizen::Base::Collection::ArrayListT AppControlList; + typedef Tizen::Base::Collection::MultiHashMapT AppControlAliasList; + typedef Tizen::Base::Collection::HashMapT AliasMapType; + + _AppControlRegistry(void); + + virtual ~_AppControlRegistry(void); + + static _AppControlRegistry* GetInstance(void); + + AppControl* GetNativeAppControlN(const Tizen::Base::String& aId, const Tizen::Base::String& oId) const; + + AppControl* GetSlpAppControlN(const Tizen::Base::String& packageName, const Tizen::Base::String& oId) const; + + AppControl* GetAliasAppControlN(const Tizen::Base::String& aId, const Tizen::Base::String& oId) const; + + AppControl* GetAppControlN(const Tizen::Base::String& appId, const Tizen::Base::String& operationId) const; + + Tizen::Base::Collection::ArrayList* FindAppControlListN(const Tizen::Base::String* pOid, const Tizen::Base::String* pUri, const Tizen::Base::String* pMimeType, const Tizen::Base::String* pCategory) const; + + Tizen::Base::String GetAliasedOperation(const Tizen::Base::String& operation) const; + + _AppControlAliasEntry* GetAppControlAliasEntry(const Tizen::Base::String& aId, const Tizen::Base::String& oId) const; + + _AppControlAliasEntry* GetReverseAppControlAliasEntry(const Tizen::Base::String& aId, const Tizen::Base::String& oId) const; + + AppId GetReverseAliasAppId(const AppId& appId) const; + +private: + _AppControlRegistry(const _AppControlRegistry& rhs); + + _AppControlRegistry& operator =(const _AppControlRegistry& rhs); + + result LoadRegistry(void); + + result LoadLegacyList(void); + + result LoadAliasList(void); + +private: + AppControlList __nativeList; + + AppControlAliasList __aliasList; + + AliasMapType __aliasOperation; + + AliasMapType __aliasAppId; + + static _AppControlRegistry* __pSelf; +}; // _AppControlRegistry + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_CONTROL_REGISTRY_H_ diff --git a/src/app/FApp_AppEntry.cpp b/src/app/FApp_AppEntry.cpp new file mode 100644 index 0000000..88a0482 --- /dev/null +++ b/src/app/FApp_AppEntry.cpp @@ -0,0 +1,489 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppEntry.cpp + * @brief This is the entry point for the application. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include + + +#define LOG_IO_TAG "IO_LOG" +#define MAX_APPID 20 +#define MAX_APP_EXECUTABLE_NAME 230 +#define MAX_PACKAGE_NAME 100 +#define MAX_PR_NAME 16 + + +#ifdef __cplusplus +extern "C" +{ +#endif // __cplusplus + + +extern int OspMain(int argc, char* pArgv[]) __attribute__((weak)); +//extern void Osp_Initialize(); +extern void InitAppInfo(const char* appId, const char* exeName, int argc, char* pArgv[], int fd); + +static void +AdjustPrivilege(const char* pkgname) +{ + void* handle = dlopen("libprivilege-control.so.0", RTLD_LAZY | RTLD_LOCAL); + if (!handle) + { + fprintf(stderr, "Cannot open libprivilege-control.so.0\n"); + return; + } + + char* msg = 0; + dlerror(); + + int (* ppriv_func)(const char*) = NULL; + + ppriv_func = reinterpret_cast (dlsym(handle, "set_privilege")); + msg = dlerror(); + if (msg != NULL) + { + fprintf(stderr, "Dlsym error: %s\n", msg); + + dlclose(handle); + return; + } + + int ret = (*ppriv_func)(pkgname); + if (ret < 0) + { + fprintf(stderr, "set_privilege() returned %d\n", ret); + } + + dlclose(handle); +} + +extern "C" int capset(cap_user_header_t hdrp, const cap_user_data_t datap); + +static int +AdjustCapability(void) +{ + cap_user_header_t head = 0; + cap_user_data_t data = 0; + + head = static_cast(malloc(sizeof(*head))); + if (head == NULL) + { + fprintf(stderr, "Memory allocation failure.\n"); + return -1; + } + + head->version = _LINUX_CAPABILITY_VERSION; + head->pid = getpid(); + + data = static_cast(calloc(sizeof(*data), _LINUX_CAPABILITY_U32S)); + if (data == NULL) + { + fprintf(stderr, "Memory allocation failure.\n"); + + free(head); + return -1; + } + + data[CAP_TO_INDEX(CAP_NET_RAW)].effective |= CAP_TO_MASK(CAP_NET_RAW); + data[CAP_TO_INDEX(CAP_NET_RAW)].permitted |= CAP_TO_MASK(CAP_NET_RAW); + + if (capset(head, data) < 0) + { + fprintf(stderr, "Capability setting error\n"); + + free(data); + free(head); + return -1; + } + + free(data); + free(head); + + return 0; +} + + +static int +GetAppIdAppExecutableNameFromPathNew(const char appName[], char* appId, char* exeName) +{ + char buffer[PATH_MAX]; + + // path is "/opt/apps/[appid]/bin/[executable_name]" + + memset(buffer, 0, PATH_MAX); + const char* pRet = realpath(appName, buffer); + if (pRet == NULL) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, Improper appname %s", appName); + return -1; + } + + const char* p = strrchr(buffer, '/'); + if (p == NULL) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, Improper appname %s", appName); + return -1; + } + + const size_t pathLen = strlen(buffer); + const int execLen = strlen(p); + if (execLen <= 0 || execLen > PATH_MAX || pathLen > PATH_MAX) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, Improper appname %s", appName); + return -1; + } + + strncpy(exeName, p + 1, execLen); + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, exeName is %s", exeName); + + if (pathLen < 1 + 10 + strlen("/bin/") + execLen) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, Improper appname %s", appName); + return -1; + } + + strncpy(appId, p - strlen("bin/") - 10, 10); + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, appId is %s", appId); + + return 0; +} + +static int +GetAppIdAppExecutableNameFromPath(const char appName[], char* appId, char* exeName) +{ + const char* begin = NULL; + const char* end = NULL; + const int path_len = strlen(appName); + + // Calculate the header + const char* p = strstr(appName, "/apps/org.tizen."); + if (p == NULL) + { + return GetAppIdAppExecutableNameFromPathNew(appName, appId, exeName); + } + + begin = p + 15; + + end = strchr(begin + 1, '/'); + if (end == NULL) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, Improper appname %s", appName); + return -1; + } + + int len = end - begin - 1; + + if (len > MAX_APPID) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, Improper appname %s with length %d", appName, len); + len = MAX_APPID; + //return -1; + } + + strncpy(appId, begin + 1, len); + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, appId is %s", appId); + + int exe_len = 0; + + if (path_len > len + 21) + { + exe_len = std::min(MAX_APP_EXECUTABLE_NAME - 1, path_len - len - 21); + strncpy(exeName, end + 5, exe_len); + } + + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, exeName is %s", exeName); + + return 0; +} + +static bool +GetPackageNameFromAppIdAppExecutableName(const char appId[], const char exeName[], char* pkgName, int maxPkgName) +{ + // package name is "org.tizen.[appid]#[executable]" + + //snprintf(pkgName, maxPkgName, "org.tizen.%s#%s", appId, exeName); + snprintf(pkgName, maxPkgName, "%s", appId); + + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::App, packageName is %s", pkgName); + + return true; +} + +static void +PrintArgs(int argc, char* argv[]) +{ + const char* p = NULL; + int i = 0; + do + { + p = argv[i]; + LOG(LOG_DEBUG, LOG_IO_TAG, "%dth arg : [%s]", i, p); + i++; + } + while (p); +} + +static int +DoPreExec(const char* packageName, const char* bin_path) +{ + void* handle = NULL; + char* errormsg = 0; + int (* DoPreExecFunc)(const char*, const char*) = NULL; + int ret = 0; + + handle = dlopen("libosp-env-config.so", RTLD_LAZY | RTLD_GLOBAL); + if (!handle) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io > Failed to dlopen libosp-env-config.so (%s)", dlerror()); + return -1; + } + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io > dlopen() ok"); + + DoPreExecFunc = reinterpret_cast (dlsym(handle, "do_pre_exec")); + errormsg = dlerror(); + if (errormsg != NULL) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io > Failed to dlsym() (%s)", errormsg); + dlclose(handle); + return -1; + } + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io > dlsym() ok"); + + ret = DoPreExecFunc(packageName, bin_path); + if (ret < 0) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io > Failed to do_pre_exe() (%d)", ret); + } + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io > do_pre_exe() ok"); + + dlclose(handle); + + return 0; +} + +static void +ChangeProcessName(const char* fullPath, int argc, char** const argv) +{ + // http://stupefydeveloper.blogspot.com/2008/10/linux-change-process-name.html + // [INFO] While this implementation may not be portable, most program loader does similar work. + + // fullPath should be less than original size + const int size = strlen(argv[0]); + char* args = argv[0]; + memset(args, '\0', size); + strncpy(args, fullPath, size - 1); + + const char* fileName = NULL; + fileName = strrchr(fullPath, '/') + 1; + if (fileName) + { + char procName[MAX_PR_NAME]; + memset(procName, '\0', MAX_PR_NAME); + + snprintf(procName, MAX_PR_NAME - 1, "%s", fileName); + prctl(PR_SET_NAME, procName); + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, %s, %d > Process name %s.", __func__, __LINE__, procName); + } +} + +static int +GetDirFdFromPath(const char* pPath) +{ + int count = 0; + const int len = strlen(pPath); + char dname[PATH_MAX]; + memset(dname, 0, PATH_MAX); + + const char* p = pPath + len; + for (int i = 0; i < len; i++, p--) + { + if (*p == '/') + { + count++; + + if (count == 2) + { + goto OUT; + } + } + } + + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, %s, %d > Wrong path format : %s.", __func__, __LINE__, pPath); + + return -1; + +OUT: + strncpy(dname, pPath, p - pPath); + + const int fd = open(dname, O_RDONLY | O_CLOEXEC | O_DIRECTORY); + + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::App, %s, %d > Directory path : %s, fd : %d.", __func__, __LINE__, dname, fd); + + return fd; +} + + +static void +AdjustHwAccInfo(const char* packageId, const char* execName) +{ + char appId[MAX_APPID + MAX_APP_EXECUTABLE_NAME + 2] = {0, }; + strncpy(appId, packageId, 10); + appId[10] = '.'; + strncpy(appId + 11, execName, MAX_APP_EXECUTABLE_NAME); + + pkgmgrinfo_appinfo_h appHandle = NULL; + int ret = pkgmgrinfo_appinfo_get_appinfo(appId, &appHandle); + if (ret != PMINFO_R_OK) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::App, %s, %d > Getting package info failed for %s.", __func__, __LINE__, appId); + return; + } + + pkgmgrinfo_app_hwacceleration hwAcceleration; + + ret = pkgmgrinfo_appinfo_get_hwacceleration(appHandle, &hwAcceleration); + if (ret != PMINFO_R_OK) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::App, %s, %d > Getting hwaccel info failed for %s.", __func__, __LINE__, appId); + pkgmgrinfo_appinfo_destroy_appinfo(appHandle); + } + + switch(hwAcceleration) + { + case PMINFO_HWACCELERATION_NOT_USE_GL: + setenv("HWACC", "NOT_USE", 1); + break; + case PMINFO_HWACCELERATION_USE_GL: + setenv("HWACC", "USE", 1); + break; + case PMINFO_HWACCELERATION_USE_SYSTEM_SETTING: + break; + default: + // no need to handle default + break; + } + + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::App, %s, %d > HWACC sets for %s with %d.", __func__, __LINE__, appId, hwAcceleration); + pkgmgrinfo_appinfo_destroy_appinfo(appHandle); +} + + +/** +* The entry function of SLP application called by the operating system. +*/ +int _OSP_EXPORT_ +main(int argc, char* pArgv[]) +{ + bool bCommand = false; + + char appId[MAX_APPID]; + char exeName[MAX_APP_EXECUTABLE_NAME]; + char packageName[MAX_PACKAGE_NAME]; + char fullPath[PATH_MAX]; + + memset(appId, 0, MAX_APPID); + memset(exeName, 0, MAX_APP_EXECUTABLE_NAME); + memset(packageName, 0, MAX_PACKAGE_NAME); + memset(fullPath, 0, PATH_MAX); + + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, %s, %d > executable binary path: %s", __func__, __LINE__, pArgv[0]); + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, %s, %d > uid: %d, euid: %d", __func__, __LINE__, getuid(), geteuid()); + + const int len = strlen(pArgv[0]); + bCommand = (len > 4 && (strncmp(pArgv[0] + len - 4, ".exe", 4) == 0)); + if (bCommand) + { + const int path_size = std::min(PATH_MAX - 1, len - 4); + strncpy(fullPath, pArgv[0], path_size); + } + else + { + strncpy(fullPath, pArgv[0], PATH_MAX - 1); + } + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, %s, %d > processed binary path: %s", __func__, __LINE__, fullPath); + + // convert package path to appId + GetAppIdAppExecutableNameFromPath(fullPath, appId, exeName); + GetPackageNameFromAppIdAppExecutableName(appId, exeName, packageName, MAX_PACKAGE_NAME); + + if (getuid() == 0) + { + // self caging + DoPreExec(packageName, fullPath); + + // adjust privilege + AdjustPrivilege(packageName); + } + + AdjustCapability(); + + PrintArgs(argc, pArgv); + + if (bCommand) + { + ChangeProcessName(fullPath, argc, pArgv); + pArgv[0] = strdup(fullPath); + } + + int fd = GetDirFdFromPath(pArgv[0]); + if (fd == -1) + { + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, %s, %d > Failed to open path.", __func__, __LINE__); + return -1; + } + + // dlopen will load Osp_Initialize() internally as __attribute__((constructor)) + //Osp_Initialize(); + InitAppInfo(appId, exeName, argc, pArgv, fd); + + AdjustHwAccInfo(appId, exeName); + + int r = OspMain(argc, pArgv); + + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, %s, %d > OSP application is terminated.", __func__, __LINE__); + LOG(LOG_DEBUG, LOG_IO_TAG, "Tizen::Io, %s, %d > uid: %d, euid: %d", __func__, __LINE__, getuid(), geteuid()); + + return r; +} + +#ifdef __cplusplus +} +#endif // __cplusplus diff --git a/src/app/FApp_AppImpl.cpp b/src/app/FApp_AppImpl.cpp new file mode 100644 index 0000000..bc07e0e --- /dev/null +++ b/src/app/FApp_AppImpl.cpp @@ -0,0 +1,1210 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppImpl.cpp + * @brief This is the implementation for the _AppImpl class. + */ + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "FApp_IAppManager.h" +#include "FApp_AppManagerProxy.h" +#include "FApp_AppImpl.h" +#include "FApp_AppInfo.h" +#include "FApp_AppControlManager.h" +#include "FApp_AppArg.h" +#include "FApp_IAppImpl.h" +#include "FApp_AppResourceImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Io; +using namespace Tizen::System; + +namespace +{ + +const int HEARTBEAT_WAIT_COUNT = 20; +const char HEARBEAT_PATH[] = "/tmp/osp-initialized"; +const wchar_t SERVICE_APPID[] = L"aospd00043.osp-app-service"; +const char SELECTOR_RESPONSE_KEY[] = "__APP_SVC_START_INFO__"; + +} + +namespace Tizen { namespace App +{ + +_AppImpl* _AppImpl::__pAppImpl = null; +bool _AppImpl::__isTerminationRequested = false; +static const int _DATACONTROL_PACKET_INDEX_APPID = 0; +static const int _DATACONTROL_PACKET_INDEX_REQUESTTYPE = 1; +static const int _DATACONTROL_PACKET_INDEX_REQID = 2; +static const int _DATACONTROL_PACKET_INDEX_PROVIDERID = 3; +static const int _DATACONTROL_PACKET_INDEX_DATAID = 4; +static const int _DATACONTROL_PACKET_INDEX_COLUMNCOUNT = 5; +static const int _DATACONTROL_PACKET_INDEX_DELETEWHERE = 5; +static const int _DATACONTROL_PACKET_INDEX_COLUMNLIST = 6; +static const int _DATACONTROL_PACKET_INDEX_INSERTMAP = 6; +static const int _DATACONTROL_PACKET_INDEX_UPDATEMAP = 6; + +_AppImpl::_AppImpl(App* pApp) + : __pCheckpointEventListener(null) + , __pSqlDataControlProviderEventListener(null) + , __pMapDataControlProviderEventListener(null) + , __pAppControlProviderEventListener(null) + , __pAppControlProviderInternalEventListener(null) + , __pAppLaunchConditionEventListener(null) + , __pApp(pApp) + , __pIAppImpl(null) + , __pRequestHandler(&_AppImpl::HandleAppRequest) + , __pLegacyRequestHandler(&_AppImpl::HandleDummyAppRequest) +{ + __pAppImpl = this; +} + + +result +_AppImpl::Construct(const IList* pArgs) +{ + SysTryReturnResult(NID_APP, pArgs != null, E_INVALID_ARG, "pArguments must not be null."); + SysAssertf(__pApp != null, "Getting App instance failed."); + + result r = __appUserEvent.Construct(); + SysTryLog(NID_APP, !IsFailed(r), "[%s] User event handler failure.", GetErrorMessage(r)); + + __appUserEvent.AddListener(*this); + + _AppInfo::SetAppState(INITIALIZING); + + return E_SUCCESS; +} + + +result +_AppImpl::Execute(_IAppImpl* pIAppImpl) +{ + result r = E_SUCCESS; + int eflResult = APP_ERROR_NONE; + int argc = _AppInfo::GetArgc(); + char** pArgv = _AppInfo::GetArgv(); + _IAppManager* pAppManager = null; + + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturnResult(NID_APP, pAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + pAppImpl->__pIAppImpl = pIAppImpl; + + // handle legacy version handling + if (_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat()) + { + pAppImpl->SetLegacyRequestHandler(); + } + + // clear previous notification + // [INFO] behavior change : platform does not clear previous notification + notification_delete_all_by_type(NULL, NOTIFICATION_TYPE_NOTI); + + app_event_callback_s state_handler; + memset(&state_handler, 0, sizeof(app_event_callback_s)); + + state_handler.create = &OnCreate; + state_handler.service = &OnService; + state_handler.terminate = &OnTerminate; + state_handler.pause = &OnPause; + state_handler.resume = &OnResume; + state_handler.device_orientation = &OnDeviceOrientationChanged; + + state_handler.low_memory = &OnLowMemory; + state_handler.low_battery = &OnLowBattery; + state_handler.language_changed = &OnLanguageChanged; + state_handler.region_format_changed = &OnRegionFormatChanged; + + _Aul::SetPowerOffNotiListener(OnPowerOffNotiReceived, this); +// if (pAppManager != null) +// { +// r = pAppManager->RegisterApplication(_AppInfo::GetPackageId(), _AppInfo::GetAppExecutableName(), _AppInfo::GetAppType() , _AppInfo::GetProcessId()); +// SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Application registration failed.", GetErrorMessage(r)); +// } + + eflResult = app_efl_main(&argc, &pArgv, &state_handler, this); + + SysTryLog(NID_APP, eflResult == APP_ERROR_NONE, "app_efl_main failed with error (%d): Unknown", eflResult); + + // clear outstanding ongoing notification + notification_delete_all_by_type(NULL, NOTIFICATION_TYPE_ONGOING); + +//CATCH: + pAppManager = _AppManagerProxy::GetService(); + + if (pAppManager != null) + { + pAppManager->UnregisterApplication(_AppInfo::GetProcessId()); + } + + return r; +} + + +bool +_AppImpl::OnCreate(void* user_data) +{ + SysLog(NID_APP, "Platform creation event."); + + _AppInfo::SetAppState(INITIALIZING); + + _PowerManagerImpl::InitBatteryEvent(); + + return true; +} + + +void +_AppImpl::OnService(service_s* service, void* user_data) +{ + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturnVoidResult(NID_APP, pAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + SysTryReturnVoidResult(NID_APP, pAppImpl->__pIAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + + // ugly code for app selector event handling + bundle* pBundle = _AppArg::GetBundleFromSvc(service); + if (pBundle) + { + const char* pValue = appsvc_get_data(pBundle, SELECTOR_RESPONSE_KEY); + if (pValue) + { + const int req = _AppArg::GetRequestIdFromBundle(pBundle); + + const char* pOperation = appsvc_get_operation(pBundle); + + SysLog(NID_APP, "App selector response [%s, %s], req(%d).", pValue, pOperation, req); + + //_AppArg::Print(pBundle); + _AppControlManager::GetInstance()->SendAppControlStartResponse(req, pValue, pOperation); + return; + } + } + + int req = -1; + _AppHandler handler = _APP_HANDLER_NONE; + pAppImpl->RegisterAppRequest(service, req, handler); + + bool initialLaunch = false; + + // initial launch + // (1) OnAppInitializing() + // (2) OnAppInitialized() + // (3) AppControl / DataControl provider listener + // (4) OnResume() (OnForeground()) (UiApp only) + // (5) OnUserEventReceivedN() + + // already launched + // (1) AppControl / DataControl provider listener + // (2) OnResume() (OnForeground()) (UiApp only) + // (3) OnUserEventReceivedN() + + if (_AppInfo::GetAppState() == INITIALIZING) + { + initialLaunch = true; + + unsigned int winId = 0; + service_get_window(service, &winId); + if (winId > 0) + { + _AppInfo::GetAppInfo()->SetParentWindowHandle(winId); + SysLog(NID_APP, "Saving window handle 0x%x.", winId); + } + + if (!ConfirmAppService()) + { + _AppInfo::SetAppState(TERMINATED); + SysLogException(NID_APP, E_INIT_FAILED, "[E_INIT_FAILED] Osp AppService is not running."); + app_efl_exit(); + return; + } + + if (!pAppImpl->__pIAppImpl->OnAppInitializing()) + { + _AppInfo::SetAppState(TERMINATED); + SysLogException(NID_APP, E_INIT_FAILED, "[E_INIT_FAILED] The initialization of your application failed."); + app_efl_exit(); + return; + } + + _IAppManager* pAppManager = _AppManagerProxy::GetService(); + + if (pAppManager != null) + { + result r = pAppManager->RegisterApplication(_AppInfo::GetPackageId(), _AppInfo::GetAppExecutableName(), _AppInfo::GetAppType() , _AppInfo::GetProcessId()); + SysTryReturnVoidResult(NID_APP, !IsFailed(r), r, "[%s] Application registration failed.", GetErrorMessage(r)); + } + + // hide splash window + + // call for callbacks + // ptr to member function + (pAppImpl->*pAppImpl->__pRequestHandler)(service, req, handler); + + if (!pAppImpl->__pIAppImpl->OnAppInitialized()) + { + _AppInfo::SetAppState(TERMINATING); + SysLog(NID_APP, "[E_INIT_FAILED] The Initialization of your application failed."); + app_efl_exit(); + return; + } + + _AppInfo::SetAppState(RUNNING); + } + else + { + // already running + + // call for callbacks + // ptr to member function + (pAppImpl->*pAppImpl->__pRequestHandler)(service, req, handler); + } + + pAppImpl->__pIAppImpl->OnService(service, initialLaunch); + + // ptr to member function + (pAppImpl->*pAppImpl->__pLegacyRequestHandler)(service, req, handler); +} + + +void +_AppImpl::OnTerminate(void* user_data) +{ + SysLog(NID_APP, "Termination event 0x%x state", _AppInfo::GetAppState()); + + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturnVoidResult(NID_APP, pAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + SysTryReturnVoidResult(NID_APP, pAppImpl->__pIAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + + __isTerminationRequested = true; + pAppImpl->__pIAppImpl->OnTerminate(); +} + + +void +_AppImpl::OnResume(void* user_data) +{ + SysLog(NID_APP, "System resume event on 0x%x state", _AppInfo::GetAppState()); + + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturnVoidResult(NID_APP, pAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + SysTryReturnVoidResult(NID_APP, pAppImpl->__pIAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + pAppImpl->__pIAppImpl->OnResume(); +} + + +void +_AppImpl::OnPause(void* user_data) +{ + SysLog(NID_APP, "System pause event on 0x%x state", _AppInfo::GetAppState()); + + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturnVoidResult(NID_APP, pAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + SysTryReturnVoidResult(NID_APP, pAppImpl->__pIAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + pAppImpl->__pIAppImpl->OnPause(); + pAppImpl->OnAppCheckpoint(); +} + + +void +_AppImpl::OnDeviceOrientationChanged(app_device_orientation_e orientation, void* user_data) +{ + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturnVoidResult(NID_APP, pAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + SysTryReturnVoidResult(NID_APP, pAppImpl->__pIAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + + const AppState state = _AppInfo::GetAppState(); + SysTryReturnVoidResult(NID_APP, state == INITIALIZING || state == RUNNING, E_INVALID_STATE, "[E_INVALID_STATE] Invalid application state : %d.", state); + + pAppImpl->__pIAppImpl->OnDeviceOrientationChanged(orientation); +} + + +_AppImpl::~_AppImpl(void) +{ + __pAppImpl = null; +} + + +_AppImpl* +_AppImpl::GetInstance(void) +{ + return __pAppImpl; +} + + +App* +_AppImpl::GetAppInstance(void) +{ + return __pApp; +} + + +IList* +_AppImpl::GetAppArgumentListN(void) const +{ + ArrayList* pList = null; + const _AppArg* pArg = _AppControlManager::GetInstance()->FindResultRequest(0); + + if (pArg) + { + pList = pArg->GetArgListN(0); + } + else + { + // fallback + pList = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + String* pData = new (std::nothrow) String(LEGACY_LAUNCH_REASON_NORMAL); + SysTryReturn(NID_APP, pData != null, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + String* pData2 = new (std::nothrow) String(L"osp.operation.MAIN"); + SysTryReturn(NID_APP, pData2 != null, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + + pList->Construct(); + pList->Add(*pData); + pList->Add(*pData2); + } + + return pList; +} + + +result +_AppImpl::Terminate(void) +{ + result r = E_SUCCESS; + + __isTerminationRequested = true; + + app_efl_exit(); + return r; +} + + +bool +_AppImpl::OnAppInitializing(void) +{ + return false; +} + + +bool +_AppImpl::OnAppWillTerminate(void) +{ + SysTryReturn(NID_APP, __pApp != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting internal instance failed."); + + return __pApp->OnAppWillTerminate(); +} + + +result +_AppImpl::RegisterAppRequest(service_s* service, int& req, _AppHandler& handler) +{ + _AppControlManager* pManager = _AppControlManager::GetInstance(); + SysTryReturnResult(NID_APP, pManager != null, E_SYSTEM, "Wrong system state."); + + result r = pManager->RegisterRequest(service, req, handler); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + int providerType = _AppInfo::GetAppHandlerType(); + providerType |= (_APP_HANDLER_LAUNCH_NORMAL | _APP_HANDLER_LAUNCH_COND); + + SysTryLog(NID_APP, (handler & providerType) != 0, "Request 0x%x received for 0x%x.", handler, + _AppInfo::GetAppHandlerType()); + return E_SUCCESS; +} + + +result +_AppImpl::HandleAppRequest(service_s* service, int req, _AppHandler handler) +{ + const _AppArg* pArg = _AppControlManager::GetInstance()->FindResultRequest(req); + SysTryReturnResult(NID_APP, pArg != null, E_SYSTEM, "No argument found for %d.", req); + + pArg->Print(); + + switch (handler) + { + case _APP_HANDLER_DATACONTROL: + SysLog(NID_APP, "Handling DataControl request"); + + OnDataControlRequestReceived(*pArg, static_cast< RequestId >(req)); + + _AppControlManager::GetInstance()->RemoveResultRequest(req); + break; + + case _APP_HANDLER_LAUNCH_COND: + SysLog(NID_APP, "Handling conditional launch request"); + + OnConditionRequestReceived(*pArg, static_cast< RequestId >(req)); + break; + + default: + SysLog(NID_APP, "Handling AppControl request"); + + OnAppControlRequestReceived(*pArg, static_cast< RequestId >(req)); + break; + } + + return E_SUCCESS; +} + + +result +_AppImpl::HandleLegacyAppRequest(service_s* service, int req, _AppHandler handler) +{ + const _AppArg* pArg = _AppControlManager::GetInstance()->FindResultRequest(0); + SysTryReturnResult(NID_APP, pArg != null, E_SYSTEM, "No argument found for %d.", req); + + //pArg->Print(); + + switch (handler) + { + case _APP_HANDLER_LAUNCH_NORMAL: + SysLog(NID_APP, "Handling normal launch request"); + OnUserEventReceivedN(AppLaunchRequestId, pArg->GetArgListN(req)); + + // [TODO] request handle memory cleanup confirm + _AppControlManager::GetInstance()->RemoveResultRequest(req); + break; + + case _APP_HANDLER_LAUNCH_COND: + SysLog(NID_APP, "Handling conditional launch request"); + + OnUserEventReceivedN(AppLaunchRequestId, pArg->GetArgListN(req)); + + // [TODO] request handle memory cleanup confirm + _AppControlManager::GetInstance()->RemoveResultRequest(req); + break; + + default: + break; + } + + return E_SUCCESS; +} + + +result +_AppImpl::HandleDummyAppRequest(service_s* service, int req, _AppHandler handler) +{ + SysLog(NID_APP, "Dummy handler"); + + return E_SUCCESS; +} + + +result +_AppImpl::SetLegacyRequestHandler(void) +{ + SysLog(NID_APP, "Setting request handler for legacy application."); + + __pRequestHandler = &_AppImpl::HandleDummyAppRequest; + __pLegacyRequestHandler = &_AppImpl::HandleLegacyAppRequest; + + return E_SUCCESS; +} + + +void +_AppImpl::OnLowMemory(void* user_data) +{ + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + + SysTryReturnVoidResult(NID_APP, pAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting internal instance failed."); + SysTryReturnVoidResult(NID_APP, pAppImpl->__pApp != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting internal instance failed."); + + if (_AppInfo::GetAppState() == RUNNING) + { + pAppImpl->__pApp->OnLowMemory(); + } +} + + +void +_AppImpl::OnLowBattery(void* user_data) +{ + // Osp doesn't implement this callback. +} + +void +_AppImpl::OnBatteryLevelChanged(BatteryLevel batteryLevel) +{ + SysTryReturnVoidResult(NID_APP, __pApp != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting internal instance failed."); + + __pApp->OnBatteryLevelChanged(batteryLevel); +} + +void +_AppImpl::OnLanguageChanged(void* user_data) +{ + SysLog(NID_APP, ""); + _AppInfo::UpdatePackageInfo(true); + _AppResourceImpl::GetInstance()->Reinitialize(); +} + +void +_AppImpl::OnRegionFormatChanged(void* user_data) +{ + // Osp doesn't implement this callback. +} + + +result +_AppImpl::SendUserEvent(RequestId requestId, const IList* pArgs) +{ + _AppUserEventArg* pArg = new (std::nothrow) _AppUserEventArg(requestId, pArgs); + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "User event creation failure for %d.", requestId); + + result r = __appUserEvent.FireAsync(*pArg); + + return r; +} + + +void +_AppImpl::OnUserEventReceivedN(RequestId requestId, IList* pArgs) +{ + SysTryReturnVoidResult(NID_APP, __pApp != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting internal instance failed."); + + __pApp->OnUserEventReceivedN(requestId, pArgs); +} + + +void +_AppImpl::OnAppControlRequestReceived(const _AppArg& arg, RequestId reqId) +{ + const String& internalOperation = arg.GetValue(OSP_K_APPCONTROL_INTERNAL_OPERATION); + bool isInternalOperation = ( __pAppControlProviderInternalEventListener != null && internalOperation.IsEmpty() == false); + + if (__pAppControlProviderEventListener == null && isInternalOperation == false) + { + SysLog(NID_APP, "No AppControl provider event listener set for request %d.", reqId); + return; + } + + const String& appId = _AppInfo::GetApplicationId(); + + const char* p = appsvc_get_operation(arg.GetBundle()); + String operationId = (p) ? String(p) : TIZEN_OPERATION_MAIN; + if (operationId == L"http://tizen.org/appcontrol/operation/default") + { + operationId = TIZEN_OPERATION_MAIN; + } + + SysLog(NID_APP, "AppControl (%ls, %ls).", appId.GetPointer(), operationId.GetPointer()); + + String uri; + String mime; + const String* pUri = null; + const String* pMime = null; + p = appsvc_get_uri(arg.GetBundle()); + if (p) + { + uri = p; + pUri = &uri; + + SysLog(NID_APP, "Delivered uri is [%ls].", pUri->GetPointer()); + } + + p = appsvc_get_mime(arg.GetBundle()); + if (p) + { + mime = p; + pMime = &mime; + } + + std::unique_ptr pMap(arg.GetArgMapN()); + + if( isInternalOperation ) + { + __pAppControlProviderInternalEventListener->OnAppControlRequestReceived(reqId, operationId, pUri, pMime, pMap.get()); + } + else + { + __pAppControlProviderEventListener->OnAppControlRequestReceived(reqId, operationId, pUri, pMime, pMap.get()); + } + + SysLog(NID_APP, "AppControl (%ls, %ls) invocation finished.", appId.GetPointer(), operationId.GetPointer()); +} + + +void +_AppImpl::OnDataControlRequestReceived(const _AppArg& arg, RequestId reqId) +{ + String tempFilePath; + ISqlDataControlProviderEventListener* pSqlListener = null; + IMapDataControlProviderEventListener* pMapListener = null; + ArrayList* pColumnList = null; + HashMap* pInsertMap = null; + HashMap* pUpdateMap = null; + String* pAppId = null; + String* pRequestType = null; + String* pProviderId = null; + String* pDataId = null; + String* pReqId = null; + String* pColumnCount = null; + String* pColumn = null; + String* pValue = null; + String* pWhere = null; + String* pOrder = null; + String* pErrorMsg = null; + String* pNo = null; + String* pCount = null; + String empty(L"NULL"); +#if 0 + _DataControlResultSetImpl* pResultSetImpl = null; + String* pResult = null; + String* pObject = null; + String* pTempObject = null; + String* pTempFilePath = null; +#endif + _AppArg resultArg; + int type = 0; + _DataControlRequestType requestType = _DATACONTROL_REQUEST_TYPE_UNDEFINED; + int columnCount = 0; + int pageNo = 0; + int countPerPage = 0; + int i = 0; + int index = 0; + //ArrayList* pResultArgList = null; + result r = E_SUCCESS; + result res = E_SUCCESS; + ArrayList* pList = null; + String* pKey = null; + String* pNewValue = null; + String* pOldValue = null; +#if 0 + String* pResultCount = null; + String* pResultValue = null; +#endif + + SysLog(NID_APP, "[DC_PROVIDER] Data control request is received."); + //arg.Print(); + + pList = arg.GetArgListN(0); + SysTryCatch(NID_APP, pList, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + // key-based + pAppId = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_APPID)); // key(0) + SysTryCatch(NID_APP, pAppId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + pRequestType = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_REQUESTTYPE)); // key(1) + SysTryCatch(NID_APP, pRequestType, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + Integer::Parse(*pRequestType, type); + requestType = static_cast< _DataControlRequestType >(type); + + pReqId = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_REQID)); // key(2) + SysTryCatch(NID_APP, pReqId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + pProviderId = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_PROVIDERID)); // key(3) + SysTryCatch(NID_APP, pProviderId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + // list-based + pDataId = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_DATAID));// list(0): data ID + SysTryCatch(NID_APP, pDataId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + if (requestType >= _DATACONTROL_REQUEST_TYPE_SQL_QUERY && requestType <= _DATACONTROL_REQUEST_TYPE_SQL_DELETE) + { + pSqlListener = __pSqlDataControlProviderEventListener; + SysTryCatch(NID_APP, pSqlListener != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + } + else if (requestType >= _DATACONTROL_REQUEST_TYPE_MAP_QUERY && requestType <= _DATACONTROL_REQUEST_TYPE_MAP_DELETE) + { + pKey = dynamic_cast< String* >(pList->GetAt(5)); // list[1] + SysTryCatch(NID_APP, pKey, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + pMapListener = __pMapDataControlProviderEventListener; + SysTryCatch(NID_APP, pMapListener != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + } + else + { + SysLogException(NID_APP, E_SYSTEM, "[E_SYSTEM] invalid request"); + r = E_SYSTEM; + } + + switch (requestType) + { + case _DATACONTROL_REQUEST_TYPE_SQL_QUERY: + SysLog(NID_APP, "[DC_PROVIDER] SqlDataControl SELECT"); + + // list(1): selected column count + pColumnCount = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_COLUMNCOUNT)); + SysTryCatch(NID_APP, pColumnCount, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + if (pColumnCount->Equals(empty) == true) + { + pColumnList = null; + } + else + { + Integer::Parse(*pColumnCount, columnCount); + pColumnList = new (std::nothrow) ArrayList(); + SysTryReturnVoidResult(NID_APP, pColumnList, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); + pColumnList->Construct(); + SysLog(NID_APP, "[DC_PROVIDER] selected column count: %d", columnCount); + + i = 0; + while (i < columnCount) // list(2): column list + { + pColumn = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_COLUMNLIST + i)); + SysTryCatch(NID_APP, pColumn != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + pColumnList->Add(*(new String(*pColumn))); + SysLog(NID_APP, "[DC_PROVIDER] column[%d]: %ls", i, pColumn->GetPointer()); + i++; + } + } + + i += _DATACONTROL_PACKET_INDEX_COLUMNLIST; + pWhere = dynamic_cast< String* >(pList->GetAt(i)); // list(3): where clause + SysTryCatch(NID_APP, pWhere, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + if (pWhere->Equals(empty) == true) + { + pWhere = null; + } + else + { + SysLog(NID_APP, "[DC_PROVIDER] pWhere: %ls", pWhere->GetPointer()); + } + + i++; + pOrder = dynamic_cast< String* >(pList->GetAt(i)); // list(4): order clause + SysTryCatch(NID_APP, pOrder, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + if (pOrder->Equals(empty) == true) + { + pOrder = null; + } + else + { + SysLog(NID_APP, "[DC_PROVIDER] pOrder: %ls", pOrder->GetPointer()); + } + + i++; + pNo = dynamic_cast (pList->GetAt(i)); // list(5): page number + SysTryCatch(NID_APP, pNo, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + Integer::Parse(*pNo, pageNo); + + i++; + pCount = dynamic_cast (pList->GetAt(i)); // list(6): count per page + SysTryCatch(NID_APP, pCount, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + Integer::Parse(*pCount, countPerPage); + + pSqlListener->OnSqlDataControlSelectRequestReceived(reqId, *pProviderId, *pDataId, pColumnList, + pWhere, pOrder); + + SysLog(NID_APP, "[DC_PROVIDER] caller appId: %ls, requestType: %d, reqId: %ls, providerId: %ls, dataId: %ls, pColumnList: 0x%0x, pWhere: 0x%x, pOrder: 0x%x, pageNo: %d, countPerPage: %d", + pAppId->GetPointer(), requestType, pReqId->GetPointer(), pProviderId->GetPointer(), + pDataId->GetPointer(), pColumnList, pWhere, pOrder, pageNo, countPerPage); + break; + case _DATACONTROL_REQUEST_TYPE_SQL_INSERT: + SysLog(NID_APP, "[DC_PROVIDER] SqlDataControl INSERT"); + + // list(1): insert column count + pColumnCount = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_COLUMNCOUNT)); + SysTryCatch(NID_APP, pColumnCount, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + Integer::Parse(*pColumnCount, columnCount); + SysLog(NID_APP, "[DC_PROVIDER] inserted column count: %d", columnCount); + + pInsertMap = new (std::nothrow) HashMap(); + SysTryReturnVoidResult(NID_APP, pInsertMap, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); + pInsertMap->Construct(); + + i = 0; + index = 0; + while (i < columnCount * 2) // list(2): column-value pairs + { + pColumn = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_INSERTMAP + i++)); + SysTryCatch(NID_APP, pColumn != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + SysLog(NID_APP, "[DC_PROVIDER] column[%d]: %ls", index, pColumn->GetPointer()); + + pValue = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_INSERTMAP + i++)); + SysTryCatch(NID_APP, pValue != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + SysLog(NID_APP, "[DC_PROVIDER] value[%d]: %ls", index, pValue->GetPointer()); + + pInsertMap->Add(*(new String(*pColumn)), *(new String(*pValue))); + index++; + } + + pSqlListener->OnSqlDataControlInsertRequestReceived(reqId, *pProviderId, *pDataId, *pInsertMap); + + SysLog(NID_APP, "[DC_PROVIDER] caller appId: %ls, requestType: %d, reqId: %ls, providerId: %ls, dataId: %ls, pInsertMap: 0x%x", + pAppId->GetPointer(), requestType, pReqId->GetPointer(), pProviderId->GetPointer(), + pDataId->GetPointer(), pInsertMap); + break; + case _DATACONTROL_REQUEST_TYPE_SQL_UPDATE: + SysLog(NID_APP, "[DC_PROVIDER] SqlDataControl UPDATE"); + + // list(1): updated column count + pColumnCount = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_COLUMNCOUNT)); + SysTryCatch(NID_APP, pColumnCount, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + Integer::Parse(*pColumnCount, columnCount); + SysLog(NID_APP, "[DC_PROVIDER] updated column count: %d", columnCount); + + pUpdateMap = new (std::nothrow) HashMap(); + SysTryReturnVoidResult(NID_APP, pUpdateMap, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory."); + pUpdateMap->Construct(); + + i = 0; + index = 0; + while (i < columnCount * 2) // list(2): column-value pairs + { + pColumn = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_UPDATEMAP + i++)); + SysTryCatch(NID_APP, pColumn != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + SysLog(NID_APP, "[DC_PROVIDER] column[%d]: %ls", index, pColumn->GetPointer()); + + pValue = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_UPDATEMAP + i++)); + SysTryCatch(NID_APP, pValue != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + SysLog(NID_APP, "[DC_PROVIDER] value[%d]: %ls", index, pValue->GetPointer()); + + pUpdateMap->Add(*(new String(*pColumn)), *(new String(*pValue))); + index++; + } + + // list(3): where clause + pWhere = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_UPDATEMAP + i)); + SysTryCatch(NID_APP, pWhere, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + if (pWhere->Equals(empty) == true) + { + pWhere = null; + } + else + { + SysLog(NID_APP, "[DC_PROVIDER] pWhere: %ls", pWhere->GetPointer()); + } + + pSqlListener->OnSqlDataControlUpdateRequestReceived(reqId, *pProviderId, *pDataId, *pUpdateMap, pWhere); + + SysLog(NID_APP, "[DC_PROVIDER] caller appId: %ls, requestType: %d, reqId: %ls, providerId: %ls, dataId: %ls, pUpdateMap: 0x%x, pWhere: 0x%x", + pAppId->GetPointer(), requestType, pReqId->GetPointer(), pProviderId->GetPointer(), + pDataId->GetPointer(), pUpdateMap, pWhere); + break; + case _DATACONTROL_REQUEST_TYPE_SQL_DELETE: + SysLog(NID_APP, "[DC_PROVIDER] SqlDataControl DELETE"); + + // list(1): where clause + pWhere = dynamic_cast< String* >(pList->GetAt(_DATACONTROL_PACKET_INDEX_DELETEWHERE)); + SysTryCatch(NID_APP, pWhere, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + if (pWhere->Equals(empty) == true) + { + pWhere = null; + } + else + { + SysLog(NID_APP, "[DC_PROVIDER] pWhere: %ls", pWhere->GetPointer()); + } + + pSqlListener->OnSqlDataControlDeleteRequestReceived(reqId, *pProviderId, *pDataId, pWhere); + + SysLog(NID_APP, "[DC_PROVIDER] caller appId: %ls, requestType: %d, reqId: %ls, providerId: %ls, dataId: %ls, pWhere: 0x%x", + pAppId->GetPointer(), requestType, pReqId->GetPointer(), pProviderId->GetPointer(), + pDataId->GetPointer(), pWhere); + break; + case _DATACONTROL_REQUEST_TYPE_MAP_QUERY: + pNo = dynamic_cast (pList->GetAt(6)); // list[2] + SysTryCatch(NID_APP, pNo, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + Integer::Parse(*pNo, pageNo); + + pCount = dynamic_cast (pList->GetAt(7)); //list[3] + SysTryCatch(NID_APP, pCount, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + Integer::Parse(*pCount, countPerPage); + + pMapListener->OnMapDataControlGetValueRequestReceived(reqId, *pProviderId, *pDataId, *pKey); + break; + case _DATACONTROL_REQUEST_TYPE_MAP_INSERT: + pValue = dynamic_cast (pList->GetAt(6)); // list[2] + SysTryCatch(NID_APP, pValue, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + pMapListener->OnMapDataControlAddValueRequestReceived(reqId, *pProviderId, *pDataId, *pKey, *pValue); + break; + case _DATACONTROL_REQUEST_TYPE_MAP_UPDATE: + pOldValue = dynamic_cast (pList->GetAt(6)); // list[2] + SysTryCatch(NID_APP, pOldValue, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + pNewValue = dynamic_cast (pList->GetAt(7)); // list[3] + SysTryCatch(NID_APP, pNewValue, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + pMapListener->OnMapDataControlSetValueRequestReceived(reqId, *pProviderId, *pDataId, *pKey, *pOldValue, *pNewValue); + break; + case _DATACONTROL_REQUEST_TYPE_MAP_DELETE: + pValue = dynamic_cast (pList->GetAt(6)); // list[2] + SysTryCatch(NID_APP, pValue, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + + pMapListener->OnMapDataControlRemoveValueRequestReceived(reqId, *pProviderId, *pDataId, *pKey, *pValue); + break; + default: + SysTryCatch(NID_APP, false, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request"); + break; + } + + if (requestType >= _DATACONTROL_REQUEST_TYPE_MAP_QUERY && requestType <= _DATACONTROL_REQUEST_TYPE_MAP_DELETE) + { + SysLog(NID_APP, "caller appId: %ls, requestType: %d, reqId: %ls, providerId: %ls, dataId: %ls, key: %ls", + pAppId->GetPointer(), requestType, pReqId->GetPointer(), pProviderId->GetPointer(), + pDataId->GetPointer(), pKey->GetPointer()); + } + + if (pColumnList) + { + pColumnList->RemoveAll(true); + delete pColumnList; + } + + if (pInsertMap) + { + pInsertMap->RemoveAll(true); + delete pInsertMap; + } + + if (pUpdateMap) + { + pUpdateMap->RemoveAll(true); + delete pUpdateMap; + } + + return; + +CATCH: + if (r == E_SYSTEM) + { + pErrorMsg = new (std::nothrow) String("[E_SYSTEM] A system error has occurred."); + } + else if (r == E_OUT_OF_MEMORY) + { + pErrorMsg = new (std::nothrow) String("[E_OUT_OF_MEMORY] The memory was insufficient."); + } + SysTryReturnVoidResult(NID_APP, pErrorMsg, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory was insufficient."); + + res = DataControlProviderManager::GetInstance()->SendDataControlError(reqId, *pErrorMsg); + + if (pColumnList) + { + pColumnList->RemoveAll(true); + delete pColumnList; + } + + if (pInsertMap) + { + pInsertMap->RemoveAll(true); + delete pInsertMap; + } + + if (pUpdateMap) + { + pUpdateMap->RemoveAll(true); + delete pUpdateMap; + } + + delete pErrorMsg; + + return; +} + + +void +_AppImpl::OnConditionRequestReceived(const _AppArg& arg, RequestId reqId) +{ + if (__pAppLaunchConditionEventListener == null) + { + SysLog(NID_APP, "No App launch condition event listener"); + return; + } + + String condition = arg.GetValue(OSP_K_COND); + Object* pExtraData = null;//TODO: retrieve NFC extra data. + ArrayList* pList = arg.GetArgListN(); + + __pAppLaunchConditionEventListener->OnAppLaunchConditionMetN(condition, pExtraData, pList); +} + + +long +_AppImpl::GetWindowHandle(void) const +{ + SysTryReturn(NID_APP, __pIAppImpl != null, -1, E_INVALID_STATE, "[E_INVALID_STATE] Getting App instance failed."); + + return __pIAppImpl->OnWindowHandleRequest(); +} + + +void +_AppImpl::OnAppCheckpoint(void) +{ + if (__pCheckpointEventListener) + { + __pCheckpointEventListener->OnAppCheckpointing(*(AppRegistry::GetInstance())); + } +} + + +bool +_AppImpl::ConfirmAppService(void) +{ + int count = 0; + long interval = 100; + const String tmpFile = HEARBEAT_PATH; + + if (_AppInfo::GetApplicationId() == SERVICE_APPID) + { + return true; + } + + while (true) + { + if (File::IsFileExist(tmpFile)) + { + return true; + } + + if (count >= HEARTBEAT_WAIT_COUNT) + { + return false; + } + + SysLog(NID_APP, "Waiting for app service %dth time(%d msec).", count, interval); + count++; + Thread::Sleep(interval); + } + + return false; +} + +result +_AppImpl::SetListener(_AppEvent appEvent, IEventListener* pListener) +{ + switch (appEvent) + { + case AE_CHECKPOINT: + SysTryReturnResult(NID_APP, __pCheckpointEventListener == null, E_OBJ_ALREADY_EXIST, "Checkpoint listener is already set."); + + // fall through + case AE_CLEAR_LISTENER: + __pCheckpointEventListener = dynamic_cast (pListener); + break; + + default: + break; + } + + return E_SUCCESS; +} + + +result +_AppImpl::SetSqlDataControlProviderEventListener(ISqlDataControlProviderEventListener* pListener) +{ + __pSqlDataControlProviderEventListener = pListener; + int tmpAppHandlerType = _AppInfo::GetAppHandlerType(); + tmpAppHandlerType |= _APP_HANDLER_DATACONTROL; + _AppInfo::SetAppHandlerType(tmpAppHandlerType); + return E_SUCCESS; +} + + +result +_AppImpl::SetMapDataControlProviderEventListener(IMapDataControlProviderEventListener* pListener) +{ + __pMapDataControlProviderEventListener = pListener; + int tmpAppHandlerType = _AppInfo::GetAppHandlerType(); + tmpAppHandlerType |= _APP_HANDLER_DATACONTROL; + _AppInfo::SetAppHandlerType(tmpAppHandlerType); + return E_SUCCESS; +} + + +result +_AppImpl::SetAppControlProviderEventListener(IAppControlProviderEventListener* pListener) +{ + __pAppControlProviderEventListener = pListener; + int tmpAppHandlerType = _AppInfo::GetAppHandlerType(); + tmpAppHandlerType |= _APP_HANDLER_APPCONTROL; + _AppInfo::SetAppHandlerType(tmpAppHandlerType); + return E_SUCCESS; +} + +result +_AppImpl::SetAppControlProviderInternalEventListener(IAppControlProviderEventListener* pListener) +{ + __pAppControlProviderInternalEventListener = pListener; + int tmpAppHandlerType = _AppInfo::GetAppHandlerType(); + tmpAppHandlerType |= _APP_HANDLER_APPCONTROL; + _AppInfo::SetAppHandlerType(tmpAppHandlerType); + return E_SUCCESS; +} + + +result +_AppImpl::SetAppLaunchConditionEventListener(IAppLaunchConditionEventListener* pListener) +{ + __pAppLaunchConditionEventListener = pListener; + int tmpAppHandlerType = _AppInfo::GetAppHandlerType(); + tmpAppHandlerType |= _APP_HANDLER_LAUNCH_COND; + _AppInfo::SetAppHandlerType(tmpAppHandlerType); + + return E_SUCCESS; +} + + +bool +_AppImpl::IsTerminationRequested(void) +{ + return __isTerminationRequested; +} + +void +_AppImpl::OnPowerOffNotiReceived(void* user_data) +{ + SysLog(NID_APP, "Application is being terminated by power off."); + + app_efl_exit(); +} + +}} //Tizen::App + diff --git a/src/app/FApp_AppInfo.cpp b/src/app/FApp_AppInfo.cpp new file mode 100644 index 0000000..719f3e8 --- /dev/null +++ b/src/app/FApp_AppInfo.cpp @@ -0,0 +1,536 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppInfo.cpp + * @brief This is the implementation for the _AppInfo.cpp class. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "FAppPkg_PackageInfoImpl.h" +#include "FApp_AppInfo.h" +#include "FApp_Aul.h" +#include "FApp_AppArg.h" + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + +extern "C" +{ +void _OSP_EXPORT_ +InitAppInfo(const char* appId, const char* svcId, int argc, char* pArgv[], int fd) +{ + result r = Tizen::App::_AppInfo::GetAppInfo()->Construct(appId, svcId, argc, pArgv); + if (IsFailed(r)) + { + SysLogException(NID_APP, E_SYSTEM, "Application initialization failure for %s.", appId); + fprintf(stderr, "Application initialization failure for %s.\n", appId); + + _Process::Exit(-1); + } +} + +void _OSP_EXPORT_ +InitWebAppInfo(const char* appId, const char* rootPath) +{ + result r = Tizen::App::_AppInfo::GetAppInfo()->Construct(appId, rootPath, Tizen::App::_APP_TYPE_WEB_APP); + if (IsFailed(r)) + { + SysLogException(NID_APP, E_SYSTEM, "Application initialization failure for %s.", appId); + fprintf(stderr, "Application initialization failure for %s.\n", appId); + + _Process::Exit(-1); + } +} + +extern void FBase_Initialize(void); + +} + +namespace Tizen { namespace App +{ + +const int MAX_APIVERSION = 8; +const int MAX_APPID = 10; +const char APPINFO_FILE_PATH[] = "info/version.info"; +const char PACKAGE_PATH_FORMAT2[] = "/opt/apps/0000000000/"; +const char PATH_ROOT[] = "/opt/apps/"; +const char COMPAT_FILE_PATH[] = "info/compat.info"; + + +_AppInfo::_AppInfo(void) + : __appState(TERMINATED) + , __appType(_APP_TYPE_UI_APP) + , __appRootDirFd(-1) + , __appHandlerType(_APP_HANDLER_NONE) + , __parentWindowHandle(-1) + , __apiVersion(_API_VERSION_2_1) + , __pAppName(null) + , __pAppVersion(null) + , __argc(0) + , __pArgv(null) + , __isPackageInfoInitialized(false) + , __isOspCompat(false) + , __isSubMode(false) +{ + SysStaticAssert(sizeof(pid_t) == sizeof(int)); + + //FBase_Initialize(); +} + +_AppInfo::~_AppInfo(void) +{ + delete __pAppName; + delete __pAppVersion; +} + +_AppInfo* +_AppInfo::GetAppInfo(void) +{ + static _AppInfo info; + + return &info; +} + + +result +_AppInfo::Construct(const char* appId, const char* exeName, int argc, char* argv[]) +{ + SysAssertf(appId != null, "Valid appId required to launch application."); + + FBase_Initialize(); + + __appExecutableName = exeName; + __packageId = appId; + + if (__appExecutableName == L"_AppControl") + { + SysLog(NID_APP, "Handling for submode."); + const String& name = _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(__packageId); + + __isSubMode = true; + __appExecutableName = name; + SysLog(NID_APP, "Executable name is changed to %ls.", __appExecutableName.GetPointer()); + } + + __appId = __packageId + L'.' + __appExecutableName; + + result r = E_SUCCESS; + FILE* pFile = NULL; + + { + const int len = strlen(PACKAGE_PATH_FORMAT2); + char appInfoPath[len + 1]; + strncpy(appInfoPath, PACKAGE_PATH_FORMAT2, len); + appInfoPath[len] = '\0'; + + // due to possible dependency problem, FIoFile is not used + // app root path first + + strncpy(appInfoPath + strlen(PATH_ROOT), appId, MAX_APPID); + + // app root directory file descriptor + __appRootDirFd = open(appInfoPath, O_RDONLY | O_CLOEXEC | O_DIRECTORY); + + __appRootPath = appInfoPath; + + SysLog(NID_APP, "App root directory (%s:%d) open.", appInfoPath, __appRootDirFd); + + int fd = openat(__appRootDirFd, APPINFO_FILE_PATH, O_RDONLY); + SysAssert(fd != -1); + + pFile = fdopen(fd, "r"); + SysTryCatch(NID_APP, pFile != NULL, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Opening appinfo file (%s) failed : %s.", appInfoPath, strerror(errno)); + + char apiVersion[MAX_APIVERSION] = {0, }; + char* pRet = fgets(apiVersion, MAX_APIVERSION - 1, pFile); + SysTryCatch(NID_APP, pRet != NULL, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Reading appinfo file (%s) failed : %s.", appInfoPath, strerror(errno)); + + fclose(pFile); + // fd is closed when the stream is closed by fclose(); + + __apiVersion = GetApiVersionFromStr(apiVersion); + + __argc = argc; + __pArgv = argv; + + // to reduce package manager overhead, libc API is used + if (faccessat(__appRootDirFd, COMPAT_FILE_PATH, F_OK, 0) == 0) + { + SysLog(NID_APP, "OSP compatibility mode on."); + __isOspCompat = true; + } + + SysLog(NID_APP, "AppInfo initialization finished [%ls][%ls.%ls][%d].", + __appId.GetPointer(), __packageId.GetPointer(), __appExecutableName.GetPointer(), __apiVersion); + } + + return E_SUCCESS; + +CATCH: + __appId.Clear(); + __appExecutableName.Clear(); + + delete __pAppName; + __pAppName = null; + + delete __pAppVersion; + __pAppVersion = null; + + if (pFile != NULL) + { + fclose(pFile); + } + + return r; +} + + +// initialize app context only +result +_AppInfo::Construct(const char* appId, const char* appRoot, _AppType type) +{ + SysAssertf(appId != null, "Valid appId required to launch application."); + + FBase_Initialize(); + + __appId = appId; + + int index = 0; + if (__appId.LastIndexOf(L'.', __appId.GetLength() - 1, index) == E_SUCCESS) + { + __appId.SubString(index + 1, __appExecutableName); + __appId.SubString(0, index, __packageId); + } + else + { + __appExecutableName = __appId; + __packageId = __appId; + } + + __appRootDirFd = open(appRoot, O_RDONLY | O_CLOEXEC | O_DIRECTORY); + __apiVersion = _API_VERSION_2_1; + __appType = type; + + __appRootPath = appRoot; + if (__appRootPath[__appRootPath.GetLength()] != L'/') + { + __appRootPath.Append(L'/'); + } + + SysLog(NID_APP, "AppInfo initialization finished [%ls][%ls.%ls][%ls][%d].", __appId.GetPointer(), __packageId.GetPointer(), __appExecutableName.GetPointer(), __appRootPath.GetPointer(), __apiVersion); + + return E_SUCCESS; +} + + +result +_AppInfo::UpdateAppInfoFromPackageInfo(const PackageId& packageId) +{ + _PackageManagerImpl* pPkg = null; + pPkg = _PackageManagerImpl::GetInstance(); + SysTryReturnResult(NID_APP, pPkg != null, E_INVALID_STATE, "Invalid PackageManager instance."); + + result r = E_SUCCESS; + PackageInfo* pInfo = null; + pInfo = pPkg->GetPackageInfoN(packageId); + SysTryReturn(NID_APP, pInfo != null, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + const _PackageInfoImpl* pPkgInfo = _PackageInfoImpl::GetInstance(pInfo); + SysTryReturnResult(NID_APP, pPkgInfo != null, E_INVALID_STATE, "Invalid PackageInfo instance."); + + delete __pAppName; + __pAppName = new (std::nothrow) String(pPkgInfo->GetName()); + SysTryCatch(NID_APP, __pAppName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] AppName allocation failure."); + + delete __pAppVersion; + __pAppVersion = new (std::nothrow) String(pPkgInfo->GetVersion()); + SysTryCatch(NID_APP, __pAppVersion != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] AppVersion allocation failure."); + + __isPackageInfoInitialized = true; + + delete pInfo; + + SysLog(NID_APP, "AppInfo updated [%ls][%ls].", __pAppName->GetPointer(), __pAppVersion->GetPointer()); + + return r; + +CATCH: + delete pInfo; + + delete __pAppName; + __pAppName = null; + + delete __pAppVersion; + __pAppVersion = null; + + return r; +} + + +// [FIXME] refactoring to use hash +_ApiVersion +_AppInfo::GetApiVersionFromStr(const char* pVer) +{ + String ver(pVer); + ver.Trim(); + + if (ver == L"3.0") + { + return _API_VERSION_2_1; + } + else if (ver == L"2.0") + { + return _API_VERSION_2_0; + } + else if (ver == L"1.2") + { + return _API_VERSION_1_2; + } + else if (ver == L"1.1") + { + return _API_VERSION_1_1; + } + else if (ver == L"1.0.2") + { + return _API_VERSION_1_0_2; + } + else if (ver == L"1.0") + { + return _API_VERSION_1_0; + } + else + { + return _API_VERSION_2_1; + } +} + + +_ApiVersion +_AppInfo::GetApiVersion(void) +{ + return GetAppInfo()->__apiVersion; +} + + +bool +_AppInfo::IsOspCompat(void) +{ + return GetAppInfo()->__isOspCompat; +} + + +result +_AppInfo::SetApiVersion(_ApiVersion v) +{ + GetAppInfo()->__apiVersion = v; + return E_SUCCESS; +} + + +int +_AppInfo::GetProcessId(void) +{ + static int processId = static_cast(getpid()); + + return processId; +} + +int +_AppInfo::GetAppRootDirFd(void) +{ + return GetAppInfo()->__appRootDirFd; +} + + +const AppId& +_AppInfo::GetAppId(void) +{ + const String& packageId = GetAppInfo()->__packageId; + + SysAssertf(!packageId.IsEmpty(), "PackageId is not initialized properly."); + + return packageId; +} + + +const AppId& +_AppInfo::GetApplicationId(void) +{ + const String& appId = GetAppInfo()->__appId; + + SysAssertf(!appId.IsEmpty(), "AppId is not initialized properly."); + + return appId; +} + + +const PackageId& +_AppInfo::GetPackageId(void) +{ + const String& packageId = GetAppInfo()->__packageId; + + SysAssertf(!packageId.IsEmpty(), "PackageId is not initialized properly."); + + return packageId; +} + + +const String& +_AppInfo::GetAppExecutableName(void) +{ + return GetAppInfo()->__appExecutableName; +} + + +bool +_AppInfo::IsSubMode(void) +{ + return GetAppInfo()->__isSubMode; +} + + +String +_AppInfo::GetAppName(void) +{ + if (!GetAppInfo()->__isPackageInfoInitialized) + { + const String& packageId = GetAppInfo()->__packageId; + + SysAssertf(!packageId.IsEmpty(), "PackageId is not initialized properly."); + + result r = GetAppInfo()->UpdateAppInfoFromPackageInfo(packageId); + SysAssertf(r == E_SUCCESS, "AppInfo update failure due to package problem."); + } + + return *(GetAppInfo()->__pAppName); +} + + +String +_AppInfo::GetAppRootPath(void) +{ + return GetAppInfo()->__appRootPath; +} + +String +_AppInfo::GetAppVersion(void) +{ + if (!GetAppInfo()->__isPackageInfoInitialized) + { + const String& packageId = GetAppInfo()->__packageId; + + SysAssertf(!packageId.IsEmpty(), "PackageId is not initialized properly."); + + result r = GetAppInfo()->UpdateAppInfoFromPackageInfo(packageId); + SysAssertf(r == E_SUCCESS, "AppInfo update failure due to package problem."); + } + + return *(GetAppInfo()->__pAppVersion); +} + + +AppState +_AppInfo::GetAppState(void) +{ + return GetAppInfo()->__appState; +} + + +void +_AppInfo::SetAppState(AppState appState) +{ + GetAppInfo()->__appState = appState; +} + + +_AppType +_AppInfo::GetAppType(void) +{ + return GetAppInfo()->__appType; +} + + +void +_AppInfo::SetAppType(_AppType appType) +{ + GetAppInfo()->__appType = appType; +} + + +int +_AppInfo::GetArgc(void) +{ + return GetAppInfo()->__argc; +} + + +char** +_AppInfo::GetArgv(void) +{ + return GetAppInfo()->__pArgv; +} + + +int +_AppInfo::GetAppHandlerType(void) +{ + return GetAppInfo()->__appHandlerType; +} + + +void +_AppInfo::SetAppHandlerType(int appHandlerType) +{ + GetAppInfo()->__appHandlerType = appHandlerType; +} + + +unsigned int +_AppInfo::GetParentWindowHandle(void) +{ + return GetAppInfo()->__parentWindowHandle; +} + + +void +_AppInfo::SetParentWindowHandle(unsigned int handle) +{ + GetAppInfo()->__parentWindowHandle = handle; +} + + +void +_AppInfo::UpdatePackageInfo(bool update) +{ + GetAppInfo()->__isPackageInfoInitialized = !update; +} + +}} // Tizen::App diff --git a/src/app/FApp_AppLaunchCondition.cpp b/src/app/FApp_AppLaunchCondition.cpp new file mode 100644 index 0000000..2fbfc60 --- /dev/null +++ b/src/app/FApp_AppLaunchCondition.cpp @@ -0,0 +1,118 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppLaunchCondition.cpp + * @brief This is the implementation for the _ConditionManagerStub class. + */ +#include +#include "FApp_AppLaunchCondition.h" + +namespace Tizen { namespace App { + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + + +_AppLaunchCondition::_AppLaunchCondition(void) +: __appId(L""), __executableName(L""), __pArguments(null), __option(AppManager::LAUNCH_OPTION_DEFAULT), __conditionString(L""), __pUserData(null), __regSectionName(L"") +{ +} + +_AppLaunchCondition::~_AppLaunchCondition(void) +{ + if (__pArguments != null) + { + __pArguments->RemoveAll(true); + delete __pArguments; + } +} + +result +_AppLaunchCondition::Construct(const AppId& appId, const String& executableName, const String& conditionString, const IList* pArgs, AppManager::LaunchOption option, const String* pRegSectionName) +{ + __appId = appId; + __executableName = executableName; + __option = option; + __conditionString = conditionString; + __pUserData = null; + __regSectionName = (pRegSectionName != null) ? *pRegSectionName : L""; + + return CopyArgumentsDeeply(pArgs); +} + +AppId +_AppLaunchCondition::GetAppId(void) const +{ + return __appId; +} + +String +_AppLaunchCondition::GetConditionString(void) const +{ + return __conditionString; +} + +Object* +_AppLaunchCondition::GetUserData(void) const +{ + return const_cast(__pUserData); +} + +String +_AppLaunchCondition::GetExecutableName(void) const +{ + return __executableName; +} + +result +_AppLaunchCondition::SetUserData(const Object* pUserData) +{ + __pUserData = pUserData; + return E_SUCCESS; +} + +result +_AppLaunchCondition::CopyArgumentsDeeply(const IList *pArgs) +{ + result r = E_SUCCESS; + + if (pArgs != null && pArgs->GetCount() > 0) + { + __pArguments = new (std::nothrow) ArrayList(); + SysTryReturnResult(NID_APP, __pArguments != null, E_OUT_OF_MEMORY, "failed to allocate 'pArguments'!"); + + __pArguments->Construct(); + // deep copy + for (int i = 0; i < pArgs->GetCount() ; i++) + { + r = __pArguments->Add(* new (std::nothrow) String(* static_cast(pArgs->GetAt(i)))); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s]", GetErrorMessage(r)); + } + } + + return E_SUCCESS; + +CATCH: + __pArguments->RemoveAll(true); + delete __pArguments; + __pArguments = null; + return r; +} + + +}}//namespace Tizen { namespace App { diff --git a/src/app/FApp_AppLaunchConditionHandlerBase.cpp b/src/app/FApp_AppLaunchConditionHandlerBase.cpp new file mode 100644 index 0000000..787e509 --- /dev/null +++ b/src/app/FApp_AppLaunchConditionHandlerBase.cpp @@ -0,0 +1,52 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppLaunchConditionHandlerBase.cpp + * @brief This file contains _AppLaunchConditionHandlerBase class implementation. + */ + +#include "FApp_AppLaunchConditionHandlerBase.h" + +namespace Tizen { namespace App { + + +_AppLaunchConditionHandlerBase::_AppLaunchConditionHandlerBase(void) + :__pEventListener(null) +{ +} + +_AppLaunchConditionHandlerBase::~_AppLaunchConditionHandlerBase(void) +{ +} + +result +_AppLaunchConditionHandlerBase::SetEventListener(_IAppLaunchConditionEventListener& eventListener) +{ + __pEventListener = &eventListener; + return E_SUCCESS; +} + +result +_AppLaunchConditionHandlerBase::Fire(const _AppLaunchCondition& operation) +{ + SysTryReturnResult(NID_APP, __pEventListener != null, E_INVALID_STATE, "__pEventListener shoule not be null!"); + __pEventListener->OnAppLaunchConditionMet(operation); + return E_SUCCESS; +} + +}}//namespace Tizen { namespace App { diff --git a/src/app/FApp_AppManagerEvent.cpp b/src/app/FApp_AppManagerEvent.cpp new file mode 100644 index 0000000..e1eceaa --- /dev/null +++ b/src/app/FApp_AppManagerEvent.cpp @@ -0,0 +1,130 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerEvent.cpp + * @brief This is the implementation for the _AppManagerEvent.cpp class. + */ + +#include + +#include "FApp_Types.h" +#include "FApp_AppManagerEvent.h" +#include "FApp_AppManagerEventArg.h" +#include "FApp_IAppManagerEventListener.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + + +namespace Tizen { namespace App +{ + +_AppManagerEventArg::_AppManagerEventArg(void) + : __appType(_APP_TYPE_UI_APP) + , __eventType(_AppManagerEvent::_APP_MANAGER_EVENT_INVALID) +{ +} + +_AppManagerEventArg::_AppManagerEventArg(const AppId& appId, _AppType appType, _AppManagerEvent::_Type eventType) + : __appId(appId) + , __appType(appType) + , __eventType(eventType) +{ +} + +_AppManagerEventArg::_AppManagerEventArg(const _AppManagerEventArg& value) +{ +// *this = value; + __appId = value.__appId; + __appType = value.__appType; + __eventType = value.__eventType; +} + +_AppManagerEventArg::~_AppManagerEventArg(void) +{ +} + +const AppId +_AppManagerEventArg::GetAppId(void) const +{ + return __appId; +} + +_AppType +_AppManagerEventArg::GetAppType(void) const +{ + return __appType; +} + +_AppManagerEvent::_Type +_AppManagerEventArg::GetEventType(void) const +{ + return __eventType; +} + +_AppManagerEventArg& +_AppManagerEventArg::operator =(const _AppManagerEventArg& source) +{ + if (&source == this) + { + return *this; + } + + __appId = source.__appId; + __appType = source.__appType; + __eventType = source.__eventType; + + return *this; +} + + +/////////////////////////////////////////////////////// +//_AppManagerEvent +/////////////////////////////////////////////////////// +result +_AppManagerEvent::Construct(void) +{ + return _Event::Initialize(); +} + +void +_AppManagerEvent::FireImpl(IEventListener& listener, const IEventArg& arg) +{ + _IAppManagerEventListener* pListener = dynamic_cast<_IAppManagerEventListener*>(&listener); + SysTryReturnVoidResult(NID_APP, pListener != null, E_INVALID_STATE, "Invalid listener : listener(0x%x), arg(0x%x)", &listener, &arg); + + const _AppManagerEventArg* pEventArg = dynamic_cast(&arg); + SysTryReturnVoidResult(NID_APP, pEventArg != null, E_INVALID_STATE, "Invalid arg : listener(0x%x), arg(0x%x)", &listener, &arg); + + switch (pEventArg->GetEventType()) + { + case _APP_MANAGER_EVENT_LAUNCHED: + pListener->OnApplicationLaunched(pEventArg->GetAppId(), pEventArg->GetAppType()); + break; + + case _APP_MANAGER_EVENT_TERMINATED: + pListener->OnApplicationTerminated(pEventArg->GetAppId(), pEventArg->GetAppType()); + break; + + default: + SysLog(NID_APP, "Invalid event type(%d)!!", pEventArg->GetEventType()); + break; + } +} + +} } // Tizen::App diff --git a/src/app/FApp_AppManagerImpl.cpp b/src/app/FApp_AppManagerImpl.cpp new file mode 100755 index 0000000..b13b58d --- /dev/null +++ b/src/app/FApp_AppManagerImpl.cpp @@ -0,0 +1,1090 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerImpl.cpp + * @brief This is the implementation for the _AppManagerImpl class. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "FApp_AppControlRegistry.h" +#include "FApp_AppImpl.h" +#include "FApp_AppInfo.h" +#include "FApp_AppManagerEventArg.h" +#include "FApp_AppManagerImpl.h" +#include "FApp_AppManagerProxy.h" +#include "FApp_AppMessageImpl.h" +#include "FApp_AppControlImpl.h" +#include "FApp_ConditionManagerProxy.h" +#include "FApp_IAppManagerEventListener.h" +#include "FApp_MapDataControlImpl.h" +#include "FApp_SqlDataControlImpl.h" +#include "FAppPkg_PackageManagerImpl.h" +#include "FAppPkg_PackageInfoImpl.h" +#include "FApp_AppControlManager.h" +#include "FApp_Aul.h" + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Utility; +using namespace Tizen::Io; + +//extern const char* _DATACONTROL_RESULTSET_DIR; + +namespace +{ + +//const long MAX_APPCONTROL_ARGUMENT = 4096; +const long MAX_APPCONTROL_ARGUMENT = 1024; +const long MAX_CONDITION_LENGTH = 400; + +// ActiveWindow related function and variable from shared library. +// libecore_x.so.1 +static Ecore_X_Atom(* p_ecore_x_atom_get)(const char* name) = null; +static int(* p_ecore_x_window_prop_window_get)(Ecore_X_Window win, Ecore_X_Atom atom, Ecore_X_Window* val, unsigned int len) = null; +static Eina_Bool(* p_ecore_x_netwm_pid_get)(Ecore_X_Window win, int* pid) = null; +static int(* p_ecore_x_netwm_name_get)(Ecore_X_Window win, char** name) = null; +static Ecore_X_Window* (* p_ecore_x_window_root_list)(int* num_ret) = null; +static int* p_ECORE_X_EVENT_WINDOW_PROPERTY = null; +// libecore.so.1 +static Ecore_Event_Handler* (* p_ecore_event_handler_add)(int type, Ecore_Event_Handler_Cb func, const void* data) = null; +static void* (* p_ecore_event_handler_del)(Ecore_Event_Handler* event_handler) = null; +// libX11.so +static int (* p_XSelectInput)(Display* display, Window w, long event_mask) = null; +static Display* (* p_XOpenDisplay)(_Xconst char* display_name) = null; + +Ecore_Event_Handler* pWindowPropertyChanged = null; + + +int +GetTotalSize(const Tizen::Base::Collection::ICollection& col) +{ + int size = 0; + std::unique_ptr pEnum(col.GetEnumeratorN()); + + if (pEnum) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + String* pStr = static_cast(pEnum->GetCurrent()); + if (pStr == null) + { + continue; + } + size += pStr->GetLength(); + } + } + + return size; +} + +Eina_Bool +OnPropertyChanged(void* pData, int type, void* pEvent) +{ + using namespace Tizen::App; + + if (p_ecore_x_atom_get == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_atom_get = reinterpret_cast(lib.GetProcAddress(L"ecore_x_atom_get")); + SysTryReturnResult(NID_APP, p_ecore_x_atom_get != null, EINA_FALSE, + "A system error has been occurred. Failed to get ecore_x_atom_get."); + } + if (p_ecore_x_window_prop_window_get == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_window_prop_window_get = reinterpret_cast(lib.GetProcAddress(L"ecore_x_window_prop_window_get")); + SysTryReturnResult(NID_APP, p_ecore_x_window_prop_window_get != null, EINA_FALSE, + "A system error has been occurred. Failed to get ecore_x_window_prop_window_get."); + } + if (p_ecore_x_netwm_pid_get == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_netwm_pid_get = reinterpret_cast(lib.GetProcAddress(L"ecore_x_netwm_pid_get")); + SysTryReturnResult(NID_APP, p_ecore_x_netwm_pid_get != null, EINA_FALSE, + "A system error has been occurred. Failed to get ecore_x_netwm_pid_get."); + } + if (p_ecore_x_netwm_name_get == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_netwm_name_get = reinterpret_cast(lib.GetProcAddress(L"ecore_x_netwm_name_get")); + SysTryReturnResult(NID_APP, p_ecore_x_netwm_name_get != null, EINA_FALSE, + "A system error has been occurred. Failed to get ecore_x_netwm_name_get."); + } + + if (!pData) + { + SysLog(NID_UI, "The data is not valid."); + return EINA_FALSE; + } + if (!pEvent) + { + SysLog(NID_UI, "The event is not valid."); + return EINA_FALSE; + } + + Ecore_X_Event_Window_Property* pE = (Ecore_X_Event_Window_Property*) pEvent; + Ecore_X_Atom atom = pE->atom; + Ecore_X_Atom activeAtom = p_ecore_x_atom_get("_NET_ACTIVE_WINDOW"); + + if (atom != activeAtom) + { + return ECORE_CALLBACK_PASS_ON; + } + + Ecore_X_Window win = pE->win; + Ecore_X_Window activeWin = 0; + p_ecore_x_window_prop_window_get(win, activeAtom, &activeWin, 1); + + int pid = 0; + p_ecore_x_netwm_pid_get(activeWin, &pid); + + char* pAppName = null; + p_ecore_x_netwm_name_get(activeWin, &pAppName); + + Tizen::App::_AppManagerImpl* pAppManagerImpl = static_cast(pData); + pAppManagerImpl->FireActiveAppEvent(activeWin, pid, pAppName); + + if (pAppName) + { + free(pAppName); + } + + return ECORE_CALLBACK_PASS_ON; +} + +} // anonymous name-space + + +namespace Tizen { namespace App +{ + +const wchar_t LEGACY_LAUNCH_REASON_NORMAL[] = L"LAUNCH_NORMAL"; +const wchar_t LEGACY_LAUNCH_REASON_CONDITIONAL[] = L"LAUNCH_CONDITIONAL"; +const wchar_t OSP_UI_SONAME[] = L"libosp-uifw.so.1"; +const wchar_t OSP_ECORE_X_SONAME[] = L"libecore_x.so.1"; +const wchar_t OSP_ECORE_SONAME[] = L"libecore.so.1"; +const wchar_t OSP_X11_SONAME[] = L"libX11.so.6"; +const int _MAX_PACKAGE_ID_LENGTH = 10; + +_LibraryImpl* _AppManagerImpl::__pEcoreLibrary = null; +_LibraryImpl* _AppManagerImpl::__pEcoreXLibrary = null; + +_AppManagerImpl::_AppManagerImpl(void) + : __pConditionManager(null) + , __eventListenerCount(0) + , __pUiLibrary(null) + , __pX11Library(null) +{ + SysLog(NID_APP, ""); +} + +_AppManagerImpl::~_AppManagerImpl(void) +{ + SysLog(NID_APP, ""); + + if (__activeAppEventListenerList.GetCount() > 0) + { + if (p_ecore_event_handler_del == null) + { + _LibraryImpl& lib = GetEcoreLibraryImpl(); + p_ecore_event_handler_del = reinterpret_cast(lib.GetProcAddress(L"ecore_event_handler_del")); + } + if (p_ecore_event_handler_del) + { + if (pWindowPropertyChanged) + { + p_ecore_event_handler_del(pWindowPropertyChanged); + pWindowPropertyChanged = null; + } + } + } + + delete __pConditionManager; + delete __pUiLibrary; + delete __pX11Library; + delete __pEcoreXLibrary; + __pEcoreXLibrary = null; + delete __pEcoreLibrary; + __pEcoreLibrary = null; +} + + +result +_AppManagerImpl::Construct(void) +{ + __appManagerEvent.Construct(); + + _IAppManager* pMgr = _AppManagerProxy::GetService(); + //todo : uncomment following _SysTryReturn or put assert. + //SysTryReturn(NID_APP, pMgr != null, GetLastResult(), GetLastResult(), "[%s]GetService failed. Please check 'ps -A | grep OspAppService'!", GetLastResult()); + SysTryReturn(NID_APP, pMgr != null, E_SUCCESS, E_SUCCESS, "[E_SYSTEM] fatal error. Please check 'ps -A | grep osp-app-service'!", GetLastResult()); + pMgr->InitEventListener(this); + + return E_SUCCESS; +} + +_AppManagerImpl* +_AppManagerImpl::GetInstance(void) +{ + return AppManager::GetInstance()->__pAppManagerImpl; +} + +_ConditionManagerProxy* +_AppManagerImpl::GetConditionManagerProxy(void) +{ + if (__pConditionManager == null) + { + __pConditionManager = new (std::nothrow) _ConditionManagerProxy; + SysAssert(__pConditionManager != null); + + result r = __pConditionManager->Construct(); + SysAssertf(r == E_SUCCESS, "__pConditionManager->Construct() faliied [%s].", GetErrorMessage(r)); + } + + return __pConditionManager; +} + +AppControl* +_AppManagerImpl::FindAppControlN(const AppId& aId, const String& oId) +{ + _AppControlRegistry* pRegs = _AppControlRegistry::GetInstance(); + + AppControl* pAc = null; + + pAc = pRegs->GetNativeAppControlN(aId, oId); + if (pAc != null) + { + SetLastResult(E_SUCCESS); + return pAc; + } + + pAc = pRegs->GetAliasAppControlN(aId, oId); + if (pAc != null) + { + SetLastResult(E_SUCCESS); + return pAc; + } + + pAc = pRegs->GetAppControlN(aId, oId); + + SysTryReturn(NID_APP, pAc != null, null, E_OBJ_NOT_FOUND, "[%s] No matching AppControl instance found (%ls, %ls).", + GetErrorMessage(E_OBJ_NOT_FOUND), aId.GetPointer(), oId.GetPointer()); + SetLastResult(E_SUCCESS); + return pAc; +} + +IList* +_AppManagerImpl::FindAppControlsN(const String* pOperationId, const String* pCategory, const String* pDataType, + const String* pUriScheme) +{ + SysTryReturn(NID_APP, !(pOperationId == null && pCategory == null && pUriScheme == null && pDataType == null), null, + E_INVALID_ARG, "[%s] At least one parameter should not be null.", GetErrorMessage(E_INVALID_ARG)); + + String mimeType; + const String* pMimeType = pDataType; + + if (pDataType) + { + if ((*pDataType)[0] == L'.') + { + SysLog(NID_APP, "Extension to MIME conversion for %ls", pDataType->GetPointer()); + + String ext; + pDataType->SubString(1, ext); + + result r = _AppControlManager::GetMimeFromExt(ext, mimeType); + + SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] MIME type conversion failure for %ls.", GetErrorMessage(r), ext.GetPointer()); + + pMimeType = &mimeType; + + SysLog(NID_APP, "Conversion : %ls -> %ls.", pDataType->GetPointer(), pMimeType->GetPointer()); + } + } + + if (pUriScheme) + { + SysTryReturn(NID_APP, !(pUriScheme->IsEmpty()), null, E_INVALID_FORMAT, "[%s] The specified URI scheme is invalid.", + GetErrorMessage(E_INVALID_FORMAT)); + } + + ArrayList* pRetArg = null; + pRetArg = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pRetArg != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + pRetArg->Construct(); + + _AppControlRegistry* pRegs = _AppControlRegistry::GetInstance(); + + pRetArg = pRegs->FindAppControlListN(pOperationId, pUriScheme, pMimeType, pCategory); + + if ((pRetArg == null) || (pRetArg->GetCount() == 0)) + { + delete pRetArg; + pRetArg = null; + SetLastResult(E_OBJ_NOT_FOUND); + return null; + } + + SetLastResult(E_SUCCESS); + SysLog(NID_APP, "Found %d matching AppControls.", pRetArg->GetCount()); + + return pRetArg; +} + + +result +_AppManagerImpl::StartAppControl(const String& uri, const String* pOperationId, const String* pDataType, + IAppControlListener* pListener) +{ + return StartAppControl(pOperationId, null, pDataType, &uri, null, pListener); +} + + +result +_AppManagerImpl::StartAppControl(const String* pOperationId, const String* pCategory, const String* pDataType, + const String* pUri, const IList* pDataList, IAppControlListener* pListener) +{ + SysTryReturnResult(NID_APP, !(pOperationId == null && pUri == null && pCategory == null && pDataType == null), E_INVALID_ARG, + "At least one of the specified argument must not be null."); + if (pDataList != null) + { + int argSize = 0; + argSize = GetTotalSize(*pDataList); + + SysLog(NID_APP, "Argument count = %d, size = %d", pDataList->GetCount(), argSize); + + SysTryReturnResult(NID_APP, argSize <= MAX_APPCONTROL_ARGUMENT, E_MAX_EXCEEDED, + "The size of pDataList exceeded the limit(%d).", + MAX_APPCONTROL_ARGUMENT); + } + + String operation = (pOperationId) ? *pOperationId : TIZEN_OPERATION_MAIN; + + std::unique_ptr pBundle(bundle_create()); + SysTryReturnResult(NID_APP, pBundle.get(), E_OUT_OF_MEMORY, "Bundle creation failure."); + + _AppMessageImpl::SetOperation(pBundle.get(), operation); + + if (pUri) + { + _AppMessageImpl::SetUri(pBundle.get(), *pUri); + } + + if (pDataType) + { + String mimeType = *pDataType; + + if ((*pDataType)[0] == L'.') + { + SysLog(NID_APP, "Extension to MIME conversion for %ls", pDataType->GetPointer()); + +#if 0 + String ext; + pDataType->SubString(1, ext); + + result r = _AppControlManager::GetMimeFromExt(ext, mimeType); + + SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] MIME type conversion failure for %ls.", GetErrorMessage(r), ext.GetPointer()); + + pMimeType = &mimeType; + + SysLog(NID_APP, "Conversion : %ls -> %ls.", pDataType->GetPointer(), pMimeType->GetPointer()); +#endif + } + + _AppMessageImpl::SetMime(pBundle.get(), mimeType); + } + + if (pCategory) + { + _AppMessageImpl::SetCategory(pBundle.get(), *pCategory); + } + + return _AppControlImpl::StartImplicit(pBundle.get(), pDataList, pListener); +} + + +SqlDataControl* +_AppManagerImpl::GetSqlDataControlN(const String& providerId) +{ + SqlDataControl* pDc = null; + String type(L"Sql"); + String* pAppId = null; + String* pAccess = null; + String appId; + + // XXX: Need _NativeDataControlRegistry for SLP native app ? + // Try to searach SLP data control. +// _NativeDataControlRegistry* pReg = _NativeDataControlRegistry::GetInstance(); // singleton +// pDc = pReg->GetNativeSqlDataControlN(providerId); +// if (pDc != null) +// { +// return pDc; +// } + + std::unique_ptr pList(_PackageManagerImpl::GetInstance()->GetDataControlInfoN(providerId, type)); + SysTryReturn(NID_APP, pList != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The data control provider does not exist."); + + pAppId = dynamic_cast< String* >(pList->GetAt(0)); + SysTryReturn(NID_APP, pAppId != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error."); + pAccess = dynamic_cast< String* >(pList->GetAt(1)); + SysTryReturn(NID_APP, pAccess != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error."); + pAccess->ToLower(); + + if (pAppId->StartsWith(L"org.tizen.", 0)) + { + std::unique_ptr pStrTok(new (std::nothrow) StringTokenizer(*pAppId, L'.')); + SysTryReturn(NID_APP, pStrTok != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + for (int i = 0; i < 3; ++i) + { + pStrTok->GetNextToken(appId); + } + + appId[_MAX_PACKAGE_ID_LENGTH] = L'.'; + } + else + { + appId.Append(*pAppId); + } + + pDc = _SqlDataControlImpl::CreateSqlDataControl(appId, providerId, *pAccess); + SysTryReturn(NID_APP, pDc != null, null, GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult())); + + return pDc; +} + +MapDataControl* +_AppManagerImpl::GetMapDataControlN(const String& providerId) +{ + MapDataControl* pDc = null; + String type(L"Map"); + String* pAppId = null; + String* pAccess = null; + String appId; + + // XXX: Need _NativeDataControlRegistry for SLP native app ? + // Try to searach SLP data control. +// _NativeDataControlRegistry* pReg = _NativeDataControlRegistry::GetInstance(); // singleton +// pDc = pReg->GetNativeMapDataControlN(providerId); +// if (pDc != null) +// { +// return pDc; +// } + + std::unique_ptr pList(_PackageManagerImpl::GetInstance()->GetDataControlInfoN(providerId, type)); + SysTryReturn(NID_APP, pList != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The data control provider does not exist."); + + pAppId = dynamic_cast< String* >(pList->GetAt(0)); + SysTryReturn(NID_APP, pAppId != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error."); + pAccess = dynamic_cast< String* >(pList->GetAt(1)); + SysTryReturn(NID_APP, pAccess != null, null, E_SYSTEM, "[E_SYSTEM] The method cannot proceed due to a severe system error."); + pAccess->ToLower(); + + if (pAppId->StartsWith(L"org.tizen.", 0)) + { + std::unique_ptr pStrTok( new (std::nothrow) StringTokenizer(*pAppId, L'.')); + SysTryReturn(NID_APP, pStrTok != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + for (int i = 0; i < 3; ++i) + { + pStrTok->GetNextToken(appId); + } + + appId[_MAX_PACKAGE_ID_LENGTH] = L'.'; + } + else + { + appId.Append(*pAppId); + } + + pDc = _MapDataControlImpl::CreateMapDataControl(appId, providerId, *pAccess); + SysTryReturn(NID_APP, pDc != null, null, GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult())); + + return pDc; +} + +result +_AppManagerImpl::GetAppRootPath(const AppId& appId, String& appRootPath) +{ + String pkgId = PackageManager::GetPackageIdByAppId(appId); + SysTryReturnResult(NID_APP, pkgId.IsEmpty() == false, E_APP_NOT_INSTALLED, + "The application is not installed. (appId: %ls)", appId.GetPointer()); + + _PackageManagerImpl* pPkgMgr = _PackageManagerImpl::GetInstance(); + SysTryReturnResult(NID_APP, pPkgMgr != null, E_SYSTEM, + "Failed to get _PackageManagerImpl instance."); + + std::unique_ptr< PackageInfo >pPkgInfo(pPkgMgr->GetPackageInfoN(pkgId)); + SysTryReturnResult(NID_APP, pPkgInfo != null, E_APP_NOT_INSTALLED, + "The application is not installed. (appId: %ls)", appId.GetPointer()); + + _PackageInfoImpl* pPkgInfoImpl = _PackageInfoImpl::GetInstance(pPkgInfo.get()); + SysTryReturnResult(NID_APP, pPkgInfoImpl != null, E_SYSTEM, + "Failed to get _PackageInfoImpl instance."); + + appRootPath = pPkgInfoImpl->GetAppRootPath(); + appRootPath.Append(L"/"); + + return E_SUCCESS; +} + +result +_AppManagerImpl::LaunchApplication(const String& appId, const IList* pArguments, AppManager::LaunchOption option) +{ + SysTryReturnResult(NID_APP, !appId.IsEmpty(), E_INVALID_ARG, "The appid is empty."); + SysTryReturnResult(NID_APP, _Aul::IsInstalled(appId) == true, E_OBJ_NOT_FOUND, + "The target application(%ls) is not installed.", appId.GetPointer()); +// SysTryReturnResult(NID_APP, +// appId.GetLength() <= WIDGET_APP_MAX_APPID_LENGTH, E_MAX_EXCEEDED, +// "The length of appid exceeded the limit(%d).", +// WIDGET_APP_MAX_APPID_LENGTH); + + AppControl* pAc = _AppControlRegistry::GetInstance()->GetAppControlN(appId, TIZEN_OPERATION_MAIN); + SysTryReturnResult(NID_APP, pAc != null, E_OBJ_NOT_FOUND, "The target application (%ls) is not found.", appId.GetPointer()); + + if (pArguments) + { + int argSize = 0; + argSize = GetTotalSize(*pArguments); + + SysLog(NID_APP, "Argument count = %d, size = %d", pArguments->GetCount(), argSize); + + SysTryReturnResult(NID_APP, argSize <= MAX_APPCONTROL_ARGUMENT, E_MAX_EXCEEDED, + "The size of pDataList exceeded the limit(%d).", + MAX_APPCONTROL_ARGUMENT); + } + + result r = pAc->Start(pArguments, null); + + SysLog(NID_APP, "[%s] Launching %ls finished.", GetErrorMessage(r), appId.GetPointer()); + return r; +} + + +result +_AppManagerImpl::LaunchApplication(const String& appId, AppManager::LaunchOption option) +{ + SysTryReturnResult(NID_APP, !appId.IsEmpty(), E_APP_NOT_INSTALLED, "The appid is empty."); + + std::unique_ptr pName(_StringConverter::CopyToCharArrayN(appId)); + + int ret = aul_open_app(pName.get()); + + if (ret > 0) + { + SysLog(NID_APP, "Launching %ls successful.", appId.GetPointer()); + return E_SUCCESS; + } + + // failure + SysTryReturnResult(NID_APP, _Aul::IsInstalled(appId) == true, E_APP_NOT_INSTALLED, + "The target application(%ls) is not installed.", appId.GetPointer()); + + result r = E_SYSTEM; + switch (ret) + { + case AUL_R_EINVAL: + r = E_APP_NOT_INSTALLED; + break; + case AUL_R_OK: + // r = E_SUCCESS; + // never reach here + break; + default: + break; + } + + SysLog(NID_APP, "[%s] Launching %ls failed.", GetErrorMessage(r), appId.GetPointer()); + return r; +} + + +result +_AppManagerImpl::TerminateApplication(const AppId& appId, const String* pExecutableName) +{ + result r = E_SUCCESS; + + _IAppManager* pMgr = _AppManagerProxy::GetService(); + if (pMgr) + { + const String& name = (pExecutableName) ? *pExecutableName : _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(appId); + r = pMgr->TerminateApplication(appId, name); + } + + return r; +} + + +static int +TerminateIterFnCb(const aul_app_info* pAppInfo, void* pData) +{ + const char* pStr = static_cast(pData); + + if (pStr && strncmp(pStr, pAppInfo->pkg_name, 10) == 0) + { + aul_terminate_pid(pAppInfo->pid); + SysLog(NID_APP, "%s(%d) is terminated.", pAppInfo->pkg_name, pAppInfo->pid); + } + return 0; +} + +result +_AppManagerImpl::TerminateApplications(const PackageId& packageId) +{ + result r = E_SUCCESS; + + std::unique_ptr pPackage(_StringConverter::CopyToCharArrayN(packageId)); + aul_app_get_running_app_info(TerminateIterFnCb, static_cast(pPackage.get())); + + SysLog(NID_APP, "%ls terminated.", packageId.GetPointer()); + return E_SUCCESS; +} + +bool +_AppManagerImpl::IsRunning(const AppId& appId, const String* pExecutableName) const +{ + bool b = false; + + _IAppManager* pMgr = _AppManagerProxy::GetService(); + if (pMgr) + { + const String& name = (pExecutableName) ? *pExecutableName : _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(appId); + b = pMgr->IsRunning(appId, name); + } + + return b; +} + +static int +AulAppInfoIterFnCb(const aul_app_info* pAppInfo, void* pData) +{ + ArrayList* pList = static_cast(pData); + if (pList && pAppInfo && pAppInfo->appid) + { + pList->Add(*new (std::nothrow) String(pAppInfo->appid)); + } + + return 0; +} + +IList* +_AppManagerImpl::GetRunningAppListN(void) const +{ + ArrayList* pRunningAppList = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pRunningAppList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + pRunningAppList->Construct(); + + int ret = aul_app_get_running_app_info(AulAppInfoIterFnCb, reinterpret_cast(pRunningAppList)); + SysTryLog(NID_APP, ret == AUL_R_OK, "Getting running list failed."); + + // according to the doxygen, GetRunningAppListN() does not return null pointer for no object + return pRunningAppList; +} + + +result +_AppManagerImpl::RegisterAppLaunch(const AppId& appId, const String& executableName, const String& condition, const IList* pArguments, + AppManager::LaunchOption option) +{ + _ConditionManagerProxy* pProxy = GetConditionManagerProxy(); + SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null."); + + return pProxy->RegisterAppLaunch(appId, executableName, condition, pArguments, option); +} + +result +_AppManagerImpl::UnregisterAppLaunch(const AppId& appId, const String& executableName, const String* pCondition) +{ + _ConditionManagerProxy* pProxy = GetConditionManagerProxy(); + SysTryReturnResult(NID_APP, null != pProxy, E_INVALID_STATE, "ConditionManager instance must not be null."); + + if (pCondition) + { + SysTryReturnResult(NID_APP, + !pCondition->IsEmpty() && pCondition->GetLength() < MAX_CONDITION_LENGTH, E_OBJ_NOT_FOUND, + "No such a condition."); + } + + return pProxy->UnregisterAppLaunch(appId, executableName, pCondition); +} + +bool +_AppManagerImpl::IsAppLaunchRegistered(const AppId& appId, const String &executableName, const String* pCondition) +{ + _ConditionManagerProxy* pProxy = GetConditionManagerProxy(); + SysTryReturn(NID_APP, null != pProxy, false, E_INVALID_STATE, "[%s] ConditionManager instance must not be null.", + GetErrorMessage(E_INVALID_STATE)); + + ClearLastResult(); + return pProxy->IsAppLaunchRegistered(appId, executableName, pCondition); +} + +result +_AppManagerImpl::SetEventListener(_AppEvent appEvent, Tizen::Base::Runtime::IEventListener* pListener) +{ + return _AppImpl::GetInstance()->SetListener(appEvent, pListener); +} + +result +_AppManagerImpl::OnServiceEventReceived(int clientId, const _AppManagerEventArg& arg) +{ + SysLog(NID_APP, "appId:%ls, appType:0x%x", arg.GetAppId().GetPointer(), arg.GetAppType()); + + _AppManagerEventArg* pArg = new (std::nothrow)_AppManagerEventArg(arg); + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + __appManagerEvent.FireAsync(*pArg); + return E_SUCCESS; +} + +result +_AppManagerImpl::OnTerminateApplicationRequested(int clientId) +{ + SysLog(NID_APP, ""); + + return E_SUCCESS; +} + +result +_AppManagerImpl::AddEventListener(_IAppManagerEventListener& listener) +{ + _IAppManager* pMgr = _AppManagerProxy::GetService(); + SysTryReturnResult(NID_APP, pMgr != null, E_INVALID_STATE, ""); + + result r = __appManagerEvent.AddListener(listener); + SysTryReturn(NID_APP, IsFailed(r) == false, r, r, "[%s]", GetErrorMessage(r)); + + __eventListenerCount++; + SysLog(NID_APP, "registered event listener(s) # %d", __eventListenerCount); + + if( __eventListenerCount > 1) + { + return E_SUCCESS; + } + + return pMgr->AddEventListener(-1); +} + +result +_AppManagerImpl::RemoveEventListener(_IAppManagerEventListener& listener) +{ + _IAppManager* pMgr = _AppManagerProxy::GetService(); + SysTryReturnResult(NID_APP, pMgr != null, E_INVALID_STATE, ""); + + result r = __appManagerEvent.RemoveListener(listener); + SysTryReturn(NID_APP, IsFailed(r) == false, r, r, "[%s]", GetErrorMessage(r)); + + __eventListenerCount--; + SysLog(NID_APP, "registered event listener(s) # %d", __eventListenerCount); + + if (__eventListenerCount == 0) + { + return pMgr->RemoveEventListener(-1); + } + + return E_SUCCESS; +} + +// input ("qik37po9ck.BasicApp") => output {"qik37po9ck", "BasicApp"} +result +_AppManagerImpl::ExtractValues(AppId inAppId, AppId& outAppId, String& outExecutableName) +{ + const int APP_ID_LEN = 10; + + if (inAppId.GetLength() > APP_ID_LEN) + { + result r = inAppId.SubString(APP_ID_LEN + 1, inAppId.GetLength() - (APP_ID_LEN + 1), outExecutableName); + SysTryReturnResult(NID_APP, !IsFailed(r), E_INVALID_ARG, "invalid AppId(%ls)", inAppId.GetPointer()); + + r = inAppId.SubString(0, APP_ID_LEN, outAppId); + SysTryReturnResult(NID_APP, !IsFailed(r), E_INVALID_ARG, "invalid AppId(%ls)", inAppId.GetPointer()); + + SysLog(NID_APP, "appId(%ls), executableName(%ls)", outAppId.GetPointer(), outExecutableName.GetPointer()); + return E_SUCCESS; + } + return E_SYSTEM; +} + +_LibraryImpl& +_AppManagerImpl::GetUiLibraryImpl(void) +{ + if (__pUiLibrary == null) + { + __pUiLibrary = new (std::nothrow) _LibraryImpl; + SysAssertf(__pUiLibrary != null, "_LibraryImpl allocation failure."); + + result r = __pUiLibrary->Construct(OSP_UI_SONAME); + SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r)); + } + + return *__pUiLibrary; +} + +_LibraryImpl& +_AppManagerImpl::GetEcoreXLibraryImpl(void) +{ + if (__pEcoreXLibrary == null) + { + __pEcoreXLibrary = new (std::nothrow) _LibraryImpl; + SysAssertf(__pEcoreXLibrary != null, "_LibraryImpl allocation failure."); + + result r = __pEcoreXLibrary->Construct(OSP_ECORE_X_SONAME); + SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r)); + } + return *__pEcoreXLibrary; +} + +_LibraryImpl& +_AppManagerImpl::GetEcoreLibraryImpl(void) +{ + if (__pEcoreLibrary == null) + { + __pEcoreLibrary = new (std::nothrow) _LibraryImpl; + SysAssertf(__pEcoreLibrary != null, "_LibraryImpl allocation failure."); + + result r = __pEcoreLibrary->Construct(OSP_ECORE_SONAME); + SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r)); + } + return *__pEcoreLibrary; +} + +_LibraryImpl& +_AppManagerImpl::GetX11LibraryImpl(void) +{ + if (__pX11Library == null) + { + __pX11Library = new (std::nothrow) _LibraryImpl; + SysAssertf(__pX11Library != null, "_LibraryImpl allocation failure."); + + result r = __pX11Library->Construct(OSP_X11_SONAME); + SysAssertf(r == E_SUCCESS, "Dynamic loading error : %s.", GetErrorMessage(r)); + } + return *__pX11Library; +} + +void +_AppManagerImpl::FireActiveAppEvent(unsigned int xid, int pid, char* pAppName) +{ + static int oldPid = 0; + if (oldPid != pid) + { + oldPid = pid; + std::unique_ptr > pEnum(__activeAppEventListenerList.GetEnumeratorN()); + if (pEnum.get()) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + Tizen::App::IActiveAppEventListener* pListener = null; + pEnum->GetCurrent(pListener); + if (pListener) + { + char pkgname[255] = {0, }; + aul_app_get_pkgname_bypid(pid, pkgname, 255); + // TODO: Translate it to package name --> AppId + pListener->OnActiveAppChanged(AppId(pkgname)); + } + } + } + } +} + +unsigned int +_AppManagerImpl::GetActiveWindow(void) +{ + if (p_ecore_x_window_root_list == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_window_root_list = reinterpret_cast(lib.GetProcAddress(L"ecore_x_window_root_list")); + SysTryReturnResult(NID_APP, p_ecore_x_window_root_list != null, 0, + "A system error has been occurred. Failed to get p_ecore_x_window_root_list."); + } + if (p_ecore_x_atom_get == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_atom_get = reinterpret_cast(lib.GetProcAddress(L"ecore_x_atom_get")); + SysTryReturnResult(NID_APP, p_ecore_x_atom_get != null, 0, + "A system error has been occurred. Failed to get ecore_x_atom_get."); + } + if (p_ecore_x_window_prop_window_get == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_window_prop_window_get = reinterpret_cast(lib.GetProcAddress(L"ecore_x_window_prop_window_get")); + SysTryReturnResult(NID_APP, p_ecore_x_window_prop_window_get != null, EINA_FALSE, + "A system error has been occurred. Failed to get ecore_x_window_prop_window_get."); + } + + Ecore_X_Window* pRoots = null; + int num = 0; + + pRoots = p_ecore_x_window_root_list(&num); + Ecore_X_Atom activeAtom = p_ecore_x_atom_get("_NET_ACTIVE_WINDOW"); + + Ecore_X_Window activeWin = 0; + p_ecore_x_window_prop_window_get(pRoots[0], activeAtom, &activeWin, 1); + + return activeWin; +} + +int +_AppManagerImpl::GetProcessId(unsigned int window) +{ + if (p_ecore_x_netwm_pid_get == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_netwm_pid_get = reinterpret_cast(lib.GetProcAddress(L"ecore_x_netwm_pid_get")); + SysTryReturnResult(NID_APP, p_ecore_x_netwm_pid_get != null, EINA_FALSE, + "A system error has been occurred. Failed to get ecore_x_netwm_pid_get."); + } + + int pid = 0; + p_ecore_x_netwm_pid_get(window, &pid); + + return pid; +} + +result +_AppManagerImpl::AddActiveAppEventListener(IActiveAppEventListener& listener) +{ + if (p_ecore_x_window_root_list == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ecore_x_window_root_list = reinterpret_cast(lib.GetProcAddress(L"ecore_x_window_root_list")); + SysTryReturnResult(NID_APP, p_ecore_x_window_root_list != null, EINA_FALSE, + "A system error has been occurred. Failed to get p_ecore_x_window_root_list."); + } + if (p_ECORE_X_EVENT_WINDOW_PROPERTY == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetEcoreXLibraryImpl(); + p_ECORE_X_EVENT_WINDOW_PROPERTY = reinterpret_cast(lib.GetProcAddress(L"ECORE_X_EVENT_WINDOW_PROPERTY")); + SysTryReturnResult(NID_APP, p_ECORE_X_EVENT_WINDOW_PROPERTY != null, EINA_FALSE, + "A system error has been occurred. Failed to get p_ECORE_X_EVENT_WINDOW_PROPERTY."); + } + if (p_XOpenDisplay == null) + { + _LibraryImpl& lib = GetX11LibraryImpl(); + p_XOpenDisplay = reinterpret_cast(lib.GetProcAddress(L"XOpenDisplay")); + SysTryReturnResult(NID_APP, p_XOpenDisplay != null, EINA_FALSE, + "A system error has been occurred. Failed to get p_XOpenDisplay."); + } + if (p_XSelectInput == null) + { + _LibraryImpl& lib = GetX11LibraryImpl(); + p_XSelectInput = reinterpret_cast(lib.GetProcAddress(L"XSelectInput")); + SysTryReturnResult(NID_APP, p_XSelectInput != null, EINA_FALSE, + "A system error has been occurred. Failed to get p_XSelectInput."); + } + if (p_ecore_event_handler_add == null) + { + _LibraryImpl& lib = GetEcoreLibraryImpl(); + p_ecore_event_handler_add = reinterpret_cast(lib.GetProcAddress(L"ecore_event_handler_add")); + SysTryReturnResult(NID_APP, p_ecore_event_handler_add != null, EINA_FALSE, + "A system error has been occurred. Failed to get p_ecore_event_handler_add."); + } + + bool alreadyExist = __activeAppEventListenerList.Contains(&listener); + SysTryReturnResult(NID_APP, !alreadyExist, E_OBJ_ALREADY_EXIST, "The event listener already exist."); + result r = __activeAppEventListenerList.Add(&listener); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + Ecore_X_Window* pRoots = null; + int num = 0; + pRoots = p_ecore_x_window_root_list(&num); + + for (int i = 0; i < num; i++) + { + Display* pDisplay = p_XOpenDisplay(NULL); + p_XSelectInput(pDisplay, pRoots[i], PropertyChangeMask); + } + + if (!pWindowPropertyChanged) + { + pWindowPropertyChanged = p_ecore_event_handler_add(*p_ECORE_X_EVENT_WINDOW_PROPERTY, OnPropertyChanged, (void*) this); + SysTryReturnResult(NID_APP, pWindowPropertyChanged, E_SYSTEM, "A system error has been occurred."); + } + + return r; +} + +result +_AppManagerImpl::RemoveActiveAppEventListener(IActiveAppEventListener& listener) +{ + if (p_ecore_event_handler_del == null) + { + _LibraryImpl& lib = GetEcoreLibraryImpl(); + p_ecore_event_handler_del = reinterpret_cast(lib.GetProcAddress(L"ecore_event_handler_del")); + SysTryReturnResult(NID_APP, p_ecore_event_handler_del != null, E_SYSTEM, + "A system error has been occurred. Failed to get p_ecore_event_handler_del."); + } + + result r = __activeAppEventListenerList.Remove(&listener); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + if (__activeAppEventListenerList.GetCount() == 0) + { + p_ecore_event_handler_del(pWindowPropertyChanged); + pWindowPropertyChanged = null; + } + + return r; +} + +result +_AppManagerImpl::GetActiveApp(AppId& appId) +{ + unsigned int windowId = GetActiveWindow(); + int processId = GetProcessId(windowId); + char pkgname[255] = {0, }; + aul_app_get_pkgname_bypid(processId, pkgname, 255); + // TODO: Translate it to package name --> AppId + appId = pkgname; + return E_SUCCESS; +} + +}} // Tizen::App diff --git a/src/app/FApp_AppManagerIpcMessage.cpp b/src/app/FApp_AppManagerIpcMessage.cpp new file mode 100644 index 0000000..e9a530a --- /dev/null +++ b/src/app/FApp_AppManagerIpcMessage.cpp @@ -0,0 +1,46 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerIpcMessage.cpp + * @brief This file contains IPC message class generated by macros. + */ + +#define IPC_MESSAGE_IMPL +#include "FApp_AppManagerIpcMessage.h" + +// Generate constructors. +#include "ipc/struct_constructor_macros.h" +#include "FApp_AppManagerIpcMessage.h" +// Generate destructors. + +#include "ipc/struct_destructor_macros.h" +#include "FApp_AppManagerIpcMessage.h" + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC +{ +#include "FApp_AppManagerIpcMessage.h" +} // namespace IPC + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC +{ +#include "FApp_AppManagerIpcMessage.h" +} // namespace IPC diff --git a/src/app/FApp_AppManagerProxy.cpp b/src/app/FApp_AppManagerProxy.cpp new file mode 100644 index 0000000..23d1249 --- /dev/null +++ b/src/app/FApp_AppManagerProxy.cpp @@ -0,0 +1,255 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerProxy.cpp + * @brief This is the implementation for the _AppManagerProxy class. + */ + +#include +#include + +#include + +#include +#include + +#include "FApp_Types.h" +#include "FApp_AppInfo.h" +#include "FApp_IAppManagerEventListener.h" +#include "FApp_IAppManagerServiceEventListener.h" +#include "FApp_AppManagerEventArg.h" +#include "FApp_AppManagerProxy.h" +#include "FApp_AppManagerIpcMessage.h" + +namespace +{ + +const char IPC_SERVER_NAME[] = "osp.app.ipcserver.appmanager"; +const int INVALID_CLIENT_ID = -1; +}; + + +namespace Tizen { namespace App +{ + +using namespace Tizen::Base; +using namespace Tizen::Io; +using namespace Tizen::Base::Runtime; + + +_IAppManager* _AppManagerProxy::__pSelf = null; +_IAppManagerServiceEventListener* _AppManagerProxy::__pServiceEventListener = null; + +_AppManagerProxy::_AppManagerProxy(void) + : __pIpcClient(null) +{ + SysLog(NID_APP, ""); +} + +_AppManagerProxy::~_AppManagerProxy(void) +{ + delete __pIpcClient; +} + + +result +_AppManagerProxy::Construct(void) +{ + __pIpcClient = new (std::nothrow) _IpcClient(); + SysTryReturnResult(NID_APP, __pIpcClient != null, E_OUT_OF_MEMORY, "_IpcClient creation failed."); + + result r = __pIpcClient->Construct(IPC_SERVER_NAME, this); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "_IpcClient constructing faliied [%s].", GetErrorMessage(r)); + + return E_SUCCESS; +} + +_IAppManager* +_AppManagerProxy::GetService(void) +{ + _AppManagerProxy* pProxy = null; + + if (__pSelf == null) + { + SysLog(NID_APP, "Create new instance"); + + pProxy = new (std::nothrow) _AppManagerProxy(); + SysTryReturn(NID_APP, pProxy != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] failed to create _AppManagerProxy"); + + result r = pProxy->Construct(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] pProxy->Construct() failure.", GetErrorMessage(r)); + + __pSelf = pProxy; + } + + return __pSelf; + +CATCH: + delete pProxy; + return null; +} + +void +_AppManagerProxy::SetService(_IAppManager* pAppManager) +{ + __pSelf = pAppManager; +} + + +result +_AppManagerProxy::LaunchApplication(const AppId& appId, const String& executableName, int req) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, ""); + + std::auto_ptr pMsg (new (std::nothrow) AppManager_LaunchApplication(appId, executableName, req)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "SendRequest is failed."); + + return E_SUCCESS; +} + +result +_AppManagerProxy::TerminateApplication(const AppId& appId, const String& executableName) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, ""); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) AppManager_TerminateApplication(appId, executableName, &response)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "SendRequest is failed."); + + return response; +} + +bool +_AppManagerProxy::IsRunning(const AppId& appId, const String& executableName) +{ + bool isRunning = false; + + std::auto_ptr pMsg (new (std::nothrow) AppManager_IsRunning(appId, executableName, &isRunning)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + SysTryReturn(NID_APP, !IsFailed(r), false, r, "SendRequest is failed."); + + return isRunning; +} +result +_AppManagerProxy::GetRunningAppList(Collection::ArrayList* pArray) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + + SysLog(NID_APP, ""); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) AppManager_GetRunningAppList(pArray, &response)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "SendRequest is failed."); + + return response; +} + +result +_AppManagerProxy::RegisterApplication(const AppId& appId, const String& executableName, _AppType appType, int pId) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, ""); + + std::auto_ptr pMsg (new (std::nothrow) AppManager_RegisterApplication(appId, executableName, static_cast(appType), pId)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "SendRequest is failed."); + + return E_SUCCESS; +} + +result +_AppManagerProxy::UnregisterApplication(int pId) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + + SysLog(NID_APP, ""); + + std::auto_ptr pMsg (new (std::nothrow) AppManager_UnregisterApplication(pId)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "SendRequest is failed."); + + return E_SUCCESS; +} + +void +_AppManagerProxy::OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message) +{ + IPC_BEGIN_MESSAGE_MAP(_AppManagerProxy, message) + IPC_MESSAGE_HANDLER_EX(AppManager_OnEventReceived, &client, OnEventReceived ) + IPC_MESSAGE_HANDLER_EX(AppManager_OnTerminateApplicationRequested, &client, OnTerminateApplicationRequested ) + IPC_END_MESSAGE_MAP() +} + +bool +_AppManagerProxy::OnEventReceived(const _AppManagerEventArg& arg) +{ + SysTryReturnResult(NID_APP, __pServiceEventListener != null, E_INVALID_STATE, "__pServiceEventListener instance must not be null."); + + __pServiceEventListener->OnServiceEventReceived(-1, arg); + + return true; +} + +void +_AppManagerProxy::OnTerminateApplicationRequested(void) +{ + SysTryReturnVoidResult(NID_APP, __pServiceEventListener != null, E_INVALID_STATE, "[E_INVALID_STATE] __pServiceEventListener instance must not be null."); + + __pServiceEventListener->OnTerminateApplicationRequested(-1); +} + +result +_AppManagerProxy::InitEventListener(_IAppManagerServiceEventListener* pListener) +{ + __pServiceEventListener = pListener; + return E_SUCCESS; +} + +result +_AppManagerProxy::AddEventListener(int clientId) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, ""); + + std::auto_ptr pMsg(new (std::nothrow) AppManager_AddEventListener(_AppInfo::GetProcessId())); + result r = __pIpcClient->SendRequest(*pMsg); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "SendRequest is failed."); + + return E_SUCCESS; +} + +result +_AppManagerProxy::RemoveEventListener(int clientId) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, ""); + + std::auto_ptr pMsg (new (std::nothrow) AppManager_RemoveEventListener(_AppInfo::GetProcessId())); + result r = __pIpcClient->SendRequest(*pMsg); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "SendRequest is failed."); + + return E_SUCCESS; +} + + +} } // Tizen::App diff --git a/src/app/FApp_AppMessageImpl.cpp b/src/app/FApp_AppMessageImpl.cpp new file mode 100644 index 0000000..33b5d81 --- /dev/null +++ b/src/app/FApp_AppMessageImpl.cpp @@ -0,0 +1,280 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppMessageImpl.cpp + * @brief This is the implementation for the _AppMessageImpl.cpp class. + */ + +#include +#include + +#include + +#include +#include +#include +#include + +#include + +#include "FApp_AppMessageImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +_AppMessageImpl::_AppMessageImpl(void) +: __pBundle(bundle_create()) +{ + SysAssert(__pBundle != NULL); +} + +_AppMessageImpl::_AppMessageImpl(const _AppMessageImpl&rhs) +: __pBundle(bundle_dup(rhs.__pBundle)) +{ + SysAssert(__pBundle != NULL); +} + +_AppMessageImpl::~_AppMessageImpl(void) +{ + SysAssert(__pBundle != NULL); + bundle_free(__pBundle); +} + +_AppMessageImpl& +_AppMessageImpl::operator =(const _AppMessageImpl& rhs) +{ + if (&rhs != this) + { + if (__pBundle) + { + bundle_free(__pBundle); + __pBundle = NULL; + } + + __pBundle = bundle_dup(rhs.__pBundle); + SysAssert(__pBundle != NULL); + } + + return *this; +} + +String +_AppMessageImpl::GetValue(const String& key) const +{ + return GetValue(key.GetPointer()); +} + +String +_AppMessageImpl::GetValue(const wchar_t key[]) const +{ + SysAssert(__pBundle != NULL); + + std::unique_ptr pKey(_StringConverter::CopyToCharArrayN(key)); + + return String(appsvc_get_data(__pBundle, pKey.get())); +} + +result +_AppMessageImpl::AddData(const String& key, const String& value) +{ + SysAssert(__pBundle != NULL); + + return AddData(__pBundle, key, value); +} + +result +_AppMessageImpl::AddData(bundle* pBundle, const String& key, const String& value) +{ + std::unique_ptr pKey(_StringConverter::CopyToCharArrayN(key)); + std::unique_ptr pVal(_StringConverter::CopyToCharArrayN(value)); + + appsvc_add_data(pBundle, pKey.get(), pVal.get()); + + return E_SUCCESS; +} + +result +_AppMessageImpl::SetOperation(bundle* pBundle, const String& operation) +{ + std::unique_ptr pVal(_StringConverter::CopyToCharArrayN(operation)); + + appsvc_set_operation(pBundle, pVal.get()); + + return E_SUCCESS; +} + +result +_AppMessageImpl::SetUri(bundle* pBundle, const String& uri) +{ + std::unique_ptr pVal(_StringConverter::CopyToCharArrayN(uri)); + + appsvc_set_uri(pBundle, pVal.get()); + + return E_SUCCESS; +} + +result +_AppMessageImpl::SetMime(bundle* pBundle, const String& mime) +{ + std::unique_ptr pVal(_StringConverter::CopyToCharArrayN(mime)); + + appsvc_set_mime(pBundle, pVal.get()); + + return E_SUCCESS; +} + +result +_AppMessageImpl::SetCategory(bundle* pBundle, const String& category) +{ + std::unique_ptr pVal(_StringConverter::CopyToCharArrayN(category)); + + appsvc_set_category(pBundle, pVal.get()); + + return E_SUCCESS; +} + +result +_AppMessageImpl::AddData(const IList* pList) +{ + SysAssert(__pBundle != NULL); + + return AddData(__pBundle, pList); +} + +result +_AppMessageImpl::AddData(bundle* pBundle, const IList* pList) +{ + if (pList == null) + { + return E_SUCCESS; + } + + std::unique_ptr pEnum(pList->GetEnumeratorN()); + SysTryReturnResult(NID_APP, pEnum != null, E_OUT_OF_MEMORY, "Getting enumerator failed."); + + String key; + String value; + while (pEnum->MoveNext() == E_SUCCESS) + { + String* pStr = dynamic_cast(pEnum->GetCurrent()); + + int index = -1; + if (pStr == null || pStr->IndexOf(L':', 0, index) != E_SUCCESS) + { + continue; + } + pStr->SubString(0, index, key); + if (key.IsEmpty()) + { + continue; + } + + pStr->SubString(index + 1, value); + + AddData(pBundle, key, value); + + SysLog(NID_APP, "Added (%ls, %ls).", key.GetPointer(), value.GetPointer()); + } + + return E_SUCCESS; +} + +result +_AppMessageImpl::AddData(const IMap* pMap) +{ + SysAssert(__pBundle != NULL); + + return AddStringMap(__pBundle, pMap); +} + +result +_AppMessageImpl::AddStringMap(bundle* pBundle, const IMap* pMap) +{ + if (pMap == null || pMap->GetCount() == 0) + { + SysLog(NID_APP, "No element added for bundle."); + return E_SUCCESS; + } + + std::unique_ptr pEnum (pMap->GetMapEnumeratorN()); + while(pEnum->MoveNext() == E_SUCCESS) + { + const String* pKey = static_cast(pEnum->GetKey()); + const Object* pObj = pEnum->GetValue(); + + if (pKey && pObj) + { + if (typeid(*pObj) == typeid(const String)) + { + const String* pVal = static_cast(pEnum->GetValue()); + if (pVal) + { + _AppMessageImpl::AddData(pBundle, *pKey, *pVal); + } + } + } + } + + return E_SUCCESS; +} + +ArrayList* +_AppMessageImpl::GetValueArray(bundle* pBundle, const String& key) +{ + std::unique_ptr pKey(_StringConverter::CopyToCharArrayN(key)); + + return GetValueArray(pBundle, pKey.get()); +} + +ArrayList* +_AppMessageImpl::GetValueArray(bundle* pBundle, const char* pKey) +{ + int len = 0; + const char** pStrArray = bundle_get_str_array(pBundle, pKey, &len); + if (len == 0) + { + return null; + } + + ArrayList* pArray = new (std::nothrow) ArrayList(SingleObjectDeleter); + SysTryReturn(NID_APP, pArray != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating array failed."); + + pArray->Construct(); + + for (int i = 0; i < len; i++) + { + const char* pStr = pStrArray[i]; + if (pStr) + { + pArray->Add(new (std::nothrow) String(pStr)); + } + } + + if (pArray->GetCount() == 0) + { + delete pArray; + pArray = null; + } + + return pArray; +} + +}} // Tizen::App diff --git a/src/app/FApp_AppRegistryImpl.cpp b/src/app/FApp_AppRegistryImpl.cpp new file mode 100644 index 0000000..b2acafb --- /dev/null +++ b/src/app/FApp_AppRegistryImpl.cpp @@ -0,0 +1,266 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppRegistryImpl.cpp + * @brief This is the implementation for the _AppRegistryImpl class. + */ + +#include +#include + +#include +#include "FApp_AppRegistryImpl.h" +#include "FApp_AppInfo.h" + +using namespace Tizen::Io; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + + +_AppRegistryImpl::_AppRegistryImpl(void) + : __pRegistry(null) + , __sectionName(L"__ApplicationStates") +{ +} + + +_AppRegistryImpl::~_AppRegistryImpl(void) +{ + if (__pRegistry != null) + { + __pRegistry->Flush(); + + delete __pRegistry; + __pRegistry = null; + } +} + + +result +_AppRegistryImpl::Construct(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pRegistry == null, + "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + const String& packageId = _AppInfo::GetPackageId(); + String regName = _AppInfo::GetAppRootPath() + L"data/"; + + SysAssertf(!packageId.IsEmpty(), "Empty packageId."); + r = regName.Append(static_cast (packageId)); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] String appending has failed.", GetErrorMessage(r)); + + __pRegistry = new (std::nothrow) Registry(); + SysTryCatch(NID_APP, __pRegistry != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] Failed while instantiating registry."); + + r = __pRegistry->Construct(regName, true); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%ls] Constructing the registry %s has failed.", regName.GetPointer(), + GetErrorMessage(r)); + + r = __pRegistry->AddSection(__sectionName); + if (r == E_SECTION_ALREADY_EXIST) + { + // section may exist already + r = E_SUCCESS; + } + + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Adding section to registry has failed.", GetErrorMessage(r)); + + return r; + +CATCH: + delete __pRegistry; + __pRegistry = null; + + SysLog(NID_APP, "Exit."); + + return r; +} + + +result +_AppRegistryImpl::Add(const String& key, const String& value) +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->AddValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Adding value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Add(const String& key, int value) +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->AddValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Adding value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Add(const String& key, double value) +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->AddValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Adding value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Set(const String& key, const String& value) +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->SetValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Setting value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Set(const String& key, int value) +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->SetValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Setting value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Set(const String& key, double value) +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->SetValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Setting value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Save(void) +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->Flush(); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Saving value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Remove(const String& key) +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->RemoveValue(__sectionName, key); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Removing value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Get(const String& key, String& value) const +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->GetValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Getting value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Get(const String& key, int& value) const +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->GetValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Getting value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +result +_AppRegistryImpl::Get(const String& key, double& value) const +{ + SysAssertf(__pRegistry != null, "Not yet constructed. Construct() should be called before use."); + + result r = E_SUCCESS; + + r = __pRegistry->GetValue(__sectionName, key, value); + + SysTryLog(NID_APP, !IsFailed(r), "[%s] Getting value to the registry has failed.", GetErrorMessage(r)); + + return r; +} + + +} } // Tizen::App diff --git a/src/app/FApp_AppRegistryImpl.h b/src/app/FApp_AppRegistryImpl.h new file mode 100644 index 0000000..8d2a7ed --- /dev/null +++ b/src/app/FApp_AppRegistryImpl.h @@ -0,0 +1,240 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppRegistryImpl.h + * @brief This is the header file of the _AppRegistryImpl class. + */ + +#ifndef _FAPP_INTERNAL_APP_REGISTRY_IMPL_H_ +#define _FAPP_INTERNAL_APP_REGISTRY_IMPL_H_ + +#include +#include +#include + +namespace Tizen { namespace Io { class Registry; } } + +namespace Tizen { namespace App +{ + +/** + * @class _AppRegistryImpl + * @brief This class manages an application's preferences. + * @since 1.0 + */ +class _AppRegistryImpl + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. + * + * @since 1.0 + */ + virtual ~_AppRegistryImpl(void); + + /** + * Adds a string value along with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value A string value + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_ALREADY_EXIST The key has already been used in the application preferences. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @remark In order to save the value in the persistent storage, the _AppRegistryImpl::Save() method must be called. + */ + result Add(const Tizen::Base::String& key, const Tizen::Base::String& value); + + /** + * Adds an integer value along with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value An integer value + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_ALREADY_EXIST The key has already been used in the application preferences. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @remark Call the _AppRegistryImpl::Save() method to save the value in the persistent storage. + */ + result Add(const Tizen::Base::String& key, int value); + + /** + * Adds a floating point value along with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value A floating point value + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_ALREADY_EXIST The key has already been used in the application preferences. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @remark Call the _AppRegistryImpl::Save() method to save the value in the persistent storage. + */ + result Add(const Tizen::Base::String& key, double value); + + /** + * Updates a string value associated with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value A string value + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_NOT_FOUND The specified key was not used in the application preferences. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @remark Call the _AppRegistryImpl::Save() method to save the value in the persistent storage. + */ + result Set(const Tizen::Base::String& key, const Tizen::Base::String& value); + + /** + * Updates an integer value associated with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value An integer value + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_NOT_FOUND The specified key was not used in the application preferences. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @remark Call the _AppRegistryImpl::Save() method to save the value in the persistent storage. + */ + result Set(const Tizen::Base::String& key, int value); + + /** + * Updates a floating point value associated with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key A key corresponding to the value + * @param[in] value A floating point value + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_NOT_FOUND The specified key was not used in the application preferences. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @remark Call the _AppRegistryImpl::Save() method to save the value in the persistent storage. + */ + result Set(const Tizen::Base::String& key, double value); + + /** + * Saves the values temporarily in the persistent storage. @n + * This method is invoked internally when the instance of this class is deleted. + * + * @since 1.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + */ + result Save(void); + + /** + * Removes a preference associated with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key The key of the value to be removed + * @exception E_SUCCESS The method was successful. + * @exception E_KEY_NOT_FOUND The specified key was not used in the application preferences. + */ + result Remove(const Tizen::Base::String& key); + + /** + * Retrieves a string value associated with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key The key of the value to retrieve + * @param[out] value A string value to be retrieved + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_NOT_FOUND The specified key was not used in the application preferences. + */ + result Get(const Tizen::Base::String& key, Tizen::Base::String& value) const; + + /** + * Retrieves an integer value associated with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key The key of the value to retrieve + * @param[out] value An integer value to be retrieved + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_NOT_FOUND The specified key was not used in the application preferences. + */ + result Get(const Tizen::Base::String& key, int& value) const; + + /** + * Retrieves a floating point value associated with the specified key. + * + * @since 1.0 + * @return An error code + * @param[in] key The key of the value to retrieve + * @param[out] value A floating point value to be retrieved + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of the specified string for a section or entry is smaller than or equal to zero. Or, a @c null value or string with '\0' and '\n' was passed. + * @exception E_KEY_NOT_FOUND The specified key was not used in the application preferences. + */ + result Get(const Tizen::Base::String& key, double& value) const; + +private: + /** + * This is the default constructor for this class. + * + * @since 1.0 + */ + _AppRegistryImpl(void); + + /** + * This is the copy constructor for this class. + * + * @since 1.0 + */ + _AppRegistryImpl(const _AppRegistryImpl& source); + + /** + * Allocates memory for an _AppRegistryImpl object. + * + * @since 1.0 + * + * @return An error code + * @exception E_SUCCESS The method was successful. + */ + result Construct(void); + + /** + * This is the assignment operator for this class. + */ + _AppRegistryImpl& operator =(const _AppRegistryImpl& source); + +private: + Tizen::Io::Registry* __pRegistry; + const Tizen::Base::String __sectionName; + + friend class AppRegistry; +}; // _AppRegistryImpl + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_REGISTRY_IMPL_H_ diff --git a/src/app/FApp_AppResourceImpl.cpp b/src/app/FApp_AppResourceImpl.cpp new file mode 100644 index 0000000..33ad248 --- /dev/null +++ b/src/app/FApp_AppResourceImpl.cpp @@ -0,0 +1,200 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppResourceImpl.cpp + * @brief This is the implementation for the _AppResourceImpl class. + */ + +#include +#include +#include +#include +#include + +#include + +#include "FApp_AppResourceImpl.h" +#include "FApp_AppResourceString.h" +#include "FApp_AppManagerImpl.h" +#include "FApp_IAppResourceBitmap.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Io; +using namespace Tizen::Locales; +using namespace Tizen::System; + +using namespace Tizen::Graphics; + +namespace Tizen { namespace App +{ + +#define BITMAP_PIXEL_FORMAT_INVALID (BITMAP_PIXEL_FORMAT_MIN) + +static _IAppResourceBitmap*(* p_Create_AppResourceBitmapInstanceN)(void) = null; +static _IAppResourceBitmap*(* p_Create_AppResourceBitmapInstanceByAppIdN)(const String& appId) = null; + +_AppResourceImpl::_AppResourceImpl(void) + : __pAppResource(null) + , __p_AppResourceString(null) + , __p_IAppResourceBitmap(null) + , __isByAppId(false) +{ +} + + +result +_AppResourceImpl::Construct(const Locale& locale) +{ + return Construct(); +} + + +result +_AppResourceImpl::Construct(void) +{ + return E_SUCCESS; +} + +result +_AppResourceImpl::Construct(const AppId& appId) +{ + result r = E_SUCCESS; + if (__p_AppResourceString == null) + { + __p_AppResourceString = new (std::nothrow) _AppResourceString(); + SysTryReturnResult(NID_APP, __p_AppResourceString != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]Failed to create String resource"); + + r = __p_AppResourceString->Construct(appId); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Failed to construct String resource", GetErrorMessage(r)); + } + + if (p_Create_AppResourceBitmapInstanceByAppIdN == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetInstance()->GetUiLibraryImpl(); + p_Create_AppResourceBitmapInstanceByAppIdN = reinterpret_cast<_IAppResourceBitmap*(*)(const String& appId)>(lib.GetProcAddress(L"_Create_IAppResourceBitmapInstanceByAppIdN")); + SysTryCatch(NID_APP, p_Create_AppResourceBitmapInstanceByAppIdN != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get Bitmap resource [%s].", GetErrorMessage(GetLastResult())); + } + + if (__p_IAppResourceBitmap == null) + { + __p_IAppResourceBitmap = p_Create_AppResourceBitmapInstanceByAppIdN(appId); + SysTryCatch(NID_APP, __p_IAppResourceBitmap != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get Bitmap resource."); + } + + __isByAppId = true; + return E_SUCCESS; + +CATCH: + delete __p_AppResourceString; + __p_AppResourceString = null; + + return r; +} + +_AppResourceImpl::~_AppResourceImpl(void) +{ + delete __p_AppResourceString; + delete __p_IAppResourceBitmap; +} + + +result +_AppResourceImpl::GetString(const String& resourceId, String& loadedString) +{ + result r = E_SUCCESS; + + if ((__isByAppId == false) && (__p_AppResourceString == null)) + { + __p_AppResourceString = new (std::nothrow) _AppResourceString(); + SysTryReturnResult(NID_APP, __p_AppResourceString != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]Not enough memory."); + + r = __p_AppResourceString->Construct(); + SysTryCatch(NID_APP, !IsFailed(r), , r = E_SYSTEM, "[E_SYSTEM] Failed to get String resource."); + } + + r = __p_AppResourceString->GetString(resourceId, loadedString); + +CATCH: + return r; +} + + +Bitmap* +_AppResourceImpl::GetBitmapN(const String& imgFilePath, BitmapPixelFormat pixelFormat) +{ + if (__isByAppId == false) + { + if (p_Create_AppResourceBitmapInstanceN == null) + { + _LibraryImpl& lib = _AppManagerImpl::GetInstance()->GetUiLibraryImpl(); + p_Create_AppResourceBitmapInstanceN = reinterpret_cast<_IAppResourceBitmap*(*)(void)>(lib.GetProcAddress(L"_Create_IAppResourceBitmapInstanceN")); + SysTryCatch(NID_APP, p_Create_AppResourceBitmapInstanceN != null, , E_SYSTEM, "[E_SYSTEM] Failed to get Bitmap resource [%s].", GetErrorMessage(GetLastResult())); + } + + if (__p_IAppResourceBitmap == null) + { + __p_IAppResourceBitmap = p_Create_AppResourceBitmapInstanceN(); + SysTryCatch(NID_APP, __p_IAppResourceBitmap != null, , E_SYSTEM, "[E_SYSTEM] Failed to get Bitmap resource."); + } + } + + return __p_IAppResourceBitmap->GetBitmapN(imgFilePath, pixelFormat); + +CATCH: + return null; +} + + +Bitmap* +_AppResourceImpl::GetBitmapN(const String& imgFilePath) +{ + return GetBitmapN(imgFilePath, BITMAP_PIXEL_FORMAT_INVALID); +} + + +AppResource* +_AppResourceImpl::GetAppResource(void) +{ + return __pAppResource; +} + +_AppResourceImpl* +_AppResourceImpl::GetInstance(void) +{ +// return __pAppResource->__pAppResourceImpl; + return AppResource::GetInstance()->__pAppResourceImpl; +} + +void +_AppResourceImpl::Reinitialize(void) +{ + if (__p_AppResourceString != null) + { + + __p_AppResourceString->Initialize(); + } + AppResource::Reinitialize(); +} + +void +_AppResourceImpl::Reinitialize(const AppId& appId) +{ + __p_AppResourceString->Initialize(appId); +} +} } // Tizen::App diff --git a/src/app/FApp_AppResourceImpl.h b/src/app/FApp_AppResourceImpl.h new file mode 100644 index 0000000..eb475ed --- /dev/null +++ b/src/app/FApp_AppResourceImpl.h @@ -0,0 +1,184 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppResourceImpl.h + * @brief This is the header file of the _AppResourceImpl class. + */ + +#ifndef _FAPP_INTERNAL_APP_RESOURCE_IMPL_H_ +#define _FAPP_INTERNAL_APP_RESOURCE_IMPL_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Locales { class Locale; } } +namespace Tizen { namespace Graphics { class Bitmap; } } + +namespace Tizen { namespace App +{ + +class AppResource; +class _AppResourceString; +class _IAppResourceBitmap; + +class _AppResourceImpl + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. + * + * @since 1.0 + */ + virtual ~_AppResourceImpl(void); + + /** + * Gets the string at the specified resource ID. + * + * @since 1.0 + * @return An error code + * @param[in] resourceId The resource ID describing the String resource + * @param[out] loadedString The string obtained from the loaded application resource + * @exception E_SUCCESS The method was successful. + * @exception E_FAILURE The argument passed is not found. + * @exception E_INVALID_ARG The argument passed to a method contains an invalid resource ID. + */ + result GetString(const Tizen::Base::String& resourceId, Tizen::Base::String& loadedString); + + /** + * Gets the Bitmap at the specified path. @n + * This method interprets the given resource path and reads the best matching image file for the current device resolution. @n + * To load bitmap image from a file, you give the name of file as the input parameter not the file path (Ex: "img.png"). + * Then, the system will first look for the image file in the folder specific to the current device resolution such as + * '320x480' and if the file does not exist, it will then search the folder that corresponds to the current screen density, + * such as 'ScreenDensity-Middle'. After searching density folder, all other density folders are searched in the order high to low. + * Currently supported image formats are JPEG, GIF, PNG, BMP, TIFF, and WBMP. + * + * @since 1.1 + * + * @return A Bitmap instance generated from the specified file + * @param[in] imagePath The relative path starting from the directory "/res/screen-density-XXX/", @n + * where A and B represents the screen width and height of the supported device models, respectively. + * @param[in] pixelFormat The pixel format of the resulting bitmap + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_UNSUPPORTED_FORMAT The image file format or specified pixel format is not supported. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_FILE_NOT_FOUND The specified file could not be found. + * @exception E_SYSTEM A system error occurred. + */ + Tizen::Graphics::Bitmap* GetBitmapN(const Tizen::Base::String& imagePath, Tizen::Graphics::BitmapPixelFormat pixelFormat); + + /** + * Gets the Bitmap at the specified path. @n + * This method interprets the given resource path and reads the best matching image file for the current device resolution. @n + * To load bitmap image from a file, you give the name of file as the input parameter not the file path (Ex: "img.png"). + * Then, the system will first look for the image file in the folder specific to the current device resolution such as + * '320x480' and if the file does not exist, it will then search the folder that corresponds to the current screen density, + * such as 'ScreenDensity-Middle'. After searching density folder, all other density folders are searched in the order high to low. + * Currently supported image formats are JPEG, GIF, PNG, BMP, TIFF, and WBMP. + * + * In this method, the system decides the proper pixel format and whether to use chroma key composition to enable transparency. @n + * If the input image file has the alpha channel, the pixel format is set to Tizen::Graphics::BITMAP_PIXEL_FORMAT_ARGB8888. + * Otherwise, the pixel format is set to BITMAP_PIXEL_FORMAT_RGB565 and the masking color of the bitmap is set to magenta, Tizen::Graphics::Color(255, 0, 255). @n + * Typically, a WVGA Tizen device would support alpha channel, while WQVGA device would support bitmap with masking color, to support transparency. + * You can place a 32-bit version of the resource and a 16-bit version in the WQVGA resource folder at the same folder. To distinguish the pixel format, you can use a postfix '@@16' such as 'image@@.bmp'. + * If you don't use postfix, this API would load the correct image and set the pixel format from the image file, that is appropriate for the current device. @n + * Currently supported image formats are JPEG, GIF, PNG, BMP, TIFF, and WBMP. + * + * @since 1.1 + * + * @return A Bitmap instance generated from the specified file. + * @param[in] imagePath The relative path starting from the density directory "/res/screen-density-XXX/", @n + * where A and B represents the width and height of the screen of the supported device models, respectively + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_UNSUPPORTED_FORMAT The image file format is not supported. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_FILE_NOT_FOUND The specified file could not be found. + * @exception E_SYSTEM A system error occurred. + */ + Tizen::Graphics::Bitmap* GetBitmapN(const Tizen::Base::String& imagePath); + + /** + * Gets the AppResoruce instance pointer. + * + * @since 2.0 + * @return An AppResoruce instance pointer, if successful @n + * @c null, if it fails + */ + static _AppResourceImpl* GetInstance(void); + + AppResource* GetAppResource(void); + + void Reinitialize(void); + + void Reinitialize(const AppId& appId); + +private: + /** + * This is the default constructor for this class. + * + * @since 1.0 + */ + _AppResourceImpl(void); + + /** + * This is the copy constructor for this class. + * + * @since 1.0 + */ + _AppResourceImpl(const _AppResourceImpl& source); + + /** + * Initializes this instance. + * + */ + result Construct(void); + + /** + * Initializes this instance. + * + */ + result Construct(const AppId& appId); + + /** + * Initializes this instance with the specified locale. + * + */ + result Construct(const Tizen::Locales::Locale& locale); + + /** + * This is the assignment operator for this class. + */ + _AppResourceImpl& operator =(const _AppResourceImpl& source); + +private: + friend class AppResource; + AppResource* __pAppResource; + _AppResourceString* __p_AppResourceString; + _IAppResourceBitmap* __p_IAppResourceBitmap; + bool __isByAppId; + +}; // _AppResourceImpl + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_RESOURCE_IMPL_H_ diff --git a/src/app/FApp_AppResourceString.cpp b/src/app/FApp_AppResourceString.cpp new file mode 100644 index 0000000..9bfc349 --- /dev/null +++ b/src/app/FApp_AppResourceString.cpp @@ -0,0 +1,644 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppResourceString.cpp + * @brief This is the implementation for the _AppResourceString class. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "FApp_AppResourceString.h" +#include "FAppPkg_PackageManagerImpl.h" +#include "FAppPkg_PackageInfoImpl.h" + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Io; +using namespace Tizen::Locales; +using namespace Tizen::System; + +static const char* AR_ROOT_NODE_NAME = "string_table"; +static const char* AR_CHILD_NODE_1 = "text"; +static const char* AR_ATTRIBUTE = "id"; + +static xmlNodePtr gCur = 0; + +namespace Tizen { namespace App +{ + +_AppResourceString::_AppResourceString(void) + : __pDoc(null) + , __pLockOfParser(null) +{ +} + + +result +_AppResourceString::Construct(const Tizen::Locales::Locale& locale) +{ + return Construct(); +} + + +result +_AppResourceString::Construct(void) +{ + return Initialize(); +} + +result +_AppResourceString::Construct(const AppId& appId) +{ + return Initialize(appId); +} + +result +_AppResourceString::Initialize(void) +{ + result r = E_SUCCESS; + if (__pLockOfParser == null) + { + __pLockOfParser = new (std::nothrow) Tizen::Base::Runtime::Mutex(); + SysTryReturnResult(NID_APP, __pLockOfParser != null, E_OUT_OF_MEMORY, "Failed to initialize resource parser."); + + r = __pLockOfParser->Create(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Failed to Create Mutex.", GetErrorMessage(r)); + } + + + r = __pLockOfParser->Acquire(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Failed to Acquire Mutex.", GetErrorMessage(r)); + + r = InitializeStringInfo(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Failed to InitializeStringInfo.", GetErrorMessage(r)); + + __pLockOfParser->Release(); + return E_SUCCESS; + +CATCH: + delete __pLockOfParser; + __pLockOfParser = null; + + return r; +} + +result +_AppResourceString::Initialize(const AppId& appId) +{ + result r = E_SUCCESS; + if (__pLockOfParser == null) + { + __pLockOfParser = new (std::nothrow) Tizen::Base::Runtime::Mutex(); + SysTryReturnResult(NID_APP, __pLockOfParser != null, E_OUT_OF_MEMORY, "Failed to initialize resource parser."); + + r = __pLockOfParser->Create(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Failed to Create Mutex.", GetErrorMessage(r)); + } + + r = __pLockOfParser->Acquire(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Failed to Acquire Mutex.", GetErrorMessage(r)); + + r = InitializeStringInfo(appId); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Failed to InitializeStringInfo.", GetErrorMessage(r)); + + __pLockOfParser->Release(); + return E_SUCCESS; + +CATCH: + delete __pLockOfParser; + __pLockOfParser = null; + + return r; +} + + + +result +_AppResourceString::InitializeStringInfo(void) +{ + if (__pDoc != null) + { + SysLog(NID_APP, "__pDoc is freed to reinitialize."); + xmlFreeDoc(__pDoc); + __pDoc = null; + } + + char* pValue = null; + int ret = runtime_info_get_value_string(RUNTIME_INFO_KEY_LANGUAGE, &pValue); + SysTryReturnResult(NID_APP, ret == 0, E_FAILURE, "[E_SYSTEM] runtime_info_get_value_string returns %d.", ret); + + U_ICU_NAMESPACE::Locale icuLcl(pValue); + + String language(icuLcl.getISO3Language()); + String country(icuLcl.getCountry()); + +// SysLog(NID_APP, "res/%ls-%ls.xml", language.GetPointer(), country.GetPointer()); + + String resFilename; + result r = resFilename.Format(256 * 2 + 10, L"res/%ls-%ls.xml", language.GetPointer(), country.GetPointer()); + SysTryReturn(NID_APP, !IsFailed(r), E_FAILURE, r, "[%s] Failed to format path string", GetErrorMessage(r)); + + const String& homePath = _AppInfo::GetAppRootPath(); + __pDoc = ParseXmlFile( homePath + resFilename); + + // Fall-back + if (__pDoc == null) + { + String dirName(L"res/"); + Directory dir; + DirEnumerator* pDirEnum = null; + String name; + + r = dirName.Insert(homePath, 0); + SysTryReturn(NID_APP, !IsFailed(r), E_FAILURE, r, "[%s] Failed to insert string.", GetErrorMessage(r)); + + // open directory + r = dir.Construct(dirName); + if (r == E_SUCCESS) + { + // read all directory entries + pDirEnum = dir.ReadN(); + if (pDirEnum != null) + { + const String starts = language + L"-"; + const String ends = L".xml"; + + // loop through all directory entries + while (pDirEnum->MoveNext() == E_SUCCESS) + { + // get several properties of each directory entry. + name = pDirEnum->GetCurrentDirEntry().GetName(); + + if (name.StartsWith(starts, 0) && name.EndsWith(ends)) + { + resFilename = L"res/" + name; + __pDoc = ParseXmlFile(homePath + resFilename); + break; + } + } + // Delete enumerator + delete pDirEnum; + } + } + } + + if (__pDoc == null) + { + __pDoc = ParseXmlFile(homePath + L"res/eng-GB.xml"); + } + + if (__pDoc == null) + { + __pDoc = ParseXmlFile(homePath + L"res/eng-US.xml"); + } + + if (__pDoc == null) + { + __pDoc = ParseXmlFile(homePath + L"res/English.xml"); + } + + if (__pDoc == null) + { + SysLog(NID_APP, "Can't find xml resource file."); + return E_SUCCESS; //E_FILE_NOT_FOUND; + } + + xmlNodePtr cur = xmlDocGetRootElement(__pDoc); + SysTryReturnResult(NID_APP, cur != null, E_FAILURE, "Empty document."); + + if (xmlStrcmp(cur->name, (const xmlChar*) AR_ROOT_NODE_NAME)) + { + SysLogException(NID_APP, E_FAILURE, "[E_FAILURE] Document root node is not ."); + return E_FAILURE; + } + + gCur = cur; + + return E_SUCCESS; +} + +result +_AppResourceString::InitializeStringInfo(const AppId& appId) +{ + if (__pDoc != null) + { + SysLog(NID_APP, "__pDoc is freed to reinitialize."); + xmlFreeDoc(__pDoc); + __pDoc = null; + } + + char* pValue = null; + int ret = runtime_info_get_value_string(RUNTIME_INFO_KEY_LANGUAGE, &pValue); + SysTryReturnResult(NID_APP, ret == 0, E_FAILURE, "[E_SYSTEM] runtime_info_get_value_string returns %d.", ret); + + + U_ICU_NAMESPACE::Locale icuLcl(pValue); + + String language(icuLcl.getISO3Language()); + String country(icuLcl.getCountry()); + +// SysLog(NID_APP, "res/%ls-%ls.xml", language.GetPointer(), country.GetPointer()); + + String resFilename; + result r = resFilename.Format(256 * 2 + 10, L"/res/%ls-%ls.xml", language.GetPointer(), country.GetPointer()); + SysTryReturn(NID_APP, !IsFailed(r), E_FAILURE, r, "[%s] Failed to format path string", GetErrorMessage(r)); + + PackageInfo* pPkgInfo = null; + pPkgInfo = _PackageManagerImpl::GetInstance()->GetPackageInfoN(appId); + SysTryReturnResult(NID_APP, pPkgInfo != null, E_APP_NOT_INSTALLED, "Failed to get the package info"); + + _PackageInfoImpl* pPkgInfoImpl = _PackageInfoImpl::GetInstance(pPkgInfo); + SysTryReturnResult(NID_APP, pPkgInfoImpl != null, E_APP_NOT_INSTALLED, "Failed to get the package info impl"); + + const Tizen::Base::String& homePath = pPkgInfoImpl->GetAppRootPath(); + + __pDoc = ParseXmlFile( homePath + resFilename); + + // Fall-back + if (__pDoc == null) + { + String dirName(L"/res/"); + Directory dir; + DirEnumerator* pDirEnum = null; + String name; + + r = dirName.Insert(homePath, 0); + SysTryReturn(NID_APP, !IsFailed(r), E_FAILURE, r, "[%s] Failed to insert string.", GetErrorMessage(r)); + + // open directory + r = dir.Construct(dirName); + if (r == E_SUCCESS) + { + // read all directory entries + pDirEnum = dir.ReadN(); + if (pDirEnum != null) + { + const String starts = language + L"-"; + const String ends = L".xml"; + + // loop through all directory entries + while (pDirEnum->MoveNext() == E_SUCCESS) + { + // get several properties of each directory entry. + name = pDirEnum->GetCurrentDirEntry().GetName(); + + if (name.StartsWith(starts, 0) && name.EndsWith(ends)) + { + resFilename = L"/res/" + name; + __pDoc = ParseXmlFile(homePath + resFilename); + break; + } + } + // Delete enumerator + delete pDirEnum; + } + } + } + + if (__pDoc == null) + { + __pDoc = ParseXmlFile(homePath + L"/res/eng-GB.xml"); + } + + if (__pDoc == null) + { + __pDoc = ParseXmlFile(homePath + L"/res/eng-US.xml"); + } + + if (__pDoc == null) + { + __pDoc = ParseXmlFile(homePath + L"/res/English.xml"); + } + + if (__pDoc == null) + { + SysLog(NID_APP, "Can't find xml resource file."); + return E_DATA_NOT_FOUND; + } + + xmlNodePtr cur = xmlDocGetRootElement(__pDoc); + SysTryReturnResult(NID_APP, cur != null, E_FAILURE, "Empty document."); + + if (xmlStrcmp(cur->name, (const xmlChar*) AR_ROOT_NODE_NAME)) + { + SysLogException(NID_APP, E_FAILURE, "[E_FAILURE] Document root node is not ."); + return E_FAILURE; + } + + gCur = cur; + + delete pPkgInfo; + return E_SUCCESS; +} + +xmlDocPtr +_AppResourceString::ParseXmlFile(const String& path) +{ + if (File::IsFileExist(path) == false ) + { + SysLog(NID_APP, "'%ls' isn't exist.", path.GetPointer()); + return null; + } + + std::unique_ptr pBuf(_StringConverter::CopyToCharArrayN(path)); + xmlDocPtr docPtr = xmlParseFile(pBuf.get()); + + if (docPtr == null) + { + SysLog(NID_APP, "failed to parse resource file(%ls)", path.GetPointer()); + return null; + } + + SysLog(NID_APP, "'%ls' is parsed successfully.", path.GetPointer()); + return docPtr; +} + + +_AppResourceString::~_AppResourceString(void) +{ + if (__pDoc != null) + { + xmlFreeDoc(__pDoc); + } + delete __pLockOfParser; +} + + +result +_AppResourceString::GetString(const String resourceId, String& loadedString) +{ + SysTryReturnResult(NID_APP, __pDoc != null, E_INVALID_STATE, "Can't find xml resource file."); + +#if defined(ENABLE_XPATH) + xmlXPathContextPtr __pXpathCtx = null; + xmlXPathObjectPtr __pXpathObj = null; + + String key; + key.Format(1024, L"/string_table/text[@id='%ls']", resourceId.GetPointer()); + + xmlChar* pXpathExpr = (xmlChar*) (_StringConverter::CopyToCharArrayN(key)); + xmlChar* pContent = null; + // Create xpath evaluation context + __pXpathCtx = xmlXPathNewContext(__pDoc); + if (__pXpathCtx == null) + { + SysLogException(NID_APP, E_INVALID_STATE, "[E_INVALID_STATE] XPathNewContext must not be null."); + + delete[] pXpathExpr; + return E_INVALID_STATE; + } + + // Evaluate xpath expression + __pXpathObj = xmlXPathEvalExpression(pXpathExpr, __pXpathCtx); + if (null == __pXpathObj || + null == __pXpathObj->nodesetval || + null == __pXpathObj->nodesetval->nodeTab || + null == __pXpathObj->nodesetval->nodeTab[0]->children + ) + { + SysLog(NID_APP, "xpath expression is invalid."); + + xmlXPathFreeContext(__pXpathCtx); + __pXpathCtx = null; + delete[] pXpathExpr; + return E_INVALID_ARG; + } + delete[] pXpathExpr; + + pContent = __pXpathObj->nodesetval->nodeTab[0]->children->content; + loadedString = String((char*) pContent); + + SysLog(NID_APP, "content : %s.", pContent); + + // file close & open + // Cleanup of XPath data + xmlXPathFreeObject(__pXpathObj); + __pXpathObj = null; + xmlXPathFreeContext(__pXpathCtx); + __pXpathCtx = null; + + SysLog(NID_APP, "Free xpath data."); + + return E_SUCCESS; + +#else + xmlNodePtr cur = null; + xmlChar* pValue = null; + xmlChar* pId = null; + + SysTryReturnResult(NID_APP, !resourceId.IsEmpty(), E_INVALID_ARG, "Wrong resource Id."); + SysTryReturnResult(NID_APP, gCur != null && __pDoc != null, E_INVALID_STATE, + "Application string resource was not initialized."); + SysTryReturnResult(NID_APP, __pLockOfParser != null, E_INVALID_STATE, "__pLockOfParser was not initialized."); + + result r = __pLockOfParser->Acquire(); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Failed to Acquire Mutex.", GetErrorMessage(r)); + + pId = (xmlChar*) (_StringConverter::CopyToCharArrayN(resourceId)); + cur = gCur; + cur = cur->xmlChildrenNode; + while (cur != null) + { + if ((!xmlStrcmp(cur->name, (const xmlChar*) AR_CHILD_NODE_1))) + { + pValue = xmlGetProp(cur, (const xmlChar*) AR_ATTRIBUTE); + if (!xmlStrcmp(pValue, (const xmlChar*) pId)) + { + xmlChar* pContent = xmlNodeListGetString( __pDoc, cur->xmlChildrenNode, 1); + SysLog(NID_APP, "xml content=%s", pContent); + loadedString = (char*) (pContent); + + if (HasSpecialString(loadedString)) + { + String rawString(loadedString); + ConvertToCstyleString(rawString, loadedString); + } + + if (pContent) + { + xmlFree(pContent); + } + + if (pValue) + { + xmlFree(pValue); + } + + if (pId) + { + delete[] (char*) pId; + } + + __pLockOfParser->Release(); + return E_SUCCESS; + } + if (pValue) + { + xmlFree(pValue); + } + } + cur = cur->next; + } + + if (pId) + { + delete[] (char*) pId; + } + + __pLockOfParser->Release(); + + return E_FAILURE; +#endif +} + + +bool +_AppResourceString::HasSpecialString(const String& resourceStr) +{ + int foundIndex = 0; + + return((resourceStr.IndexOf("<", 0, foundIndex) == E_SUCCESS) + || (resourceStr.IndexOf("&", 0, foundIndex) == E_SUCCESS) + || (resourceStr.IndexOf(">", 0, foundIndex) == E_SUCCESS) + || (resourceStr.IndexOf("'", 0, foundIndex) == E_SUCCESS) + || (resourceStr.IndexOf(""", 0, foundIndex) == E_SUCCESS) + || (resourceStr.IndexOf("&", 0, foundIndex) == E_SUCCESS) + || (resourceStr.IndexOf("\\", 0, foundIndex) == E_SUCCESS)); +} + + +result +_AppResourceString::ConvertToCstyleString(const String& resourceStr, String& convertedStr) +{ + result r = E_SUCCESS; + + int i = 0; + int j = 0; + int len = 0; + + SysTryReturnResult(NID_APP, resourceStr.GetLength() > 0, E_INVALID_ARG, "resource string must be greater than 0."); + + std::unique_ptr pBuffer(_StringConverter::CopyToCharArrayN(resourceStr)); + // len = resourceStr.GetLength(); comment out because GetLength() returns UTF8 length. + SysTryReturnResult(NID_APP, pBuffer != null, E_OUT_OF_MEMORY, "Memory allocation failure."); + + len = strlen(pBuffer.get());// len = String_length((MString)pBuffer); + + while (i < len) + { + if (pBuffer[i] == '\\') + { + if (pBuffer[i + 1] == 'n') + { + pBuffer[j] = '\n'; + i += 2; + j++; + } + else if (pBuffer[i + 1] == 't') + { + pBuffer[j] = '\t'; + i += 2; + j++; + } + else if (pBuffer[i + 1] == '\\') + { + pBuffer[j] = '\\'; + i += 2; + j++; + } + else + { + i++; + } + } + else if ((pBuffer[i] == '&') && (pBuffer[i + 1] == 'l') && (pBuffer[i + 2] == 't') && + (pBuffer[i + 3] == ';')) + { + pBuffer[j] = '<'; + i += 4; + j++; + } + else if ((pBuffer[i] == '&') && (pBuffer[i + 1] == 'g') && (pBuffer[i + 2] == 't') && + (pBuffer[i + 3] == ';')) + { + pBuffer[j] = '>'; + i += 4; + j++; + } + else if ((pBuffer[i] == '&') && (pBuffer[i + 1] == 'a') && (pBuffer[i + 2] == 'm') && + (pBuffer[i + 3] == 'p') && (pBuffer[i + 4] == ';')) + { + pBuffer[j] = '&'; + i += 5; + j++; + } + else if ((pBuffer[i] == '&') && (pBuffer[i + 1] == 'a') && (pBuffer[i + 2] == 'p') && + (pBuffer[i + 3] == 'o') && (pBuffer[i + 4] == 's') && (pBuffer[i + 5] == ';')) + { + pBuffer[j] = 39; // ' + i += 6; + j++; + } + else if ((pBuffer[i] == '&') && (pBuffer[i + 1] == 'q') && (pBuffer[i + 2] == 'u') && + (pBuffer[i + 3] == 'o') && (pBuffer[i + 4] == 't') && (pBuffer[i + 5] == ';')) + { + pBuffer[j] = 34; // " + i += 6; + j++; + } + else + { + pBuffer[j] = pBuffer[i]; + i++; + j++; + } + } + if (j != i) + { + for (; j <= i; j++) + { + pBuffer[j] = '\0'; + } + } + + convertedStr = pBuffer.get(); + + return r; +} + + +} } // Tizen::App diff --git a/src/app/FApp_AppResourceString.h b/src/app/FApp_AppResourceString.h new file mode 100644 index 0000000..58a0a3b --- /dev/null +++ b/src/app/FApp_AppResourceString.h @@ -0,0 +1,118 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppResourceString.h + * @brief This is the header file of the _AppResourceString class. + */ + +#ifndef _FAPP_INTERNAL_APP_RESOURCE_STRING_H_ +#define _FAPP_INTERNAL_APP_RESOURCE_STRING_H_ + +#include +#include + +namespace Tizen { namespace Locales { class Locale; } } + +struct _xmlDoc; +typedef _xmlDoc* xmlDocPtr; + +namespace Tizen { namespace App +{ + +class _AppResourceString + : public Tizen::Base::Object +{ +public: + /** + * This is the destructor for this class. + * + * @since 1.0 + */ + virtual ~_AppResourceString(void); + + /** + * Gets the string at the specified resource ID. + * + * @since 1.0 + * @return An error code + * @param[in] resourceId The resource ID describing the String resource + * @param[out] loadedString The string obtained from the loaded application resource + * @exception E_SUCCESS The method was successful. + * @exception E_FAILURE The argument passed is not found. + * @exception E_INVALID_STATE The state of XML context is not in a valid state. + * @exception E_INVALID_ARG The argument passed to a method contains an invalid resource ID. + */ + result GetString(const Tizen::Base::String resourceId, Tizen::Base::String& loadedString); + + /** + * Initializes this instance. + * + */ + result Construct(void); + + /** + * Initializes this instance with the specified locale. + * + */ + result Construct(const Tizen::Locales::Locale& locale); + + + result Initialize(void); + + result Construct(const AppId& appId); + + result Initialize(const AppId& appId); + +private: + result InitializeStringInfo(void); + result InitializeStringInfo(const AppId& appId); + static bool HasSpecialString(const Tizen::Base::String& resourceStr); + static result ConvertToCstyleString(const Tizen::Base::String& resourceStr, Tizen::Base::String& convertedStr); + static xmlDocPtr ParseXmlFile(const Tizen::Base::String& path); + +private: + /** + * This is the default constructor for this class. + * + * @since 1.0 + */ + _AppResourceString(void); + + /** + * This is the copy constructor for this class. + * + * @since 1.0 + */ + _AppResourceString(const _AppResourceString& source); + + /** + * This is the assignment operator for this class. + */ + _AppResourceString& operator =(const _AppResourceString& source); + +private: + + xmlDocPtr __pDoc; + Tizen::Base::Runtime::Mutex* __pLockOfParser; + + friend class _AppResourceImpl; +}; // _AppResourceString + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_RESOURCE_STRING_H_ diff --git a/src/app/FApp_AppSettingImpl.cpp b/src/app/FApp_AppSettingImpl.cpp new file mode 100644 index 0000000..4502758 --- /dev/null +++ b/src/app/FApp_AppSettingImpl.cpp @@ -0,0 +1,1201 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppResourceImpl.cpp + * @brief This is the implementation file of the _AppResourceImpl class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FApp_AppSettingImpl.h" +#include "FApp_AppInfo.h" +#include "FAppPkg_PackageManagerImpl.h" +#include "FAppPkg_PackageInfoImpl.h" + + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; +using namespace Tizen::Security; +using namespace Tizen::App; + + +namespace Tizen { namespace App +{ + +const int APP_ID_LENTH = 10; +const int MAX_CONTENT_LEN = 512; +const int MAX_LOCAL_BUFSIZE = 128; +const char* DBUS_PATH = "/setting/dbus_handler"; +const char* DBUS_SIGNAL_INTERFACE = "org.tizen.setting.signal"; +static const wchar_t DBUS_SIGNAL_PREFIX[] = L"Update_"; + +static const wchar_t RESOUCE_FILE_PATH[] = L"setting/"; +static const wchar_t RESOUCE_FILE_NAME[] = L"setting"; +static const wchar_t RESOUCE_FILE_EXT[] = L".xml"; + +static _AppSettingImpl* pAppSettingImplInstance = null; + +_AppSettingImpl::_MutiInstanceManager _AppSettingImpl::__appIdMultiInstanceMgr; // static member +DBusConnection* pDBusConnection = null; + +class _CleanUpDBus +{ +public: + ~_CleanUpDBus() + { + if (pDBusConnection) + { + dbus_connection_close(pDBusConnection); + pDBusConnection = null; + } + } +}; +static _CleanUpDBus cleanUpDBus; + +_AppSettingImpl::_MutiInstanceManager::_MutiInstanceManager(void) +{ + __stringToInstanceMap.Construct(); +} + +_AppSettingImpl::_MutiInstanceManager::~_MutiInstanceManager(void) +{ + __stringToInstanceMap.RemoveAll(true); // Remove instance on exit. +} + +AppSetting* +_AppSettingImpl::_MutiInstanceManager::GetInstance(const String& version) +{ + result r = E_SUCCESS; + AppSetting* pAppSettingInstance = null; + String* pKeyStr = null; + + AppSetting* pAppSetting = static_cast( __stringToInstanceMap.GetValue(version)); + if (pAppSetting) + { + return pAppSetting; + } + + // Common creation part + std::unique_ptr<_AppSettingImpl> pAppSettingImpl(new (std::nothrow) _AppSettingImpl()); + SysTryReturn(NID_APP, pAppSettingImpl != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + // Get current application context AppId + App* pApp = App::GetInstance(); + String appId; + SysTryCatch(NID_APP, pApp != null, , E_SYSTEM, "[%s] A system error has been occurred. App::GetInstance() failed", + GetErrorMessage(E_SYSTEM)); + appId = pApp->GetAppId(); + + r = pAppSettingImpl->Construct(appId, version); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + pAppSettingInstance = _AppSettingImpl::CreateAppSetting(); + SysTryCatch(NID_APP, pAppSettingInstance != null, , E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + _AppSettingImpl::SetImplInstance(*pAppSettingInstance, *pAppSettingImpl.release()); + + pKeyStr = new (std::nothrow) String(version); + SysTryCatch(NID_APP, pKeyStr != null, , E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = __stringToInstanceMap.Add(*pKeyStr, *pAppSettingInstance); + SysTryCatch(NID_APP, r != E_OUT_OF_MEMORY, , r, "[%s] Memory allocation failed.", GetErrorMessage(r)); + SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] A system error has been occurred.", GetErrorMessage(E_SYSTEM)); + + return pAppSettingInstance; + +CATCH: + delete pAppSettingInstance; + return null; +} + +AppSetting* +_AppSettingImpl::_MutiInstanceManager::GetInstanceByAppId(const AppId& appId) +{ + result r = E_SUCCESS; + AppSetting* pAppSettingInstance = null; + String* pKeyStr = null; + + r = _AccessController::CheckUserPrivilege(_PRV_APPSETTING); + SysTryReturn(NID_APP, !IsFailed(r), null, E_PRIVILEGE_DENIED, + "[%s] The application does not have the privilege to call this method.", GetErrorMessage(E_PRIVILEGE_DENIED)); + + // Convert AppId to package type id. + String packageId; + appId.SubString(0, APP_ID_LENTH, packageId); + + AppSetting* pAppSetting = static_cast( __stringToInstanceMap.GetValue(packageId)); + if (pAppSetting) + { + return pAppSetting; + } + + _PackageManagerImpl* pPkgMgrImpl = _PackageManagerImpl::GetInstance(); + SysTryReturn(NID_APP, pPkgMgrImpl != null, null, E_SYSTEM, + "[%s] A system error has been occurred. failed to get _PackageMaangerImpl.", GetErrorMessage(E_SYSTEM)); + + PackageInfo* pPackageInfo = null; + pPackageInfo = pPkgMgrImpl->GetPackageInfoN(packageId); // !E_SUCCESS for DB fail and query fail + SysTryReturn(NID_APP, pPackageInfo != null, null, E_APP_NOT_INSTALLED, "[%s] Propagating.", GetErrorMessage(E_APP_NOT_INSTALLED)); + + const _PackageInfoImpl* pPkgInfoImpl = _PackageInfoImpl::GetInstance(pPackageInfo); + SysTryReturn(NID_APP, pPkgInfoImpl != null, null, E_SYSTEM, + "[%s] A system error has been occurred. failed to get _PackageInfoImpl.", GetErrorMessage(E_SYSTEM)); + + String rootPath = pPkgInfoImpl->GetAppRootPath(); + rootPath += L"/"; + + // Common creation part + std::unique_ptr<_AppSettingImpl> pAppSettingImpl(new (std::nothrow) _AppSettingImpl()); + SysTryReturn(NID_APP, pAppSettingImpl != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pAppSettingImpl->ConstructByAppPath(packageId, rootPath); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + pAppSettingInstance = _AppSettingImpl::CreateAppSetting(); + SysTryCatch(NID_APP, pAppSettingInstance != null, , E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + _AppSettingImpl::SetImplInstance(*pAppSettingInstance, *pAppSettingImpl.release()); + + pKeyStr = new (std::nothrow) String(packageId); + SysTryCatch(NID_APP, pKeyStr != null, , E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = __stringToInstanceMap.Add(*pKeyStr, *pAppSettingInstance); + SysTryCatch(NID_APP, r != E_OUT_OF_MEMORY, , r, "[%s] Memory allocation failed.", GetErrorMessage(r)); + SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] A system error has been occurred.", GetErrorMessage(E_SYSTEM)); + + return pAppSettingInstance; + +CATCH: + delete pAppSettingInstance; + delete pPackageInfo; + return null; +} + +result +_AppSettingImpl::_MutiInstanceManager::ReleaseInstanceByAppId(const AppId& appId) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_APPSETTING); + SysTryReturnResult(NID_APP, !IsFailed(r), E_PRIVILEGE_DENIED, + "The application does not have the privilege to call this method."); + + // Convert AppId to package type id. + String packageId; + appId.SubString(0, APP_ID_LENTH, packageId); + + AppSetting* pAppSetting = static_cast(__stringToInstanceMap.GetValue(packageId)); + if (pAppSetting) + { + if (pDBusConnection) + { + _AppSettingImpl* pThisAppSettingImpl = _AppSettingImpl::GetInstance(*pAppSetting); + dbus_connection_remove_filter(pDBusConnection, HandleDBusMessage, pThisAppSettingImpl); + } + __stringToInstanceMap.Remove(packageId, true); // Delete item instance and remove item from __stringToInstanceMap + return E_SUCCESS; + } + else + { + return E_OBJ_NOT_FOUND; + } +} + +result +_AppSettingImpl::_MutiInstanceManager::ReleaseOtherAppInstances(void) +{ + if (pDBusConnection) + { // Iterate all element and remove correspond dbus filter + std::unique_ptr pEnum(__stringToInstanceMap.GetMapEnumeratorN()); + if (pEnum.get()) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + AppSetting* pAppSetting = null; + pAppSetting = static_cast(pEnum->GetValue()); + _AppSettingImpl* pThisAppSettingImpl = _AppSettingImpl::GetInstance(*pAppSetting); + dbus_connection_remove_filter(pDBusConnection, HandleDBusMessage, pThisAppSettingImpl); + } + } + } + __stringToInstanceMap.RemoveAll(true); + return E_SUCCESS; +} + +class _SettingItem + : public Object +{ +public: + _SettingItem(Object* pItemValue, int min, int max, xmlNodePtr pItemXmlNode) + : __pValue(pItemValue) + , __min(min) + , __max(max) + , __pXmlNode(pItemXmlNode) + {} + ~_SettingItem(void) + { + delete __pValue; + } + Object* GetValue(void) + { + return __pValue; + } + const Object* GetValue(void) const + { + return __pValue; + } + int GetMin(void) + { + return __min; + } + int GetMax(void) + { + return __max; + } + xmlNodePtr GetXmlNode(void) + { + return __pXmlNode; + } +private: + _SettingItem(void); + _SettingItem(const _SettingItem& rhs); + _SettingItem& operator =(const _SettingItem& rhs); +private: + Object* __pValue; + int __min; + int __max; + xmlNodePtr __pXmlNode; +}; + +class _ReverseStringComparer + : public Tizen::Base::Collection::IComparer +{ +public: + _ReverseStringComparer(void) {}; + virtual ~_ReverseStringComparer(void) {}; + virtual result Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const + { + const String& objString1 = static_cast(obj1); + const String& objString2 = static_cast(obj2); + cmp = objString2.CompareTo(objString1); // reverse + return E_SUCCESS; + } +}; + +_AppSettingImpl::_AppSettingImpl(void) + : __oldVersionInstance(false) + , __pEventListener(null) + , __pDoc(null) +{ + +} + +_AppSettingImpl::~_AppSettingImpl(void) +{ + if (__pDoc) + { + xmlFreeDoc(__pDoc); + __pDoc = null; + } + __settingContainer.RemoveAll(true); +} + +_AppSettingImpl* +_AppSettingImpl::GetInstance(void) +{ + ClearLastResult(); + result r = E_SUCCESS; + + if (pAppSettingImplInstance == null) + { + pAppSettingImplInstance = new (std::nothrow) _AppSettingImpl(); + SysTryReturn(NID_APP, pAppSettingImplInstance != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + // Get current application context AppId + App* pApp = App::GetInstance(); + SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] A system error has been occurred. App::GetInstance() failed", + GetErrorMessage(E_SYSTEM)); + String appId; + appId = pApp->GetAppId(); + r = pAppSettingImplInstance->Construct(appId); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + } + return pAppSettingImplInstance; + +CATCH: + delete pAppSettingImplInstance; + pAppSettingImplInstance = null; + return null; +} + +AppSetting* +_AppSettingImpl::GetInstance(const Tizen::Base::String& version) +{ + ClearLastResult(); + //result r = E_SUCCESS; + + static _MutiInstanceManager multiInstanceManager; + AppSetting* pVersionAppSetting = multiInstanceManager.GetInstance(version); + SysTryReturn(NID_APP, pVersionAppSetting != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + return pVersionAppSetting; +} + +AppSetting* +_AppSettingImpl::GetInstanceByAppId(const AppId& appId) +{ + ClearLastResult(); + + AppSetting* pAppSettingByAppId = __appIdMultiInstanceMgr.GetInstanceByAppId(appId); + return pAppSettingByAppId; +} + +result +_AppSettingImpl::ReleaseInstanceByAppId(const AppId& appId) +{ + return __appIdMultiInstanceMgr.ReleaseInstanceByAppId(appId); +} + +result +_AppSettingImpl::ReleaseOtherAppInstances(void) +{ + return __appIdMultiInstanceMgr.ReleaseOtherAppInstances(); +} + +Tizen::Base::Collection::IList* +_AppSettingImpl::GetAppSettingVersionListN(void) +{ + result r = E_SUCCESS; + ArrayList* pVersionList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pVersionList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + r = pVersionList->Construct(); + SysTryReturn(NID_APP, !IsFailed(r), null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + // Iterate file and add to list + String dirPath = _AppInfo::GetAppRootPath() + RESOUCE_FILE_PATH; + Directory dir; + r = dir.Construct(dirPath); + SysTryReturn(NID_APP, !IsFailed(r), null, E_SYSTEM, "[%s] A system error has been occurred. Directory construction failed.", + GetErrorMessage(E_SYSTEM)); + + std::unique_ptr pDirEnum(dir.ReadN()); + SysTryReturn(NID_APP, pDirEnum != null, null, E_SYSTEM, + "[%s] A system error has been occurred. Directory enumerator getting failed.", GetErrorMessage(E_SYSTEM)); + + String settingName(RESOUCE_FILE_NAME); + String settingExt(RESOUCE_FILE_EXT); + while (pDirEnum->MoveNext() == E_SUCCESS) + { + DirEntry dirEntry = pDirEnum->GetCurrentDirEntry(); + if (!dirEntry.IsDirectory()) + { + String fullName = dirEntry.GetName(); + // Check name and extension to getting valid one + String name; + String ext; + const int extLength = settingExt.GetLength(); + const int posStart = settingName.GetLength(); + const int posEnd = fullName.GetLength() - extLength; + if (posStart >= posEnd) + { + continue; + } + fullName.SubString(0, posStart, name); + fullName.SubString(posEnd, ext); + if ((name == settingName) && (ext == settingExt)) + { + String version; + if (E_SUCCESS == fullName.SubString(posStart, posEnd-posStart, version)) + { + String* pVersionStr = new (std::nothrow) String(version); + SysTryReturn(NID_APP, pVersionStr != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + pVersionList->Add(*pVersionStr); + } + } + } + } + + if (pVersionList->GetCount()) + { + static _ReverseStringComparer strComparator; + pVersionList->Sort(strComparator); + pVersionList->RemoveAt(0); // remove latest version from list. + } + + return pVersionList; +} + +result +_AppSettingImpl::GetValue(const Tizen::Base::String& id, bool& value) const +{ + const Object* pObject = __settingContainer.GetValue(id); + SysTryReturnResult(NID_APP, pObject != null, E_OBJ_NOT_FOUND, "Specified id is not found in the application setting"); + const _SettingItem* pItem = dynamic_cast(pObject); + SysTryReturnResult(NID_APP, pItem != null, E_TYPE_MISMATCH, "Type mismatch for instance of id."); + const Boolean* pBoolean = dynamic_cast(pItem->GetValue()); + SysTryReturnResult(NID_APP, pBoolean != null, E_TYPE_MISMATCH, + "Type mismatch between requested type bool and object type of %ls.", id.GetPointer()); + value = pBoolean->ToBool(); + + return E_SUCCESS; +} + +result +_AppSettingImpl::GetValue(const Tizen::Base::String& id, int& value) const +{ + const Object* pObject = __settingContainer.GetValue(id); + SysTryReturnResult(NID_APP, pObject != null, E_OBJ_NOT_FOUND, "Specified id is not found in the application setting"); + const _SettingItem* pItem = dynamic_cast(pObject); + SysTryReturnResult(NID_APP, pItem != null, E_TYPE_MISMATCH, "Type mismatch for instance of id."); + const Integer* pInteger = dynamic_cast(pItem->GetValue()); + SysTryReturnResult(NID_APP, pInteger != null, E_TYPE_MISMATCH, + "Type mismatch between requested type int and object type of %ls.", id.GetPointer()); + value = pInteger->ToInt(); + + return E_SUCCESS; +} + +result +_AppSettingImpl::GetValue(const Tizen::Base::String& id, Tizen::Base::String& value) const +{ + const Object* pObject = __settingContainer.GetValue(id); + SysTryReturnResult(NID_APP, pObject != null, E_OBJ_NOT_FOUND, "Specified id is not found in the application setting"); + const _SettingItem* pItem = dynamic_cast(pObject); + SysTryReturnResult(NID_APP, pItem != null, E_TYPE_MISMATCH, "Type mismatch for instance of id."); + const String* pString = dynamic_cast(pItem->GetValue()); + SysTryReturnResult(NID_APP, pString != null, E_TYPE_MISMATCH, + "Type mismatch between requested type String and object type of %ls.", id.GetPointer()); + value = *pString; + + return E_SUCCESS; +} + +result +_AppSettingImpl::SetValue(const Tizen::Base::String& id, bool value, bool save) +{ + Object* pObject = __settingContainer.GetValue(id); + SysTryReturnResult(NID_APP, pObject != null, E_OBJ_NOT_FOUND, "Specified id is not found in the application setting"); + _SettingItem* pItem = dynamic_cast<_SettingItem*>(pObject); + SysTryReturnResult(NID_APP, pItem != null, E_TYPE_MISMATCH, "Type mismatch for instance of id."); + Boolean* pBoolean = dynamic_cast(pItem->GetValue()); + SysTryReturnResult(NID_APP, pBoolean != null, E_TYPE_MISMATCH, + "Type mismatch between requested type bool and object type of %ls.", id.GetPointer()); + *pBoolean = value; + + static const String strTrue(L"true"); + static const String strFalse(L"false"); + const String& strValue = value ? strTrue : strFalse; + UpdateProperty(pItem->GetXmlNode(), strValue); + if (save) + { + Save(); + static const String strIntTrue(L"1"); + static const String strIntFalse(L"0"); + SendMessage(id, value ? strIntTrue : strIntFalse, true); + } + if (__pEventListener) + { + __pEventListener->OnAppSettingChanged(id); + } + + return E_SUCCESS; +} + +result +_AppSettingImpl::SetValue(const Tizen::Base::String& id, int value, bool save) +{ + Object* pObject = __settingContainer.GetValue(id); + SysTryReturnResult(NID_APP, pObject != null, E_OBJ_NOT_FOUND, "Specified id is not found in the application setting"); + _SettingItem* pItem = dynamic_cast<_SettingItem*>(pObject); + SysTryReturnResult(NID_APP, pItem != null, E_TYPE_MISMATCH, "Type mismatch for instance of id."); + Integer* pInteger = dynamic_cast(pItem->GetValue()); + SysTryReturnResult(NID_APP, pInteger != null, E_TYPE_MISMATCH, + "Type mismatch between requested type int and object type of %ls.", id.GetPointer()); + + SysTryReturnResult(NID_APP, (pItem->GetMin() <= value), E_OUT_OF_RANGE, "value(%d) is less than minimum range(%d).", + value, pItem->GetMin()); + SysTryReturnResult(NID_APP, (pItem->GetMax() >= value), E_OUT_OF_RANGE, "value(%d) is greater than maximum range(%d).", + value, pItem->GetMax()); + *pInteger = value; + + String strValue = pInteger->ToString(); + UpdateProperty(pItem->GetXmlNode(), strValue); + if (save) + { + Save(); + SendMessage(id, strValue, true); + } + if (__pEventListener) + { + __pEventListener->OnAppSettingChanged(id); + } + + return E_SUCCESS; +} + +result +_AppSettingImpl::SetValue(const Tizen::Base::String& id, const Tizen::Base::String& value, bool save) +{ + Object* pObject = __settingContainer.GetValue(id); + SysTryReturnResult(NID_APP, pObject != null, E_OBJ_NOT_FOUND, "Specified id is not found in the application setting"); + _SettingItem* pItem = dynamic_cast<_SettingItem*>(pObject); + SysTryReturnResult(NID_APP, pItem != null, E_TYPE_MISMATCH, "Type mismatch for instance of id."); + String* pString = dynamic_cast(pItem->GetValue()); + SysTryReturnResult(NID_APP, pString != null, E_TYPE_MISMATCH, + "Type mismatch between requested type String and object type of %ls.", id.GetPointer()); + + SysTryReturnResult(NID_APP, pItem->GetMin() <= value.GetLength(), E_OUT_OF_RANGE, + "value length(%d) less than minimum length(%d).", value.GetLength(), pItem->GetMin()); + SysTryReturnResult(NID_APP, pItem->GetMax() >= value.GetLength(), E_OUT_OF_RANGE, + "value length(%d) greater than maximum range(%d).", value.GetLength(), pItem->GetMax()); + *pString = value; + + UpdateProperty(pItem->GetXmlNode(), *pString); + if (save) + { + Save(); + SendMessage(id, *pString, false); + } + if (__pEventListener) + { + __pEventListener->OnAppSettingChanged(id); + } + + return E_SUCCESS; +} + +result +_AppSettingImpl::SetAppSettingEventListener(IAppSettingEventListener* pListener) +{ + __pEventListener = pListener; + return E_SUCCESS; +} + +_AppSettingImpl* +_AppSettingImpl::GetInstance(AppSetting& appSetting) +{ + return appSetting.__pAppSettingImpl; +} + +const _AppSettingImpl* +_AppSettingImpl::GetInstance(const AppSetting& appSetting) +{ + return appSetting.__pAppSettingImpl; +} + +result +_AppSettingImpl::Construct(const AppId& correspondAppId, const String& version) +{ + result r = E_SUCCESS; + if (version.GetLength() > 0) + { + __oldVersionInstance = true; + } + correspondAppId.SubString(0, APP_ID_LENTH, __correspondAppId); // Use 10 char id value. + + __filePath = _AppInfo::GetAppRootPath() + RESOUCE_FILE_PATH; + __filePath += RESOUCE_FILE_NAME; + if (version.GetLength()) + { + __filePath += version; + } + __filePath += RESOUCE_FILE_EXT; + + r = __settingContainer.Construct(); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + if (!__oldVersionInstance) + { + SysTryReturnResult(NID_APP, InitizlizeDBus(), E_SYSTEM, "A system error has been occurred. DBus initialization failed."); + } + r = Load(); + SysTryReturnResult(NID_APP, !IsFailed(r), E_SYSTEM, "A system error has been occurred. Loading procedure failed."); + return r; +} + +result +_AppSettingImpl::ConstructByAppPath(const AppId& correspondAppId, const Tizen::Base::String& appRootPath) +{ + result r = E_SUCCESS; + SysTryReturn(NID_APP, !appRootPath.IsEmpty(), E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used. appRootPath length is 0.", GetErrorMessage(E_INVALID_ARG)); + + correspondAppId.SubString(0, APP_ID_LENTH, __correspondAppId); // Use 10 char id value. + __filePath = appRootPath + RESOUCE_FILE_PATH; + __filePath += RESOUCE_FILE_NAME; + __filePath += RESOUCE_FILE_EXT; + + r = __settingContainer.Construct(); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + SysTryReturnResult(NID_APP, InitizlizeDBus(), E_SYSTEM, "A system error has been occurred. DBus initialization failed."); + r = Load(); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +_AppSettingImpl::Load(void) +{ + SysTryReturnResult(NID_APP, File::IsFileExist(__filePath), E_OBJ_NOT_FOUND, + "The instance of specified AppId does not have setting information."); + + result r = E_SUCCESS; + std::unique_ptr pfilePath(Tizen::Base::Utility::StringUtil::StringToUtf8N(__filePath)); + SysTryReturnResult(NID_APP, pfilePath != null, E_OUT_OF_MEMORY, "Memory allocation failed. File path conversion failed."); + + __pDoc = xmlParseFile(reinterpret_cast(pfilePath->GetPointer())); + SysTryReturnResult(NID_APP, __pDoc != null, E_SYSTEM, + "A system error has been occurred. Can not parse xml file: %ls", __filePath.GetPointer()); + + xmlNodePtr rootNodePtr = xmlDocGetRootElement(__pDoc); + SysTryReturnResult(NID_APP, rootNodePtr != null, E_SYSTEM, "A system error has been occurred. Can not find root node"); + + VisitNode(rootNodePtr); + + return r; +} + +result +_AppSettingImpl::Save(void) +{ + static const int XML_SAVE_FAILED = -1; + static const int XML_SAVE_FORMAT = 1; + + SysTryReturnResult(NID_APP, __pDoc != null, E_SYSTEM, + "A system error has been occurred. XML Document not valid so can not save it."); + std::unique_ptr pfilePath(Tizen::Base::Utility::StringUtil::StringToUtf8N(__filePath)); + SysTryReturnResult(NID_APP, pfilePath != null, E_OUT_OF_MEMORY, "Memory allocation failed. File path conversion failed."); + + int result = xmlSaveFormatFile(reinterpret_cast(pfilePath->GetPointer()), __pDoc, XML_SAVE_FORMAT); + SysTryReturnResult(NID_APP, result != XML_SAVE_FAILED, E_SYSTEM, "A system error has been occurred. Document saving failed."); + + return E_SUCCESS; +} + +void +_AppSettingImpl::VisitNode(xmlNodePtr pCurrentNode) +{ + for (xmlNodePtr nodePtr = pCurrentNode; nodePtr != null; nodePtr = nodePtr->next) // Visit sibling node + { + // Check node name and add to collection. + if (nodePtr->type == XML_ELEMENT_NODE) + { + CheckNodeNameAndAddToCollection(nodePtr); + } + // Visit child node + VisitNode(nodePtr->children); + } +} + +void +_AppSettingImpl::CheckNodeNameAndAddToCollection(xmlNodePtr pNode) +{ + static const char* pPropId = "id"; + static const char* pPropValue = "value"; + + // 1. Get type (bool, integer, string, expandlist) + _ElementType detectedType = GetElementType(pNode); + + // Make item and add to collection. + if (detectedType != ELEMENT_INVALID) + { + // 2. Get "id" + xmlChar* pId = xmlGetProp(pNode, reinterpret_cast(pPropId)); + if (pId) + { + int min = 0; + int max = 255; + + std::unique_ptr pStrId(new (std::nothrow) String(reinterpret_cast(pId))); + SysTryReturnVoidResult(NID_APP, pStrId, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + xmlFree(pId); + + if (pStrId) + { // 3. Get min(length), max(length) value + if ((detectedType == ELEMENT_INTEGER) || (detectedType == ELEMENT_STRING)) + { + GetMinMaxValue(pNode, detectedType, min, max); + } + // 4. Get "value" + String strValue; + bool validValue = false; + xmlChar* pValue = xmlGetProp(pNode, reinterpret_cast(pPropValue)); + if (pValue) + { + strValue = String(reinterpret_cast(pValue)); + xmlFree(pValue); + pValue = null; + validValue = true; + } + // 5. Create value object from value + Object* pValueObject = GetValueObjectN(detectedType, strValue, validValue); + if (pValueObject) + { + _SettingItem* pSettingItem = new (std::nothrow) _SettingItem(pValueObject, min, max, pNode); + SysTryReturnVoidResult(NID_APP, pSettingItem, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + if (pSettingItem) + { // 6. Add item to container + SysLog(NID_APP, "AppSetting item adding: ID=%ls min=%d max=%d Value=%ls", + pStrId->GetPointer(), min, max, strValue.GetPointer()); + __settingContainer.Add(*pStrId.release(), *pSettingItem); + } + else + { + SysLog(NID_APP, "Failed create new _SettingItem"); + } + } + } // pStrId + } // pId + } // ELEMET_INVALID +} + +_ElementType +_AppSettingImpl::GetElementType(xmlNodePtr pNode) +{ + const xmlChar* pElementBool = reinterpret_cast("bool"); + const xmlChar* pElementInteger = reinterpret_cast("integer"); + const xmlChar* pElementString = reinterpret_cast("string"); + const xmlChar* pElementExpandlist = reinterpret_cast("expandlist"); + + _ElementType type = ELEMENT_INVALID; + if (xmlStrcmp(pNode->name, pElementBool) == 0) + { + type = ELEMENT_BOOL; + } + else + if (xmlStrcmp(pNode->name, pElementInteger) == 0) + { + type = ELEMENT_INTEGER; + } + else + if (xmlStrcmp(pNode->name, pElementString) == 0) + { + type = ELEMENT_STRING; + } + else + if (xmlStrcmp(pNode->name, pElementExpandlist) == 0) + { + type = ELEMENT_EXPANDLIST; + } + + return type; +} + +void +_AppSettingImpl::GetMinMaxValue(xmlNodePtr pNode, _ElementType type, int& min, int& max) +{ + const xmlChar* pPropMin = reinterpret_cast("min"); + const xmlChar* pPropMax = reinterpret_cast("max"); + const xmlChar* pPropMinLength = reinterpret_cast("minlength"); + const xmlChar* pPropMaxLength = reinterpret_cast("maxlength"); + + if (type == ELEMENT_INTEGER) + { + xmlChar* pStrMin = xmlGetProp(pNode, pPropMin); + if (pStrMin) + { + Integer::Parse(reinterpret_cast(pStrMin), min); + xmlFree(pStrMin); + } + else + { + SysLog(NID_APP, "Failed to get 'min' value."); + } + + xmlChar* pStrMax = xmlGetProp(pNode, pPropMax); + if (pStrMax) + { + Integer::Parse(reinterpret_cast(pStrMax), max); + xmlFree(pStrMax); + } + else + { + SysLog(NID_APP, "Failed to get 'max' value."); + } + } + else + if (type == ELEMENT_STRING) + { + xmlChar* pStrMin = xmlGetProp(pNode, pPropMinLength); + if (pStrMin) + { + Integer::Parse(reinterpret_cast(pStrMin), min); + xmlFree(pStrMin); + } + else + { + SysLog(NID_APP, "Failed to get 'minlength' value."); + } + + xmlChar* pStrMax = xmlGetProp(pNode, pPropMaxLength); + if (pStrMax) + { + Integer::Parse(reinterpret_cast(pStrMax), max); + xmlFree(pStrMax); + } + else + { + SysLog(NID_APP, "Failed to get 'maxlength' value."); + } + } + else + { + SysLog(NID_APP, "Invalid element type."); + } +} + +Object* +_AppSettingImpl::GetValueObjectN(_ElementType type, String& strValue, bool validValue) +{ + const String strTrue(L"true"); + Object* pValueObject = null; + + switch (type) + { + case ELEMENT_BOOL: + { + bool valueBool = false; + if (validValue) + { + if (strValue == strTrue) + { + valueBool = true; + } + } + pValueObject = new (std::nothrow) Boolean(valueBool); + SysTryReturn(NID_APP, pValueObject != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + } + break; + + case ELEMENT_INTEGER: + { + int valueInteger = 0; + if (validValue) + { + Integer::Parse(strValue, valueInteger); + } + pValueObject = new (std::nothrow) Integer(valueInteger); + SysTryReturn(NID_APP, pValueObject != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + } + break; + + case ELEMENT_STRING: + case ELEMENT_EXPANDLIST: + { + String* pStringObject = new (std::nothrow) String; + SysTryReturn(NID_APP, pStringObject != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + if (pStringObject && validValue) + { + *pStringObject = strValue; + } + pValueObject = pStringObject; + } + break; + + case ELEMENT_INVALID: + // It already validate by caller; + SysLog(NID_APP, "Invalid element type."); + break; + } + + return pValueObject; +} + +bool +_AppSettingImpl::UpdateProperty(xmlNodePtr pNode, const String& value) +{ + const xmlChar* pPropValue = reinterpret_cast("value"); + + std::unique_ptr pBuf(Tizen::Base::Utility::StringUtil::StringToUtf8N(value)); + if (pBuf) + { + xmlAttrPtr attrPtr = xmlSetProp(pNode, pPropValue, reinterpret_cast(pBuf->GetPointer())); + if (attrPtr) + { + return true; + } + } + else + { + SysLog(NID_APP, "StringToUtf8N is failed."); + } + return false; +} + +bool +_AppSettingImpl::InitizlizeDBus(void) +{ + DBusError error; + dbus_error_init(&error); + + if (pDBusConnection == null) + { + char rule[MAX_LOCAL_BUFSIZE]; + pDBusConnection = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error); + if (pDBusConnection == null) + { + SysLog(NID_APP, "Fail to connect to the D-BUS daemon: %s", error.message); + dbus_error_free(&error); + return false; + } + dbus_connection_setup_with_g_main(pDBusConnection, null); + + snprintf(rule, MAX_LOCAL_BUFSIZE, "path='%s',type='signal',interface='%s'", DBUS_PATH, DBUS_SIGNAL_INTERFACE); + dbus_bus_add_match(pDBusConnection, rule, &error); + if (dbus_error_is_set(&error)) + { + SysLog(NID_APP, "Fail to add match : %s", error.message); + dbus_error_free(&error); + return false; + } + } + + // this value is vary by AppSetting instance for proper handling. + // Should be explicit remove filter on ReleaseInstanceByAppId. + if (dbus_connection_add_filter(pDBusConnection, HandleDBusMessage, this, NULL) == FALSE) + { + SysLog(NID_APP, "Fail to add filter : %s", error.message); + dbus_error_free(&error); + return false; + } + return true; +} + +DBusHandlerResult +_AppSettingImpl::HandleDBusMessage(DBusConnection* connection, DBusMessage* message, void* user_data) +{ + int my_pid = getpid(); + int sender_pid = 0; + char* pId = NULL; + char* pValue = NULL; + + DBusError error; + dbus_error_init(&error); + + _AppSettingImpl* pAppSettingImpl = static_cast<_AppSettingImpl*>(user_data); + SysTryLogReturn(NID_APP, pAppSettingImpl != null, DBUS_HANDLER_RESULT_HANDLED, + "Not valid pAppSettingImpl from user_data"); + String signalString(DBUS_SIGNAL_PREFIX); + signalString += pAppSettingImpl->__correspondAppId; + std::unique_ptr pBufferSignal(Tizen::Base::Utility::StringUtil::StringToUtf8N(signalString)); + SysTryLogReturn(NID_APP, pBufferSignal != null, DBUS_HANDLER_RESULT_HANDLED, "pBufferSignal is not valid"); + const char* pCharBufferSignal = reinterpret_cast(pBufferSignal->GetPointer()); + + if (dbus_message_is_signal(message, DBUS_SIGNAL_INTERFACE, pCharBufferSignal)) + { + if (dbus_message_get_args(message, &error, + DBUS_TYPE_UINT32, &sender_pid, + DBUS_TYPE_STRING, &pId, + DBUS_TYPE_STRING, &pValue, + DBUS_TYPE_INVALID) == FALSE) + { + SysLog(NID_APP, "Fail to get data : %s", error.message); + dbus_error_free(&error); + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } + + if (sender_pid != 0 && my_pid != sender_pid) + { + pAppSettingImpl->SetValueFromDBusData(pId, pValue); + } + return DBUS_HANDLER_RESULT_HANDLED; + } + else + { + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; + } +} + +void +_AppSettingImpl::SetValueFromDBusData(const char* pId, const char* pValue) +{ + const String delimiter(L"|"); + String strId; + String strValue; + int indexOfDelimiter = 0; + + // Native Setting module send the key as "id|title" so need to get id part before the '|' character. + // Value is "INT|value" for check box and slider Or "STRING|value" so need to get right side value string. + String strOrg(pId); + strOrg.Trim(); + result r = strOrg.IndexOf(delimiter, 0, indexOfDelimiter); + SysTryReturnVoidResult(NID_APP, !IsFailed(r), r, "[%s] Propagating. Bus data parsing failed", GetErrorMessage(r)); + strOrg.SubString(0, indexOfDelimiter, strId); // Get left string of '|' + + strOrg = pValue; + strOrg.Trim(); + r = strOrg.IndexOf(delimiter, 0, indexOfDelimiter); + SysTryReturnVoidResult(NID_APP, !IsFailed(r), r, "[%s] Propagating. Bus data parsing failed", GetErrorMessage(r)); + strOrg.SubString(indexOfDelimiter+1, strValue); // Get right string of '|' + + const Object* pObject = __settingContainer.GetValue(strId); + if (pObject) + { + const _SettingItem* pItem = dynamic_cast(pObject); + SysTryReturnVoidResult(NID_APP, pItem != null, E_SYSTEM, "[%s] A system error has been occurred. Casting failed to item.", + GetErrorMessage(E_SYSTEM)); + const Boolean* pBoolean = dynamic_cast(pItem->GetValue()); + if (pBoolean) + { + static const String strFalse(L"0"); + bool valueBool = true; + + if (strValue == strFalse) + { + valueBool = false; + } + SetValue(strId, valueBool, false); + return; + } + const Integer* pInteger = dynamic_cast(pItem->GetValue()); + if (pInteger) + { + int valueInteger = 0; + Integer::Parse(strValue, valueInteger); + SetValue(strId, valueInteger, false); + return; + } + const String* pString = dynamic_cast(pItem->GetValue()); + if (pString) + { + SetValue(strId, strValue, false); + return; + } + SysLog(NID_APP, "Failed determin value type for id=%s", pId); + } + else + { + SysLog(NID_APP, "Failed find value for id=%s", pId); + } +} + +bool +_AppSettingImpl::SendMessage(const String& id, const String& value, bool intType) +{ + if (__oldVersionInstance) + { + return true; // NOP for old version instance. + } + + if (!pDBusConnection) + { + SysLog(NID_APP, "DBus connection invalid"); + return false; + } + + bool result = true; + const String strRightOfId(L"|N/A"); + const String strLeftOfValueIntType(L"INT|"); + const String strLeftOfValueStrType(L"STRING|"); + + String strId = id + strRightOfId; + String strValue; + if (intType) + { + strValue = strLeftOfValueIntType; + } + else + { + strValue = strLeftOfValueStrType; + } + strValue += value; + String signalString(DBUS_SIGNAL_PREFIX); + signalString += __correspondAppId; + + std::unique_ptr pBufferId(Tizen::Base::Utility::StringUtil::StringToUtf8N(strId)); + std::unique_ptr pBufferValue(Tizen::Base::Utility::StringUtil::StringToUtf8N(strValue)); + std::unique_ptr pBufferSignal(Tizen::Base::Utility::StringUtil::StringToUtf8N(signalString)); + if (pBufferId && pBufferValue && pBufferSignal) + { + int sender_pid = getpid(); + const char* pCharBufferId = reinterpret_cast(pBufferId->GetPointer()); + const char* pCharBufferValue = reinterpret_cast(pBufferValue->GetPointer()); + const char* pCharBufferSignal = reinterpret_cast(pBufferSignal->GetPointer()); + + DBusMessage* pMessageWihtAppId = dbus_message_new_signal(DBUS_PATH, DBUS_SIGNAL_INTERFACE, pCharBufferSignal); + if (dbus_message_append_args(pMessageWihtAppId, + DBUS_TYPE_UINT32, &sender_pid, + DBUS_TYPE_STRING, &pCharBufferId, + DBUS_TYPE_STRING, &pCharBufferValue, + DBUS_TYPE_INVALID) == FALSE) + { + SysLog(NID_APP, "DBus connection invalid"); + result = false; + } + + if (dbus_connection_send(pDBusConnection, pMessageWihtAppId, NULL) == FALSE) + { + SysLog(NID_APP, "Fail to send message"); + result = false; + } + + dbus_connection_flush(pDBusConnection); + dbus_message_unref(pMessageWihtAppId); + } + else + { + SysLog(NID_APP, "System error: memory full ?"); + } + + return result; +} + +AppSetting* +_AppSettingImpl::CreateAppSetting(void) +{ + AppSetting* pAppSetting = new (std::nothrow) AppSetting; + SysTryReturn(NID_APP, pAppSetting != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + return pAppSetting; +} + +void +_AppSettingImpl::SetImplInstance(AppSetting& appSetting, _AppSettingImpl& impl) +{ + appSetting.__pAppSettingImpl = &impl; +} + +} } // Tizen::App diff --git a/src/app/FApp_AppSettingImpl.h b/src/app/FApp_AppSettingImpl.h new file mode 100644 index 0000000..15b559e --- /dev/null +++ b/src/app/FApp_AppSettingImpl.h @@ -0,0 +1,129 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppSetting.h + * @brief This is the header file for the %_AppSettingImpl class. + * + * This header file contains the declarations of the %_AppSettingImpl class. + */ + +#ifndef _FAPP_INTERNAL_APP_SETTING_IMPL_H_ +#define _FAPP_INTERNAL_APP_SETTING_IMPL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace App +{ + +enum _ElementType { ELEMENT_INVALID, ELEMENT_BOOL, ELEMENT_INTEGER, ELEMENT_STRING, ELEMENT_EXPANDLIST }; + +class _AppSettingImpl + : public Tizen::Base::Object +{ +public: + static _AppSettingImpl* GetInstance(void); + static AppSetting* GetInstance(const Tizen::Base::String& version); + static AppSetting* GetInstanceByAppId(const AppId& appId); + static result ReleaseInstanceByAppId(const AppId& appId); + static result ReleaseOtherAppInstances(void); + static Tizen::Base::Collection::IList* GetAppSettingVersionListN(void); + result GetValue(const Tizen::Base::String& id, bool& value) const; + result GetValue(const Tizen::Base::String& id, int& value) const; + result GetValue(const Tizen::Base::String& id, Tizen::Base::String& value) const; + result SetValue(const Tizen::Base::String& id, bool value, bool save = true); + result SetValue(const Tizen::Base::String& id, int value, bool save = true); + result SetValue(const Tizen::Base::String& id, const Tizen::Base::String& value, bool save = true); + result SetAppSettingEventListener(IAppSettingEventListener* pListener); + + // + // Gets the implementation. + // + // @return The implementation + // @param[in] The interface instance pointer + // @since 2.1 + // + static _AppSettingImpl* GetInstance(AppSetting& appSetting); + + // + // Gets the implementation. + // + // @return The implementation + // @param[in] The interface instance pointer + // @since 2.1 + // + static const _AppSettingImpl* GetInstance(const AppSetting& appSetting); + + _AppSettingImpl(void); + virtual ~_AppSettingImpl(void); + static AppSetting* CreateAppSetting(void); + static void SetImplInstance(AppSetting& appSetting, _AppSettingImpl& impl); + +private: + result Construct(const AppId& correspondAppId, const Tizen::Base::String& version = L""); + result ConstructByAppPath(const AppId& correspondAppId, const Tizen::Base::String& appRootPath); + result Load(void); + result Save(void); + void VisitNode(xmlNodePtr pCurrentNode); + void CheckNodeNameAndAddToCollection(xmlNodePtr pNode); + _ElementType GetElementType(xmlNodePtr pNode); + void GetMinMaxValue(xmlNodePtr pNode, _ElementType type, int& min, int& max); + Object* GetValueObjectN(_ElementType type, Tizen::Base::String& strValue, bool validValue); + bool UpdateProperty(xmlNodePtr pNode, const Tizen::Base::String& value); + bool InitizlizeDBus(void); + static DBusHandlerResult HandleDBusMessage(DBusConnection* connection, DBusMessage* message, void* user_data); + void SetValueFromDBusData(const char* pId, const char* pValue); + bool SendMessage(const Tizen::Base::String& id, const Tizen::Base::String& value, bool intType); + + _AppSettingImpl(const _AppSettingImpl& rhs); + _AppSettingImpl& operator =(const _AppSettingImpl& rhs); + +private: + bool __oldVersionInstance; + IAppSettingEventListener* __pEventListener; + xmlDocPtr __pDoc; + AppId __correspondAppId; + Tizen::Base::String __filePath; + Tizen::Base::Collection::HashMap __settingContainer; + + class _MutiInstanceManager + { + public: + _MutiInstanceManager(void); + ~_MutiInstanceManager(void); + AppSetting* GetInstance(const Tizen::Base::String& version); + AppSetting* GetInstanceByAppId(const AppId& appId); + result ReleaseInstanceByAppId(const AppId& appId); + result ReleaseOtherAppInstances(void); + private: + Tizen::Base::Collection::HashMap __stringToInstanceMap; + }; + static _MutiInstanceManager __appIdMultiInstanceMgr; + + friend class AppSetting; +}; // _AppSettingImpl +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_SETTING_IMPL_H_ diff --git a/src/app/FApp_Aul.cpp b/src/app/FApp_Aul.cpp new file mode 100644 index 0000000..e869903 --- /dev/null +++ b/src/app/FApp_Aul.cpp @@ -0,0 +1,579 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_Aul.cpp + * @brief This is the implementation for the _Aul.cpp class. + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include "FAppPkg_PackageManagerImpl.h" +#include "FApp_Types.h" +#include "FApp_Aul.h" +#include "FApp_TemplateUtil.h" + +#ifdef __cplusplus +extern "C" { +#endif +extern int aul_listen_app_dead_signal(int (* func)(int, void*), void* data); +#ifdef __cplusplus +} +#endif + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Utility; + +namespace +{ + +const char _DESKTOP_FILE_PATH[] = "/opt/share/applications"; +const char _DESKTOP_FILE_PATH_FORMAT[] = "%s/%s.desktop"; + +const char _X_TIZEN_SVC[] = "x-tizen-svc"; //X-TIZEN-SVC=[operation1] | [URI1] | [MIME1] ; [operation2] | [URI2] | [MIME2] +const int _MAX_TIZEN_SVC_DESC_LEN = 1024; + +const int _MAX_CATEGORY = 12; +const int _MAX_PACKAGE_ID_LENGTH = 10; + +// borrowed from app-svc/include/pri_key.h +#define APP_SVC_K_RES_VAL "__APP_SVC_K_RES_VAL__" + +} + +namespace Tizen { namespace App +{ + +struct _CategoryList +{ + const char category[_MAX_CATEGORY]; + _AppType type; +}; + +static const _CategoryList _CATEGORY_LIST[] = +{ + {"home-screen", _APP_TYPE_HOME_APP}, + {"lock-screen", _APP_TYPE_LOCK_APP}, + {"ime", _APP_TYPE_IME_APP}, +}; + +static const int _NUM_CATEGORY = sizeof(_CATEGORY_LIST) / sizeof(_CategoryList); + + +result +_Aul::SendResult(bundle* b, appsvc_result_val res) +{ + result r = E_SUCCESS; + + // to skip error handling, of appsvc_send_result, use aul_send_service_result() directly. + //int ret = appsvc_send_result(b, res); + + char tmp[32] = {0, }; + snprintf(tmp, 32, "%d", static_cast(res)); + appsvc_add_data(b, APP_SVC_K_RES_VAL, tmp); + + int ret = aul_send_service_result(b); + + switch (ret) + { + case AUL_R_EINVAL: + r = E_INVALID_ARG; + SysLogException(NID_APP, r, "Invalid result bundle."); + break; + + case AUL_R_ECOMM: + r = E_SYSTEM; + SysLogException(NID_APP, r, "Internal IPC error."); + break; + + case AUL_R_ERROR: + r = E_SYSTEM; + SysLogException(NID_APP, r, "General error."); + break; + + default: + SysLog(NID_APP, "SendResult() ok"); + break; + } + + return r; +} + + +bool +_Aul::IsRunning(const AppId& appId, const String& exeName) +{ + char slpPackageName[MAX_SLP_PACKAGE_ID] = {0, }; + bool isRunning = false; + + _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance(); + SysTryReturn(NID_APP, pPackageManagerImpl != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Invalid package instance."); + + pPackageManagerImpl->GetPackageName(appId, &exeName, slpPackageName, MAX_SLP_PACKAGE_ID); + + app_manager_is_running(slpPackageName, &isRunning); + + SysLog(NID_APP, "'%s' %s running now.", slpPackageName, (isRunning == true) ? "is" : "is NOT"); + + return isRunning; +} + +bool +_Aul::IsRunning(const String& packageName) +{ + bool isRunning = false; + std::unique_ptr pSlpPackageName(_StringConverter::CopyToCharArrayN(packageName)); + + app_manager_is_running(pSlpPackageName.get(), &isRunning); + + SysLog(NID_APP, "'%ls' %s running now.", packageName.GetPointer(), (isRunning) ? "is" : "is NOT"); + return isRunning; +} + + +void +_Aul::SetOnAppTerminatedCb(int (* pf_app_dead_handler)(int pid, void* pData), void* pData) +{ + aul_listen_app_dead_signal(pf_app_dead_handler, pData); + SysLog(NID_APP, "'app_dead_handler is set."); +} + + +result +_Aul::TerminateApplicationByPid(int pid) +{ + int ret_aul = aul_terminate_pid(pid); + result r = E_SUCCESS; + + switch (ret_aul) + { + case AUL_R_EINVAL: + r = E_INVALID_ARG; + SysLogException(NID_APP, r, "invaild pid.\n"); + break; + + case AUL_R_ECOMM: + r = E_SYSTEM; + SysLogException(NID_APP, r, "internal AUL IPC error.\n"); + break; + + case AUL_R_ERROR: + r = E_SYSTEM; + SysLogException(NID_APP, r, "general error.\n"); + break; + + default: + SysLog(NID_APP, "'%d' is terminated.", pid); + break; + } + + return r; +} + +result +_Aul::SetOomAdj(int pid, int adj) +{ + // set oom_adj to -17 for system service + result r = E_SUCCESS; + char buf[FILENAME_MAX]; + FILE *fP = NULL; + + snprintf(buf, FILENAME_MAX, "/proc/%d/oom_adj", pid); + fP = fopen(buf, "w"); + SysTryReturnResult(NID_APP, fP != NULL, E_SYSTEM, "oom_adj change failed with %s.", strerror(errno)); + + fprintf(fP, "%d", adj); + fclose(fP); + + return r; +} + +result +_Aul::SetPowerOffNotiListener( void (*powerOffCb)(void *pData), void *pData) +{ + int heyFd = heynoti_init(); + SysTryReturnResult(NID_APP, heyFd >= 0, E_SYSTEM, "heynoti_init failed."); + + int ret = heynoti_subscribe(heyFd, "power_off_start", powerOffCb, pData); + SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_subscribe failed."); + + ret = heynoti_attach_handler(heyFd); + SysTryReturnResult(NID_APP, ret >= 0, E_SYSTEM, "heynoti_attach_handler failed."); + + return E_SUCCESS; +} + +int +_Aul::GetAppType(const String& category) +{ + int ret = 0; + + HashMapT map; + map.Construct(); + + StringTokenizer strTok(category, L';'); + + String token; + while (strTok.HasMoreTokens()) + { + result r = strTok.GetNextToken(token); + if (r == E_SUCCESS) + { + map.Add(token, 0); + } + } + + SysLog(NID_APP, "%d category items .", map.GetCount()); + + String key; + + for (int i = 0; i < _NUM_CATEGORY; i++) + { + bool b = false; + key = _CATEGORY_LIST[i].category; + result r = map.ContainsKey(key, b); + if (r == E_SUCCESS && b) + { + ret |= _CATEGORY_LIST[i].type; + } + } + + return ret; +} + +bool _Aul::IsInstalled(const AppId& appId) +{ + String packageId; + packageId = _PackageManagerImpl::GetPackageIdByAppId(appId); + + return _PackageManagerImpl::GetInstance()->IsPackageInstalled(packageId); +} + +result +_Aul::_DesktopFile::MakePath(const AppId& appId, const String* pExeName, char* path, int size) +{ + SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, ""); + + char packageName[MAX_SLP_PACKAGE_ID] = {0, }; + result r = E_SUCCESS; + _PackageManagerImpl* pPackageManagerImpl = _PackageManagerImpl::GetInstance(); + SysTryReturnResult(NID_APP, pPackageManagerImpl, E_INVALID_STATE, "Invalid package manager instance."); + + r = pPackageManagerImpl->GetPackageName(appId, pExeName, packageName, MAX_SLP_PACKAGE_ID); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "%s", GetErrorMessage(r)); + + snprintf(path, size, _DESKTOP_FILE_PATH_FORMAT, _DESKTOP_FILE_PATH, packageName); + + return r; +} + +result +_Aul::_DesktopFile::UpdateService(const AppId& appId, const char* value) +{ + char path[FILENAME_MAX] = {0, }; + MakePath(appId, null, path, FILENAME_MAX); + + return UpdateField(path, _X_TIZEN_SVC, value); +} + + +result +_Aul::_DesktopFile::RemoveService(const AppId& appId, const char* operationOnlyValue) +{ + char path[FILENAME_MAX] = {0, }; + MakePath(appId, null, path, FILENAME_MAX); + + return UpdateField(path, _X_TIZEN_SVC, operationOnlyValue, true); +} + + +// +// Update value of specified field. +// currently only "x-slp-svc" field is supported. +// +#define BUFFER_SIZE 1024 +result +_Aul::_DesktopFile::UpdateField(const char* path, const char* fieldName, const char* value, bool isRemove) +{ + SysTryReturnResult(NID_APP, path != null, E_INVALID_ARG, "path should not be null."); + SysTryReturnResult(NID_APP, fieldName != null, E_INVALID_ARG, "fieldName should not be null."); + SysTryReturnResult(NID_APP, value != null, E_INVALID_ARG, "value should not be null."); + + FILE* fp = fopen(path, "r+"); + SysTryReturnResult(NID_APP, fp != null, E_SYSTEM, "falied to open '%s' due to %s", path, strerror(errno)); + + char buffer[BUFFER_SIZE] = {0, }; + bool found = false; + int len = 0; + int pos = 0; + int foundpos = 0; + result r = E_SUCCESS; + int remains = 0; + + ArrayListT buffers; + buffers.Construct(); + + char* pCurrent = null; + + while (fgets(buffer, BUFFER_SIZE, fp) != NULL) + { + len = strlen(buffer); + SysTryCatch(NID_APP, len < BUFFER_SIZE, , r = E_INVALID_ARG, "strlen returns invalid value. (%d)", len ); + + if (found) + { + pCurrent = new (std::nothrow) char[len + 1]; + SysTryCatch(NID_APP, pCurrent != null, , r = E_OUT_OF_MEMORY, "failed to allocate mem pCurrent"); + + strncpy(pCurrent, buffer, len); + buffers.Add(pCurrent); + } + else + { + if (strncmp(buffer, fieldName, len) == 0) + { + int fieldNameLen = strlen(fieldName); + SysTryCatch(NID_APP, len > fieldNameLen, , E_INVALID_ARG, "[E_INVALID_ARG] fieldName(%s)", fieldName); + + pCurrent = UpdateServiceValueN(buffer + fieldNameLen, value, isRemove); + SysTryCatch(NID_APP, pCurrent != null, , r = GetLastResult(), "[%s] UpdateServiceValue failed", GetErrorMessage(GetLastResult())); + + buffers.Add(pCurrent); + + foundpos = pos; + found = true; + } + } + + pos += len; + } + + if (found) + { + fsetpos(fp, (fpos_t*) &foundpos); + + remains = buffers.GetCount(); // prevent infinite loop + while (buffers.GetCount() > 0 && remains-- > 0) + { + pCurrent = null; + buffers.GetAt(0, pCurrent); + buffers.RemoveAt(0); + SysTryCatch(NID_APP, pCurrent != null, , r = E_INVALID_STATE, ""); + + fputs(pCurrent, fp); + len = strlen(pCurrent); + pos += len; + delete[] pCurrent; + } + + int ret = truncate(path, pos); + SysTryLog(NID_APP, ret == 0, "Truncate failure (%s).", strerror(errno)); + } + else + { + char svctext[_MAX_TIZEN_SVC_DESC_LEN] = {0, }; + snprintf(svctext, _MAX_TIZEN_SVC_DESC_LEN, "%s=%s\n", fieldName, value); + fputs(svctext, fp); + } + fclose(fp); + + return E_SUCCESS; + +CATCH: + + remains = buffers.GetCount(); // prevent infinite loop + while (buffers.GetCount() > 0 && remains-- > 0) + { + pCurrent = null; + buffers.GetAt(0, pCurrent); + buffers.RemoveAt(0); + if (pCurrent != null) + { + delete[] pCurrent; + } + } + + fclose(fp); + + return r; +} + +// +// Tizen service string example +// X-TIZEN-SVC= http://tizen.org/appcontrol/operation/pick|NULL|image/jpge; http://tizen.org/appcontrol/operation/pick|NULL|video/mp4; http://tizen.org/appcontrol/operation/pick|NULL|NULL; http://tizen.org/appcontrol/operation/pview|NULL|NULL +// +char* +_Aul::_DesktopFile::UpdateServiceValueN(char* buffer, const char* newValue, bool isRemove) +{ + SysTryReturn(NID_APP, buffer != null, null, E_INVALID_ARG, ""); + SysTryReturn(NID_APP, newValue != null, null, E_INVALID_ARG, ""); + + SysLog(NID_APP, "current(%s), new(%s), isRemove(%s)", buffer, newValue, (isRemove) ? "true" : "false"); + + String buf(buffer); + bool found = false; + + const String& servicePattern(L"([A-Za-z&=:/\\.\\-]*);?"); + + ArrayList services; + String resultString; + + Utility::RegularExpression regex; + result r = regex.Construct(servicePattern); + SysTryReturn(NID_APP, !IsFailed(r), null, r, ""); + + String newOperation; + String newUrl; + String newMimeType; + String newService(newValue); + + if (isRemove == false) + { + ParseService(newService, newOperation, newUrl, newMimeType); + } + else + { + newOperation = newValue; + } + + services.Construct(); + + while (regex.Consume(buf, &services) == true) + { + String* pCurrentService = (String*) services.GetAt(1); + services.RemoveAll(false); + + String operation; + String url; + String mimeType; + + ParseService(*pCurrentService, operation, url, mimeType); + + if (operation == newOperation) + { + if (isRemove == true) + { + SysLog(NID_APP, "opreration '%ls' will be removed", operation.GetPointer()); + } + else + { + SysAssertf(found == false, "It's assumed that service doesn't have duplicated operation in tizen desktop file. But it isn't, so now we have to check this case."); + // replace operation. + if (found == false) // ( if duplicated operation is already exist, It will be keeped. + { + // update value + AppendServiceValueToString(resultString, newService); + SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be updated to ;%ls;%ls", operation.GetPointer(), url.GetPointer(), mimeType.GetPointer(), newUrl.GetPointer(), mimeType.GetPointer()); + } + } + found = true; + } + else + { + // add not specified service. + AppendServiceValueToString(resultString, *pCurrentService); + } + + delete pCurrentService; + } + + if (found == false && isRemove == false) + { + AppendServiceValueToString(resultString, newService); + SysLog(NID_APP, "opreration '%ls;%ls;%ls' will be added", newOperation.GetPointer(), newUrl.GetPointer(), newMimeType.GetPointer()); + } + + SysLog(NID_APP, "updated string is '%ls'", resultString.GetPointer()); + return _StringConverter::CopyToCharArrayN(resultString); +} + + +void +_Aul::_DesktopFile::AppendServiceValueToString(String& serviceString, const String& newVaue) +{ + if (serviceString.GetLength() > 0) + { + serviceString += ";"; + } + + serviceString += newVaue; +} + + +result +_Aul::_DesktopFile::ParseService(const String& service, String& operation, String& url, String& mimeType) +{ + SysLog(NID_APP, "service(%ls)", service.GetPointer()); + + const String& serviceDetailPattern(L"([A-Za-z&=/\\.\\-]*):(.*://[A-Za-z&=/\\.\\-]*|[A-Za-z&=/\\.\\-]*):([A-Za-z&=/\\.\\-]*)"); + + Utility::RegularExpression regexDetail; + result r = regexDetail.Construct(serviceDetailPattern); + SysTryReturn(NID_APP, !IsFailed(r), null, r, "[%s] RegularExpression::Construct(L\"%ls\") failed.", GetErrorMessage(r), serviceDetailPattern.GetPointer()); + + ArrayList matchedItems; + matchedItems.Construct(); + regexDetail.Match(service, true, &matchedItems); + + int matchedCount = matchedItems.GetCount(); + SysTryLog(NID_APP, matchedCount == 4, "It's assumed that x-slp-svc value always have operation:url:mime in tizen desktop file. But it isn't or our parser is invalid. so now we have to check this case. %d", matchedItems.GetCount()); + + if (matchedCount > 1) + { + operation = *(String*) matchedItems.GetAt(1); + } + + if (matchedCount > 2) + { + url = *(String*) matchedItems.GetAt(2); + } + + if (matchedCount > 3) + { + mimeType = *(String*) matchedItems.GetAt(3); + } + + SysLog(NID_APP, "matched(%d) : (%ls;%ls;%ls)", matchedItems.GetCount(), operation.GetPointer(), url.GetPointer(), mimeType.GetPointer()); + matchedItems.RemoveAll(true); + + return E_SUCCESS; +} + +} } // Tizen::App diff --git a/src/app/FApp_ConditionManagerIpcMessages.cpp b/src/app/FApp_ConditionManagerIpcMessages.cpp new file mode 100644 index 0000000..9aa64a4 --- /dev/null +++ b/src/app/FApp_ConditionManagerIpcMessages.cpp @@ -0,0 +1,46 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_ConditionManagerIpcMessages.cpp + * @brief This file contains IPC message class generated by macros. + */ + +#define IPC_MESSAGE_IMPL +#include "FApp_ConditionManagerIpcMessages.h" + +// Generate constructors. +#include "ipc/struct_constructor_macros.h" +#include "FApp_ConditionManagerIpcMessages.h" +// Generate destructors. + +#include "ipc/struct_destructor_macros.h" +#include "FApp_ConditionManagerIpcMessages.h" + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC +{ +#include "FApp_ConditionManagerIpcMessages.h" +} // namespace IPC + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC +{ +#include "FApp_ConditionManagerIpcMessages.h" +} // namespace IPC diff --git a/src/app/FApp_ConditionManagerProxy.cpp b/src/app/FApp_ConditionManagerProxy.cpp new file mode 100644 index 0000000..bef8692 --- /dev/null +++ b/src/app/FApp_ConditionManagerProxy.cpp @@ -0,0 +1,123 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_ConditionManagerProxy.cpp + * @brief This is the implementation for the _ConditionManagerProxy.cpp class. + */ + +#include +#include + +#include + +#include +#include + +#include "FApp_ConditionManagerIpcMessages.h" +#include "FApp_ConditionManagerProxy.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +_ConditionManagerProxy::_ConditionManagerProxy(void) + : __pIpcClient(null) +{ +} + + +_ConditionManagerProxy::~_ConditionManagerProxy(void) +{ + delete __pIpcClient; +} + +result +_ConditionManagerProxy::Construct() +{ + __pIpcClient = new (std::nothrow) Tizen::Io::_IpcClient(); + SysTryReturnResult(NID_APP, __pIpcClient != null, E_OUT_OF_MEMORY, "_IpcClient creation failed."); + + result r = __pIpcClient->Construct("osp.app.ipcserver.conditionmanager"); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "_IpcClient constructing faliied [%s].", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_ConditionManagerProxy::RegisterAppLaunch(const AppId& appId, const Tizen::Base::String& executableName, const String& condition, + const IList* pArguments, AppManager::LaunchOption option) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, ""); + + result response = E_SUCCESS; + const ArrayList* pArrayList = dynamic_cast(pArguments); + ArrayList dummy; + dummy.Construct(); + + std::auto_ptr pMsg (new (std::nothrow) ConditionManager_RegisterAppLaunch( + appId, executableName, condition, (pArrayList != null) ? *pArrayList : dummy, + (int) AppManager::LAUNCH_OPTION_DEFAULT, &response)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + + SysTryReturn(NID_APP, !IsFailed(r), r, r, "__pIpcClient->SendRequest is failed. (%s)", GetErrorMessage(r)); + + return response; +} + + +result +_ConditionManagerProxy::UnregisterAppLaunch(const AppId& appId, const Tizen::Base::String& executableName, const String* pCondition) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, ""); + + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) ConditionManager_UnregisterAppLaunch( + appId, executableName, (pCondition != null) ? *pCondition : L"", &response)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + + SysTryReturn(NID_APP, !IsFailed(r), r, r, "__pIpcClient->SendRequest is failed. (%s)", GetErrorMessage(r)); + + return response; +} + +bool +_ConditionManagerProxy::IsAppLaunchRegistered(const AppId& appId, const Tizen::Base::String& executableName, const String* pCondition) const +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, ""); + + bool isAppLaunchRegistered = false; + result exception = E_SYSTEM; + std::auto_ptr pMsg(new (std::nothrow) ConditionManager_IsAppLaunchRegistered( + appId, executableName, (pCondition != null) ? *pCondition : L"", &isAppLaunchRegistered, &exception)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + + SysTryReturn(NID_APP, !IsFailed(r), false, r, "__pIpcClient->SendRequest is failed. (%s)", GetErrorMessage(r)); + SysTryReturn(NID_APP, !IsFailed(exception), false, exception, "__pIpcClient->SendRequest is failed. (%s)", GetErrorMessage(exception)); + + return isAppLaunchRegistered; +} + + +} } // Tizen::App diff --git a/src/app/FApp_ConditionManagerProxy.h b/src/app/FApp_ConditionManagerProxy.h new file mode 100644 index 0000000..bb61179 --- /dev/null +++ b/src/app/FApp_ConditionManagerProxy.h @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_ConditionManagerProxy.h + * @brief This is the header file of the _ConditionManagerProxy class. + */ + +#ifndef _FAPP_INTERNAL_CONDITION_MANAGER_PROXY_H_ +#define _FAPP_INTERNAL_CONDITION_MANAGER_PROXY_H_ + +#include +#include +#include +#include + +#include "FApp_Types.h" + +namespace Tizen { namespace Io { class _IpcClient; } } + +namespace Tizen { namespace App +{ + +/** + * @class _ConditionManagerProxy + * @brief + * @since 2.1 + */ +class _ConditionManagerProxy +{ +public: + _ConditionManagerProxy(void); + + ~_ConditionManagerProxy(void); + + result Construct(void); + + result RegisterAppLaunch(const AppId& appId, const Tizen::Base::String& executableName, const Tizen::Base::String& condition, const Tizen::Base::Collection::IList* pArguments, AppManager::LaunchOption option); + + result UnregisterAppLaunch(const AppId& appId, const Tizen::Base::String& executableName, const Tizen::Base::String* pCondition); + + bool IsAppLaunchRegistered(const AppId& appId, const Tizen::Base::String& executableName, const Tizen::Base::String* pCondition = null) const; + +private: + _ConditionManagerProxy(const _ConditionManagerProxy& rhs); + + _ConditionManagerProxy& operator =(const _ConditionManagerProxy& rhs); + +private: + Tizen::Io::_IpcClient* __pIpcClient; + +}; // _ConditionManagerProxy + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_CONDITION_MANAGER_PROXY_H_ diff --git a/src/app/FApp_DataControlProviderManagerImpl.cpp b/src/app/FApp_DataControlProviderManagerImpl.cpp new file mode 100644 index 0000000..55c6020 --- /dev/null +++ b/src/app/FApp_DataControlProviderManagerImpl.cpp @@ -0,0 +1,347 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_DataControlProviderManagerImpl.cpp + * @brief This is the implementation for the %_DataControlProviderManagerImpl class. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "FApp_Aul.h" +#include "FApp_AppArg.h" +#include "FApp_AppInfo.h" +#include "FApp_AppImpl.h" +#include "FApp_AppControlManager.h" +#include "FApp_SqlDataControlImpl.h" +#include "FApp_MapDataControlImpl.h" +#include "FApp_DataControlProviderManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +extern const char* _DATACONTROL_RESULTSET_DIR; + +namespace Tizen { namespace App +{ + +result +_DataControlProviderManagerImpl::SetSqlDataControlProviderEventListener(ISqlDataControlProviderEventListener* pListener) +{ + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturn(NID_APP, pAppImpl, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting _AppImpl instance failed."); + + return pAppImpl->SetSqlDataControlProviderEventListener(pListener); +} + +result +_DataControlProviderManagerImpl::SetMapDataControlProviderEventListener(IMapDataControlProviderEventListener* pListener) +{ + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + SysTryReturn(NID_APP, pAppImpl, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting _AppImpl instance failed."); + + return pAppImpl->SetMapDataControlProviderEventListener(pListener); +} + +result +_DataControlProviderManagerImpl::SendDataControlResult(RequestId reqId, _DataControlRequestType apiType, + IDbEnumerator* pDbEnum, IList* pResultValueList, long long insertRowId, bool providerResult, const String* pErrorMsg) +{ + ArrayList* pList = null; + String* pAppId = null; + String* pRequestType = null; + int type = 0; + _DataControlRequestType requestType = _DATACONTROL_REQUEST_TYPE_UNDEFINED; + String* pProviderId = null; + String* pReqId = null; + ArrayList* pResultArgList = null; + String* pResult = null; + String* pErrorMessage = null; + String* pTempFilePath = null; + String* pNo = null; + int pageNo = 0; + String* pCount = null; + int countPerPage = 0; + String* pResultCount = null; + String* pResultValue = null; + _AppArg resultArg; + result r = E_SUCCESS; + + _AppControlManager* pAppMgr = _AppControlManager::GetInstance(); + SysTryReturnResult(NID_APP, pAppMgr, E_SYSTEM, "Failed to get instance."); + + _ResultInfo* pResultInfo = pAppMgr->__resultManager.FindItem(static_cast< int >(reqId)); + SysTryReturnResult(NID_APP, pResultInfo, E_OBJ_NOT_FOUND, + "The data control request specified with the reqId (%ld) did not exist.", reqId); + + const _AppArg& arg = pResultInfo->arg; + + pList = arg.GetArgListN(0); + SysTryCatch(NID_APP, pList, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result object"); + + // key-based request + pAppId = dynamic_cast< String* >(pList->GetAt(0)); // request key[0] + SysTryCatch(NID_APP, pAppId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result object"); + + pRequestType = dynamic_cast< String* >(pList->GetAt(1)); // request key[1] + SysTryCatch(NID_APP, pRequestType, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result object"); + Integer::Parse(*pRequestType, type); + requestType = static_cast< _DataControlRequestType >(type); + + if (providerResult == true && apiType != requestType) + { + if ((apiType == _DATACONTROL_REQUEST_TYPE_SQL_UPDATE /*UpdateDelete*/ && requestType == _DATACONTROL_REQUEST_TYPE_SQL_DELETE) || + apiType == _DATACONTROL_REQUEST_TYPE_UNDEFINED /*MAP*/) + { + r = E_SUCCESS; + } + else + { + r = E_INVALID_ARG; + SysLog(NID_APP, "[E_INVALID_ARG] This method cannot send the result set for the specified reqId."); + goto CATCH; + } + } + + pReqId = dynamic_cast< String* >(pList->GetAt(2)); // request key[2] + SysTryCatch(NID_APP, pReqId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result object"); + + pProviderId = dynamic_cast< String* >(pList->GetAt(3)); // request key[3] + SysTryCatch(NID_APP, pProviderId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result object"); + + // Serializes the result + pResultArgList = new (std::nothrow) ArrayList(); + SysTryCatch(NID_APP, pResultArgList, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + pResultArgList->Construct(); + + pResult = new (std::nothrow) String(); + SysTryCatch(NID_APP, pResult, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + pResult->Append(static_cast< int >(providerResult)); + pResultArgList->Add(*pResult); // result list[0] + + if (pErrorMsg == null) + { + pErrorMessage = new (std::nothrow) String(); + } + else + { + pErrorMessage = new (std::nothrow) String(*pErrorMsg); + } + SysTryCatch(NID_APP, pErrorMessage, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + pResultArgList->Add(*pErrorMessage); // result list[1] + + switch (requestType) + { + case _DATACONTROL_REQUEST_TYPE_SQL_QUERY: + { + if (pDbEnum) + { + std::unique_ptr<_DataControlResultSetImpl> pResultSet(new (std::nothrow) _DataControlResultSetImpl(reqId)); + SysTryCatch(NID_APP, pResultSet, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pResultSet->FillWith(pDbEnum); + SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, + "[E_SYSTEM] The method cannot proceed due to a severe system error."); + + String tempFilePath(_DATACONTROL_RESULTSET_DIR); + tempFilePath.Append(*pAppId); + tempFilePath.Append(*pReqId); + pTempFilePath = new (std::nothrow) String(tempFilePath); + } + else + { + pTempFilePath = new (std::nothrow) String(L"NoResultSet"); + } + SysTryCatch(NID_APP, pTempFilePath, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pResultArgList->Add(*pTempFilePath); // result list[2] + break; + } + case _DATACONTROL_REQUEST_TYPE_SQL_INSERT: + pResultArgList->Add(*(new String(LongLong::ToString(insertRowId)))); // result list[2] + break; + + case _DATACONTROL_REQUEST_TYPE_SQL_UPDATE: + // fall through + case _DATACONTROL_REQUEST_TYPE_SQL_DELETE: + break; + + case _DATACONTROL_REQUEST_TYPE_MAP_QUERY: + { + SysTryCatch(NID_APP, !(providerResult == true && pResultValueList == null), r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The specified pResultValueList should not be null if the request is GetValue query."); + + if (pResultValueList) + { + // list-based request + pNo = dynamic_cast< String* >(pList->GetAt(6)); // request list[2] + SysTryCatch(NID_APP, pNo, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result object"); + Integer::Parse(*pNo, pageNo); + + pCount = dynamic_cast< String* >(pList->GetAt(7)); // request list[3] + SysTryCatch(NID_APP, pCount, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result object"); + Integer::Parse(*pCount, countPerPage); + + String resultCount; + int num = pResultValueList->GetCount(); + int currentoffset = (pageNo - 1) * countPerPage; + int remainingNum = num - currentoffset; + remainingNum = (remainingNum > 0) ? remainingNum : 0; // round off to zero if negative num is found + int addItemCount = (countPerPage > remainingNum) ? remainingNum : countPerPage; + resultCount.Append(addItemCount); + + pResultCount = new (std::nothrow) String(resultCount); + SysTryCatch(NID_APP, pResultCount, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + pResultArgList->Add(*pResultCount); // result list[2] + + for (int i = currentoffset; i < num; i++) + { + String* pTempValue = dynamic_cast< String* >(pResultValueList->GetAt(i)); + SysTryCatch(NID_APP, pTempValue != null, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The specified pResultValueList parameter should be String class."); + + pResultValue = new (std::nothrow) String(*pTempValue); + SysTryCatch(NID_APP, pResultValue, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + pResultArgList->Add(*pResultValue); // list[3] ~ + } + } + break; + } + case _DATACONTROL_REQUEST_TYPE_MAP_INSERT: + // fall through + case _DATACONTROL_REQUEST_TYPE_MAP_UPDATE: + // fall through + case _DATACONTROL_REQUEST_TYPE_MAP_DELETE: + SysTryCatch(NID_APP, !(providerResult == true && pResultValueList != null), r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The specified pResultValueList should be null if the request is \ + one of AddValue, SetValue, RemoveValue queries."); + break; + + default: + SysTryCatch(NID_APP, false, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result object"); + break; + } + + r = resultArg.ConstructResult(arg, pResultArgList); + SysTryCatch(NID_APP, !IsFailed(r), r = E_SYSTEM, r, "[%s] Propagating.", GetErrorMessage(r)); + + //resultArg.Print(); + r = _Aul::SendResult(resultArg.GetBundle(), static_cast< appsvc_result_val >(0)); + SysTryCatch(NID_APP, !IsFailed(r), r = E_SYSTEM, r, "[%s] _Aul::SendResult() was failed.", GetErrorMessage(r)); + + // Erases _AppArg after sending the result back to the caller + pAppMgr->__resultManager.RemoveItem(static_cast< int >(reqId)); + +CATCH: + if (pList) + { + pList->RemoveAll(true); + } + delete pList; + + if (pResultArgList) + { + pResultArgList->RemoveAll(true); + } + delete pResultArgList; + + return r; +} + +result +_DataControlProviderManagerImpl::SendSqlDataControlSelectResult(RequestId reqId, IDbEnumerator* pDbEnum) +{ + return _DataControlProviderManagerImpl::SendDataControlResult(reqId, _DATACONTROL_REQUEST_TYPE_SQL_QUERY, + pDbEnum, null, -1, true, null); +} + +result +_DataControlProviderManagerImpl::SendSqlDataControlInsertResult(RequestId reqId, long long insertRowId) +{ + return _DataControlProviderManagerImpl::SendDataControlResult(reqId, _DATACONTROL_REQUEST_TYPE_SQL_INSERT, + null, null, insertRowId, true, null); +} + +result +_DataControlProviderManagerImpl::SendSqlDataControlUpdateDeleteResult(RequestId reqId) +{ + return _DataControlProviderManagerImpl::SendDataControlResult(reqId, _DATACONTROL_REQUEST_TYPE_SQL_UPDATE, + null, null, -1, true, null); +} + +result +_DataControlProviderManagerImpl::SendMapDataControlResult(RequestId reqId, IList* pResultValueList) +{ + return _DataControlProviderManagerImpl::SendDataControlResult(reqId, _DATACONTROL_REQUEST_TYPE_UNDEFINED, + null, pResultValueList, -1, true, null); +} + +result +_DataControlProviderManagerImpl::SendDataControlError(RequestId reqId, const String& errorMsg) +{ + return _DataControlProviderManagerImpl::SendDataControlResult(reqId, _DATACONTROL_REQUEST_TYPE_UNDEFINED, + null, null, -1, false, &errorMsg); +} + +DataControlProviderManager* +_DataControlProviderManagerImpl::GetInstance(void) +{ + static DataControlProviderManager* pDcMgr = null; + + if (pDcMgr == null) + { + pDcMgr = new (std::nothrow) DataControlProviderManager(); + SysTryReturn(NID_APP, pDcMgr, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory was insufficient."); + } + + return pDcMgr; +} + +// private +_DataControlProviderManagerImpl::_DataControlProviderManagerImpl(void) +{ +} + +_DataControlProviderManagerImpl::~_DataControlProviderManagerImpl(void) +{ +} + +} } // Tizen::App + diff --git a/src/app/FApp_DataControlProviderManagerImpl.h b/src/app/FApp_DataControlProviderManagerImpl.h new file mode 100644 index 0000000..2d4e839 --- /dev/null +++ b/src/app/FApp_DataControlProviderManagerImpl.h @@ -0,0 +1,120 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_DataControlProviderManagerImpl.h + * @brief This is the header file for the %_DataControlProviderManagerImpl class. + * + * This header file contains the declarations of the %_DataControlProviderManagerImpl class. + */ + +#ifndef _FAPP_INTERNAL_DATACONTROL_PROVIDERMANAGER_IMPL_H_ +#define _FAPP_INTERNAL_DATACONTROL_PROVIDERMANAGER_IMPL_H_ + +#include +#include +#include +#include + +#include "FApp_AppArg.h" + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +}} +namespace Tizen { namespace Io +{ +class DataControlResultSet; +}} + +namespace Tizen { namespace App +{ + +class DataControlProviderManager; + +/** + * @class _DataControlProviderManagerImpl + * @brief This class manages all the data controls. + * @since 2.1 + * + * The %_DataControlProviderManagerImpl class manages all the data controls. + */ +class _DataControlProviderManagerImpl + : public Tizen::Base::Object +{ + +public: + result SetSqlDataControlProviderEventListener(ISqlDataControlProviderEventListener* pListener); + + result SetMapDataControlProviderEventListener(IMapDataControlProviderEventListener* pListener); + + result SendSqlDataControlSelectResult(RequestId reqId, Tizen::Io::IDbEnumerator* pDbEnum); + + result SendSqlDataControlInsertResult(RequestId reqId, long long insertRowId); + + result SendSqlDataControlUpdateDeleteResult(RequestId reqId); + + result SendMapDataControlResult(RequestId reqId, Tizen::Base::Collection::IList* pResultValueList); + + result SendDataControlError(RequestId reqId, const Tizen::Base::String& errorMsg); + + /** + * Retrieves the data control provider manager instance. + * + * @since 2.1 + * @return A pointer to the DataControlProviderManager instance if it succeeded. + * else @c null + */ + static DataControlProviderManager* GetInstance(void); + +private: + /** + * This is the default constructor for this class. + * + * @since 2.1 + */ + _DataControlProviderManagerImpl(void); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_DataControlProviderManagerImpl(void); + + /** + * This is the default copy constructor for this class. + */ + _DataControlProviderManagerImpl(const _DataControlProviderManagerImpl& source); + + /** + * This is the assignment operator for this class. + */ + _DataControlProviderManagerImpl& operator =(const _DataControlProviderManagerImpl& source); + + static result SendDataControlResult(RequestId reqId, _DataControlRequestType apiType, + Tizen::Io::IDbEnumerator* pDbEnum, Tizen::Base::Collection::IList* pResultValueList, long long insertRowId, + bool providerResult, const Tizen::Base::String* pErrorMsg); + + friend class DataControlProviderManager; +}; + +}} // Tizen::App + +#endif // _FAPP_INTERNAL_DATACONTROL_PROVIDERMANAGER_IMPL_H_ + diff --git a/src/app/FApp_ImeAppImpl.cpp b/src/app/FApp_ImeAppImpl.cpp new file mode 100644 index 0000000..46e7da8 --- /dev/null +++ b/src/app/FApp_ImeAppImpl.cpp @@ -0,0 +1,397 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_ImeAppImpl.cpp + * @brief This is the implementation for the _ImeAppImpl class. + */ + +#include +#include +#include +#include +#include + +#define Uses_SCIM_HELPER +#define Uses_SCIM_TYPES +#define Uses_SCIM_CONFIG_BASE +#undef null +#include +#define null 0 + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FApp_AppFrame.h" +#include "FApp_AppInfo.h" +#include "FApp_AppImpl.h" +#include "FApp_ImeAppImpl.h" +#include "FAppPkg_PackageManagerImpl.h" + +//#include "FUiIme_ScimDataConverter.h" + +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Ui; +using namespace Tizen::Ui::Controls; +using namespace Tizen::Ui::Ime; +using namespace Tizen::System; +using namespace Tizen::Graphics; + + +const char GLINFO_FILE_PATH[] = "info/webservice.info"; + + +namespace Tizen { namespace App +{ + +_ImeAppImpl* _ImeAppImpl::__pImeAppImpl = null; + + +_ImeAppImpl::_ImeAppImpl(UiApp* pUiApp) + : _UiAppImpl(pUiApp) + , __pAppImpl(_AppImpl::GetInstance()) + , __appUiState(APP_UI_STATE_BACKGROUND) + , __pUiApp(pUiApp) +{ + __pImeAppImpl = this; + SysTryReturnVoidResult(NID_APP, __pAppImpl != null, E_INVALID_STATE, "[E_INVALID_STATE] Getting internal instance failed."); +} + + +_ImeAppImpl::~_ImeAppImpl(void) +{ + __pImeAppImpl = null; +} + + +bool +_ImeAppImpl::OnCreate(void) +{ + SysLog(NID_APP, "Platform creation event."); + + _AppInfo::SetAppState(INITIALIZING); + + return true; +} + + +void +_ImeAppImpl::OnService(service_s* service) +{ +} + + +void +_ImeAppImpl::OnTerminate(void) +{ + SysLog(NID_APP, "Termination event 0x%x state", _AppInfo::GetAppState()); + + if (OnImeAppImplTerminating() != true) + { + SysLog(NID_APP, "[E_SYSTEM] The Termination of application failed."); + } +} + + +void +_ImeAppImpl::OnResume(void) +{ + SysLog(NID_APP, "System resume event on 0x%x state", _AppInfo::GetAppState()); + + if (_AppInfo::GetAppState() == RUNNING) + { + OnForeground(); + } +} + + +void +_ImeAppImpl::OnPause(void) +{ + SysLog(NID_APP, "System pause event on 0x%x state", _AppInfo::GetAppState()); + + if (_AppInfo::GetAppState() == RUNNING) + { + OnBackground(); + } +} + + +void +_ImeAppImpl::OnDeviceOrientationChanged(app_device_orientation_e orientation) +{ + SysLog(NID_APP, "System device orientation event."); + + _ControlImplManager* pControlImplManager = _ControlImplManager::GetInstance(); + if (pControlImplManager == null) + { + SysLog(NID_APP, "Device orientation event arrived too early."); + return; + } + + pControlImplManager->OnScreenRotated(orientation); +} + + +long +_ImeAppImpl::OnWindowHandleRequest(void) +{ + const _EcoreEvas* const pEvas = GetEcoreEvasMgr()->GetEcoreEvas(); + return (pEvas) ? static_cast(pEvas->GetXWindow()) : -1; +} + + +bool +_ImeAppImpl::OnAppInitializing(void) +{ + // [FIXME] Temporary code for enabling opengl + + // to reduce package manager overhead, _AppInfo::GetAppRootPath() is not used + + if (faccessat(_AppInfo::GetAppRootDirFd(), GLINFO_FILE_PATH, F_OK, 0) == 0) + { + SysLog(NID_APP, "Setting opengl engine for WEB_SERVICE privilege."); + elm_config_preferred_engine_set("opengl_x11"); + } + + // Do Ui related initializing for UiApp + result r = InitializeUiFramework(); + if (IsFailed(r)) + { + SysLogException(NID_APP, E_SYSTEM, "Getting resolution information failure. Application may not be installed correctly."); + _Process::Exit(-1); + } + + _KeyEventManager::GetInstance()->AddKeyEventListener(*this); + + SysTryReturn(NID_APP, __pUiApp != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting UiApp instance failed."); + return __pUiApp->OnAppInitializing(*(AppRegistry::GetInstance())); +} + + +bool +_ImeAppImpl::OnAppInitialized(void) +{ + SysTryReturn(NID_APP, __pUiApp != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting UiApp instance failed."); + + __pUiApp->OnAppInitialized(); + return true; +} + + +bool +_ImeAppImpl::OnImeAppImplTerminating(void) +{ + bool result = false; + + if (_AppInfo::GetAppState() != TERMINATED) + { + result = __pUiApp->OnAppTerminating(*(AppRegistry::GetInstance()), false); + _AppInfo::SetAppState(TERMINATED); + } + + // Do Ui related finalizing for UiApp + FinalizeUiFramework(); + + return result; +} + + +void +_ImeAppImpl::OnForeground(void) +{ + result r = E_SUCCESS; + + __appUiState = APP_UI_STATE_FOREGROUND; + __pUiApp->OnForeground(); + + r = _PowerManagerImpl::OnForeground(); + + SysTryLog(NID_APP, !IsFailed(r), "Failed to send foreground event to powermanager"); +} + + +void +_ImeAppImpl::OnBackground(void) +{ + result r = E_SUCCESS; + + __appUiState = APP_UI_STATE_BACKGROUND; + __pUiApp->OnBackground(); + + r = _PowerManagerImpl::OnBackground(); + + SysTryLog(NID_APP, !IsFailed(r), "Failed to send background event to powermanager"); +} + + +AppUiState +_ImeAppImpl::GetAppUiState(void) const +{ + return __appUiState; +} + + +_ImeAppImpl* +_ImeAppImpl::GetInstance(void) +{ + return __pImeAppImpl; +} + + +UiApp* +_ImeAppImpl::GetUiAppInstance(void) +{ + return __pUiApp; +} + + +} } //Tizen::App +/* +#define MAX_BUFFER 100 + +#ifdef __cplusplus +extern "C" +{ +#endif // __cplusplus + +extern int OspImeInfo(char* uuid, char* name, char* language) __attribute__((weak)); + +unsigned int _OSP_EXPORT_ +scim_helper_module_number_of_helpers (void) +{ + LOG(LOG_DEBUG, "IME", "IME : scim_helper_module_number_of_helpers"); + return 1; +} + +bool _OSP_EXPORT_ +scim_helper_module_get_helper_info (unsigned int idx, scim::HelperInfo& info) +{ + char uuid[MAX_BUFFER]; + char name[MAX_BUFFER]; + memset(uuid, '\0', MAX_BUFFER); + memset(name, '\0', MAX_BUFFER); + + LOG(LOG_DEBUG, "IME", "IME : scim_helper_module_get_helper_info enter"); + + if (dlsym(null, "OspImeInfo") != null) + { + LOG(LOG_DEBUG, "IME", "IME : OspImeInfo found"); + OspImeInfo(uuid, name, null); + } + + LOG(LOG_DEBUG, "IME", "IME : scim_helper_module_get_helper_info 2 %ls %ls", uuid, name); + + if (strlen(uuid) == 0) + { + LOG(LOG_DEBUG, "IME", "IME : OspImeInfo no uuid return"); + strncpy(uuid, "723191f0-cfb3-11e1-9ea3-e811323afc30", strlen("723191f0-cfb3-11e1-9ea3-e811323afc30")); + } + + if (strlen(name) == 0) + { + LOG(LOG_DEBUG, "IME", "IME : OspImeInfo no name return"); + strncpy(name, "Keyboard", strlen("Keyboard")); + } + + String Uuid(uuid); + String Name(name); + + LOG(LOG_DEBUG, "IME", "IME : scim_helper_module_get_helper_info %ls %ls", Uuid.GetPointer(), Name.GetPointer()); + + Tizen::Ui::Ime::_ScimDataConverter dataConverter; + scim::String scimUuid; + scim::String scimName; + + dataConverter.ConvertString(Uuid, scimUuid); + dataConverter.ConvertString(Name, scimName); + + if (idx == 0) + { + info = scim::HelperInfo(scimUuid, scimName, "", "", + scim::SCIM_HELPER_STAND_ALONE | scim::SCIM_HELPER_NEED_SCREEN_INFO | scim::SCIM_HELPER_AUTO_RESTART); + return true; + } + + return false; +} + +scim::String _OSP_EXPORT_ +scim_helper_module_get_helper_language (unsigned int idx) +{ + // get ImeApplicationInfo + char uuid[MAX_BUFFER]; + char language[MAX_BUFFER]; + memset(uuid, '\0', MAX_BUFFER); + memset(language, '\0', MAX_BUFFER); + + LOG(LOG_DEBUG, "IME", "IME : scim_helper_module_get_helper_language enter"); + + if (dlsym(null, "OspImeInfo") != null) + { + LOG(LOG_DEBUG, "IME", "IME : OspImeInfo found"); + OspImeInfo(uuid, null, language); + } + + if (strlen(language) == 0) + { + LOG(LOG_DEBUG, "IME", "IME : OspImeInfo no language return"); + strncpy(language, "fr_FR", strlen("fr_FR")); + } + + String Language(language); + + LOG(LOG_DEBUG, "IME", "IME : scim_helper_module_get_helper_language %ls", Language.GetPointer()); + + // convert String + Tizen::Ui::Ime::_ScimDataConverter dataConverter; + scim::String scimLanguage; + + dataConverter.ConvertString(Language, scimLanguage); + + return scimLanguage; +} + +void _OSP_EXPORT_ +scim_module_init (void) +{ + LOG(LOG_DEBUG, "IME", "IME : scim_module_init"); +} + +void _OSP_EXPORT_ +scim_module_exit (void) +{ + LOG(LOG_DEBUG, "IME", "IME : scim_module_exit"); +} + +#ifdef __cplusplus +} +#endif // __cplusplus +*/ diff --git a/src/app/FApp_ImeAppImpl.h b/src/app/FApp_ImeAppImpl.h new file mode 100644 index 0000000..c7b09b7 --- /dev/null +++ b/src/app/FApp_ImeAppImpl.h @@ -0,0 +1,221 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_ImeAppImpl.h + * @brief This is the header file for the %_ImeAppImpl class. + */ + +#ifndef _FAPP_INTERNAL_IME_APP_IMPL_H_ +#define _FAPP_INTERNAL_IME_APP_IMPL_H_ + +#include + +#include +#include + +#include "FApp_UiAppImpl.h" + +namespace Tizen { namespace Base { namespace Collection { class IList; } } } +namespace Tizen { namespace Ui {namespace Controls { class Frame; } } } + +namespace Tizen { namespace App +{ + +class IAppFrame; +class _AppFrame; + +/** + * @class _ImeAppImpl + * @brief This class is the Impl class of a IME application. + * @since 2.1 + * + * This class is the Impl class of a IME application. + */ +class _ImeAppImpl + : public Tizen::App::_UiAppImpl +{ +public: + /** + * Returns the _ImeAppImpl's instance pointer. + * + * @since 2.1 + * @return A pointer to the %_ImeAppImpl instance, @n + * else @c null if it fails + */ + static _ImeAppImpl* GetInstance(void); + + /** + * Returns the UiApp's instance pointer. + * + * @since 2.1 + * @return A pointer to the %UiApp instance, @n + * else @c null if it fails + */ + UiApp* GetUiAppInstance(void); + + /** + * Called when the application is started + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual bool OnCreate(void); + + /** + * Called when other application send the launch request to the application + * + * @since 2.1 + * @param[in] service The handle to the service + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnService(service_s* service); + + /** + * Called when the application is completely obscured by another application and becomes invisible + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnPause(void); + + /** + * Called when the application becomes visible + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnResume(void); + + /** + * Called once after the main loop of application exits + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnTerminate(void); + + /** + * Called when an orintation event occurs. + * + * @since 2.1 + * @param[in] orientation The information about the orientation event + */ + virtual void OnDeviceOrientationChanged(app_device_orientation_e orientation); + + /** + * Called when the application's state changes to Tizen::App::AppState::INITIALIZING. @n + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + virtual bool OnAppInitializing(void); + + /** + * Called when the application's INITIALIZING state is finished + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + virtual bool OnAppInitialized(void); + + + /** + * Called when the internal window handle is required. + * + * @since 2.1 + */ + virtual long OnWindowHandleRequest(void); + + /** + * Called when the application's state change to Tizen::App::AppState::TERMINATING. @n + * + * @since 2.1 + * @param[in] forcedTermination @c true if the application terminate by system or other application, else @c false. + * @return @c true if the method is successful, @n + * else @c false + */ + bool OnImeAppImplTerminating(void); + +private: + /** + * This is the default constructor for this class. + * + * @since 2.1 + */ + _ImeAppImpl(void); + + /** + * This is the constructor for this class. + * + * @since 2.1 + */ + _ImeAppImpl(UiApp* pUiApp); + + /** + * This is the copy constructor for the this class. + */ + _ImeAppImpl(const _ImeAppImpl& source); + + /** + * This is the assignment operator for this class. + */ + _ImeAppImpl& operator =(const _ImeAppImpl& source); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_ImeAppImpl(void); + + /** + * Gets the UI state of the IME application. + * + * @since 2.1 + * @return The UI state of the IME application + */ + AppUiState GetAppUiState(void) const; + + void OnForeground(void); + + void OnBackground(void); + +private: + static _ImeAppImpl* __pImeAppImpl; + + _AppImpl* __pAppImpl; + + AppUiState __appUiState; + + UiApp* __pUiApp; + + friend class UiApp; +}; //_ImeAppImpl + +} } //Tizen::App + +#endif // _FAPP_INTERNAL_IME_APP_IMPL_H_ diff --git a/src/app/FApp_LongevityManager.cpp b/src/app/FApp_LongevityManager.cpp new file mode 100644 index 0000000..5cf182c --- /dev/null +++ b/src/app/FApp_LongevityManager.cpp @@ -0,0 +1,60 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_LongevityManager.cpp + * @brief This is the implementation for the _LongevityManager.cpp class. + */ + +#include + +#include "FApp_LongevityManager.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace App +{ + +_LongevityManager::_LongevityManager(void) +{ + __objectList.Construct(); +} + +_LongevityManager::~_LongevityManager(void) +{ + __objectList.RemoveAll(true); +} + +_LongevityManager& +_LongevityManager::GetInstance(void) +{ + static _LongevityManager obj; + return obj; +} + +result +_LongevityManager::RegisterOwnership(Object& object) +{ + result r = __objectList.Add(object); + + SysLog(NID_APP, "[%s] %d entry registered.", GetErrorMessage(r), __objectList.GetCount()); + return r; +} + +} } // Tizen::App + diff --git a/src/app/FApp_LongevityManager.h b/src/app/FApp_LongevityManager.h new file mode 100644 index 0000000..d199806 --- /dev/null +++ b/src/app/FApp_LongevityManager.h @@ -0,0 +1,65 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_LongevityManager.h + * @brief This is the header file of the %_LongevityManager class. + * + * This header file contains the declarations of the %_LongevityManager class. + */ + +#ifndef _FAPP_INTERNAL_LONGEVITY_MANAGER_H_ +#define _FAPP_INTERNAL_LONGEVITY_MANAGER_H_ + +#include +#include + +namespace Tizen { namespace App +{ + +/** + * @class _LongevityManager + * @brief + * @since 2.1 + * + * This class controls the lifetime of heap-based singleton. + */ +class _LongevityManager +{ +public: + _LongevityManager(void); + + ~_LongevityManager(void); + + static _LongevityManager& GetInstance(void); + + result RegisterOwnership(Tizen::Base::Object& object); + +private: + _LongevityManager(const _LongevityManager& rhs); + + _LongevityManager& operator=(const _LongevityManager& rhs); + +private: + Tizen::Base::Collection::ArrayList __objectList; + +}; + +} } // Tizen::App + +#endif //_FAPP_INTERNAL_LONGEVITY_MANAGER_H_ + diff --git a/src/app/FApp_MapDataControlImpl.cpp b/src/app/FApp_MapDataControlImpl.cpp new file mode 100644 index 0000000..49b447a --- /dev/null +++ b/src/app/FApp_MapDataControlImpl.cpp @@ -0,0 +1,470 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_MapDataControlImpl.cpp + * @brief This is the implementation for the %_MapDataControlImpl class. + */ + +#include +#include + +#include + +#include +#include +#include +#include + +#include + +#include "FApp_AppControlManager.h" +#include "FApp_AppManagerProxy.h" +#include "FApp_MapDataControlImpl.h" +#include "FApp_AppArg.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::App; +using namespace Tizen::Io; + +namespace Tizen { namespace App +{ + +// private +_MapDataControlImpl::_MapDataControlImpl(void) + : __appId(L"") + , __providerId(L"") + , __access(_DATACONTROL_ACCESS_UNDEFINED) + , __pListener(null) +{ +} + +_MapDataControlImpl::~_MapDataControlImpl(void) +{ +} + +_MapDataControlImpl* +_MapDataControlImpl::GetInstance(MapDataControl& dc) +{ + return dc.__pMapDataControlImpl; +} + +const _MapDataControlImpl* +_MapDataControlImpl::GetInstance(const MapDataControl& dc) +{ + return dc.__pMapDataControlImpl; +} + +result +_MapDataControlImpl::StartMapDataControl(int type, const IList* pDataList, IMapDataControlResponseListener* pListener, + int* pReq) +{ + result r = E_SUCCESS; + + _AppArg* pArg = new(std::nothrow) _AppArg; // XXX: pArg will be released in _AppManagerImpl::LaunchApp(). + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pArg->Construct(*this, static_cast <_DataControlRequestType>(type), pDataList); + + _AppControlManager* pAppManagerImpl = _AppControlManager::GetInstance(); + int req = -1; + + if (__pListener) + { + SysLog(NID_APP, "listener address: 0x%x", (void*) __pListener); + + // reqId is system-wide id because the bundle is system-wide. + _AppControlManager::_RequestGuard reqObj = _AppControlManager::_RequestGuard(*pAppManagerImpl, pArg, MapDataControlCallback, __pListener, -1); + req = reqObj.GetRequestNumber(); + + r = pAppManagerImpl->LaunchApp(__appId, pArg, req); + SysTryCatch(NID_APP, r == E_SUCCESS, reqObj.Invalidate(), r, "[%s] Propgated.", GetErrorMessage(r)); + + if (pReq) + { + *pReq = req; + } + } + else + { + r = pAppManagerImpl->LaunchApp(__appId, pArg); + delete pArg; + } + + { + // registers to server + _IAppManager* pAppManager = _AppManagerProxy::GetService(); + + // actually register, not launch + if (pAppManager) + { + pAppManager->LaunchApplication(__appId, null, req); + } + } + +CATCH: + + return r; +} + +result +_MapDataControlImpl::GetValue(const String& dataId, const String& key, + RequestId& reqId, int pageNo, int countPerPage) +{ + SysTryReturnResult(NID_APP, pageNo > 0, E_INVALID_ARG, "The specified pageNo parameter is less than 1"); + SysTryReturnResult(NID_APP, countPerPage > 0, E_INVALID_ARG, "The specified countPerPage parameter is less than 1"); + SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_READ) > 0, E_ILLEGAL_ACCESS, + "The GetValue query is not permitted by DataControl provider."); + + int id = 0; + result r = E_SUCCESS; + + ArrayList* pArgList = null; + pArgList = new ArrayList(); + pArgList->Construct(); + + pArgList->Add(*(new String(dataId))); + pArgList->Add(*(new String(key))); + + String* pPageNo = new String(); + pPageNo->Append(pageNo); + pArgList->Add(*pPageNo); + + String* pCountPerPage = new String(); + pCountPerPage->Append(countPerPage); + pArgList->Add(*pCountPerPage); + + r = StartMapDataControl(_DATACONTROL_REQUEST_TYPE_MAP_QUERY, pArgList, __pListener, &id); + + reqId = static_cast< RequestId >(id); + + SysLog(NID_APP, "dataId: %ls, key: %ls, reqId: %d, pageNo: %d, countPerPage: %d", + dataId.GetPointer(), key.GetPointer(), reqId, pageNo, countPerPage); + + pArgList->RemoveAll(true); + delete pArgList; + + return r; +} + +result +_MapDataControlImpl::MapDataControlCallback(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop) +{ + ArrayList* pResultList = null; + ArrayList* pOrigList = null; + String* pRequestType = null; + String* pResult = null; + String* pReqId = null; + String* pProviderId = null; + String* pDataId = null; + String* pErrorMsg = null; + String* pResultCount = null; + String* pValue = null; + ArrayList* pResultValueList = null; + int resultCount = 0; + int requestType = 0; + int reqId = 0; + int providerRes = 0; + bool providerResult = true; + bundle* origBundle = null; + bundle* resBundle = null; + result r = E_SUCCESS; + + SysTryReturnResult(NID_APP, pResArg != null, E_INVALID_ARG, "Empty result callback."); + SysLog(NID_APP, "appsvc result value: %d", res); + + resBundle = pResArg->GetBundle(); + if (resBundle) + { + IMapDataControlResponseListener* pListener = static_cast< IMapDataControlResponseListener* >(data); + + if (pListener != null && typeid(pListener) == typeid(IMapDataControlResponseListener*)) + { + const char* p = null; + + // result list + pResultList = _AppArg::GetListN(resBundle, OSP_K_ARG); + SysTryCatch(NID_APP, pResultList, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + + pResult = dynamic_cast (pResultList->GetAt(0)); + SysTryCatch(NID_APP, pResult, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + Integer::Parse(*pResult, providerRes); + providerResult = static_cast< bool >(providerRes); + + pErrorMsg = dynamic_cast< String* >(pResultList->GetAt(1)); + SysTryCatch(NID_APP, pErrorMsg, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + + // request info + origBundle = pArg->GetBundle(); + + p = appsvc_get_data(origBundle, OSP_K_DATACONTROL_REQUEST_TYPE); + SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + pRequestType = new (std::nothrow) String(p); + SysTryCatch(NID_APP, pRequestType, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + Integer::Parse(*pRequestType, requestType); + + p = appsvc_get_data(origBundle, OSP_K_REQUEST_ID); + SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + pReqId = new (std::nothrow) String(p); + SysTryCatch(NID_APP, pReqId, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + Integer::Parse(*pReqId, reqId); + + p = appsvc_get_data(origBundle, OSP_K_DATACONTROL_PROVIDER); + SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + pProviderId = new (std::nothrow) String(p); + SysTryCatch(NID_APP, pProviderId, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + + pOrigList = _AppArg::GetListN(origBundle, OSP_K_ARG); + SysTryCatch(NID_APP, pOrigList, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + pDataId = dynamic_cast (pOrigList->GetAt(0)); + SysTryCatch(NID_APP, pDataId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + + SysLog(NID_APP, "result: %ld, requestType: %d, reqId: %d, providerId: %ls, dataId: %ls, errorMsg: %ls ", + providerRes, requestType, reqId, pProviderId->GetPointer(), pDataId->GetPointer(), pErrorMsg->GetPointer()); + + switch (static_cast< _DataControlRequestType >(requestType)) + { + case _DATACONTROL_REQUEST_TYPE_MAP_QUERY: + { + pResultValueList = new (std::nothrow) ArrayList(); + SysTryCatch(NID_APP, pResultValueList, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + + if (providerResult == true) + { + pResultCount = dynamic_cast (pResultList->GetAt(2)); + SysTryCatch(NID_APP, pResultCount, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + Integer::Parse(*pResultCount, resultCount); + + int index = 3; + while (resultCount) + { + pValue = dynamic_cast (pResultList->GetAt(index)); + SysTryCatch(NID_APP, pValue, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + + pResultValueList->Add(*(new (std::nothrow) String(*pValue))); + resultCount--; + index++; + } + } + + pListener->OnMapDataControlGetValueResponseReceived(static_cast (reqId), *pProviderId, + *pDataId, *pResultValueList, providerResult, pErrorMsg); + + pResultValueList->RemoveAll(true); + delete pResultValueList; + break; + } + case _DATACONTROL_REQUEST_TYPE_MAP_INSERT: + pListener->OnMapDataControlAddValueResponseReceived(static_cast (reqId), *pProviderId, + *pDataId, providerResult, pErrorMsg); + break; + case _DATACONTROL_REQUEST_TYPE_MAP_UPDATE: + pListener->OnMapDataControlSetValueResponseReceived(static_cast (reqId), *pProviderId, + *pDataId, providerResult, pErrorMsg); + break; + case _DATACONTROL_REQUEST_TYPE_MAP_DELETE: + pListener->OnMapDataControlRemoveValueResponseReceived(static_cast (reqId), *pProviderId, + *pDataId, providerResult, pErrorMsg); + break; + default: + break; + } + + pResultList->RemoveAll(true); + delete pResultList; + + pOrigList->RemoveAll(true); + delete pOrigList; + + delete pRequestType; + delete pReqId; + delete pProviderId; + } + } + + return E_SUCCESS; + +CATCH: + if (pResultList) + { + pResultList->RemoveAll(true); + delete pResultList; + } + + if (pResultValueList) + { + pResultValueList->RemoveAll(true); + delete pResultValueList; + } + + if (pOrigList) + { + pOrigList->RemoveAll(true); + delete pOrigList; + } + + delete pRequestType; + delete pReqId; + delete pProviderId; + + return r; +} + +result +_MapDataControlImpl::AddValue(const String& dataId, const String& key, + const String& value, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS, + "The AddValue query is not permitted by DataControl provider."); + + int id = 0; + result r = E_SUCCESS; + + ArrayList* pArgList = null; + pArgList = new ArrayList(); + pArgList->Construct(); + + pArgList->Add(*(new String(dataId))); + pArgList->Add(*(new String(key))); + pArgList->Add(*(new String(value))); + + r = StartMapDataControl(_DATACONTROL_REQUEST_TYPE_MAP_INSERT, pArgList, __pListener, &id); + + reqId = static_cast< RequestId >(id); + + SysLog(NID_APP, "dataId: %ls, key: %ls, value: %ls, reqId: %d", + dataId.GetPointer(), key.GetPointer(), value.GetPointer(), reqId); + + pArgList->RemoveAll(true); + delete pArgList; + + return r; +} + +result +_MapDataControlImpl::SetValue(const String& dataId, const String& key, + const String& oldValue, const String& newValue, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS, + "The SetValue query is not permitted by DataControl provider."); + + int id = 0; + result r = E_SUCCESS; + + ArrayList* pArgList = null; + pArgList = new ArrayList(); + pArgList->Construct(); + + pArgList->Add(*(new String(dataId))); + pArgList->Add(*(new String(key))); + pArgList->Add(*(new String(oldValue))); + pArgList->Add(*(new String(newValue))); + + r = StartMapDataControl(_DATACONTROL_REQUEST_TYPE_MAP_UPDATE, pArgList, __pListener, &id); + + reqId = static_cast< RequestId >(id); + + SysLog(NID_APP, "dataId: %ls, key: %ls, oldValue: %ls, newValue: %ls, reqId: %d", + dataId.GetPointer(), key.GetPointer(), oldValue.GetPointer(), newValue.GetPointer(), reqId); + + pArgList->RemoveAll(true); + delete pArgList; + + return r; +} + +result +_MapDataControlImpl::RemoveValue(const String& dataId, const String& key, + const String& value, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS, + "The RemoveValue query is not permitted by DataControl provider."); + + int id = 0; + result r = E_SUCCESS; + + ArrayList* pArgList = null; + pArgList = new ArrayList(); + pArgList->Construct(); + + pArgList->Add(*(new String(dataId))); + pArgList->Add(*(new String(key))); + pArgList->Add(*(new String(value))); + + r = StartMapDataControl(_DATACONTROL_REQUEST_TYPE_MAP_DELETE, pArgList, __pListener, &id); + + reqId = static_cast< RequestId >(id); + + SysLog(NID_APP, "dataId: %ls, key: %ls, value: %ls, reqId: %d", + dataId.GetPointer(), key.GetPointer(), value.GetPointer(), reqId); + + pArgList->RemoveAll(true); + delete pArgList; + + return r; +} + +result +_MapDataControlImpl::SetMapDataControlResponseListener(IMapDataControlResponseListener* pListener) +{ + __pListener = pListener; + + return E_SUCCESS; +} + +// private +MapDataControl* +_MapDataControlImpl::CreateMapDataControl(const AppId& appId, const String& providerId, const String& access) +{ + MapDataControl* pDc = null; + _MapDataControlImpl* pDcImpl = null; + + pDc = new (std::nothrow) MapDataControl; + SysTryReturn(NID_APP, pDc != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory was insufficient"); + + pDcImpl = _MapDataControlImpl::GetInstance(*pDc); + pDcImpl->__appId = appId; + pDcImpl->__providerId = providerId; + + if (access == L"readonly") + { + pDcImpl->__access = _DATACONTROL_ACCESS_READ; + } + else if (access == L"writeonly") + { + pDcImpl->__access = _DATACONTROL_ACCESS_WRITE; + } + else if (access == L"readwrite") + { + pDcImpl->__access = _DATACONTROL_ACCESS_READWRITE; + } + else + { + pDcImpl->__access = _DATACONTROL_ACCESS_UNDEFINED; + SysLog(NID_IO, "The accessibility of DataControl provider is invalid."); + } + + return pDc; +} + +}} // Tizen::App + diff --git a/src/app/FApp_MapDataControlImpl.h b/src/app/FApp_MapDataControlImpl.h new file mode 100644 index 0000000..c080ff6 --- /dev/null +++ b/src/app/FApp_MapDataControlImpl.h @@ -0,0 +1,98 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_MapDataControlImpl.h + * @brief This is the header file for the %_MapDataControlImpl class. + */ + +#ifndef _FAPP_INTERNAL_MAP_DATA_CONTROL_IMPL_H_ +#define _FAPP_INTERNAL_MAP_DATA_CONTROL_IMPL_H_ + +#include + +#include +#include +#include +#include + +#include "FApp_AppControlManager.h" + +namespace Tizen { namespace Base +{ +namespace Collection +{ +class IList; +} +}} + +namespace Tizen { namespace App { + +class IMapDataControlResponseListener; +class _AppArg; + +class _MapDataControlImpl + : public Tizen::Base::Object +{ + +public: + virtual ~_MapDataControlImpl(void); + + static _MapDataControlImpl* GetInstance(MapDataControl& dc); + + static const _MapDataControlImpl* GetInstance(const MapDataControl& dc); + + result AddValue(const Tizen::Base::String& dataId, const Tizen::Base::String& key, + const Tizen::Base::String& value, RequestId& reqId); + + result GetValue(const Tizen::Base::String& dataId, const Tizen::Base::String& key, + RequestId& reqId, int pageNo = 1, int countPerPage = 20); + + result SetValue(const Tizen::Base::String& dataId, const Tizen::Base::String& key, + const Tizen::Base::String& oldValue, const Tizen::Base::String& newValue, RequestId& reqId); + + result RemoveValue(const Tizen::Base::String& dataId, const Tizen::Base::String& key, + const Tizen::Base::String& value, RequestId& reqId); + + result SetMapDataControlResponseListener(IMapDataControlResponseListener* pListener); + + static result MapDataControlCallback(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop); + +private: + _MapDataControlImpl(void); + + static MapDataControl* CreateMapDataControl(const AppId& appId, const Tizen::Base::String& providerId, + const Tizen::Base::String& access); + + result StartMapDataControl(int type, const Tizen::Base::Collection::IList* pDataList, + IMapDataControlResponseListener* pListener, int* pReq); + + Tizen::Base::String __appId; + Tizen::Base::String __providerId; + int __access; + IMapDataControlResponseListener* __pListener; + + friend class MapDataControl; + friend class _AppManagerImpl; + friend class _AppArg; + +}; // _MapDataControlImpl + +}} // Tizen::App + +#endif // _FAPP_INTERNAL_MAP_DATA_CONTROL_IMPL_H_ + diff --git a/src/app/FApp_NotificationManagerImpl.cpp b/src/app/FApp_NotificationManagerImpl.cpp new file mode 100644 index 0000000..0b69e45 --- /dev/null +++ b/src/app/FApp_NotificationManagerImpl.cpp @@ -0,0 +1,582 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationManagerImpl.cpp + * @brief This is the placeholder for _NotificationManagerImpl class. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include "FApp_NotificationManagerImpl.h" +#include "FApp_NotificationManagerProxy.h" +#include "FApp_AppInfo.h" +#include "FAppPkg_PackageManagerImpl.h" +#include "FApp_Aul.h" +#include "FApp_AppArg.h" + +using namespace Tizen::Base; +using namespace Tizen::App; +using namespace Tizen::App::Package; + +extern "C" int service_create_request(bundle *data, service_h *service); + +namespace +{ + +result +ConvertNotificationResult(int error) +{ + switch (error) + { + case UI_NOTIFICATION_ERROR_NONE: + return E_SUCCESS; + case UI_NOTIFICATION_ERROR_INVALID_PARAMETER: + return E_INVALID_ARG; + case UI_NOTIFICATION_ERROR_OUT_OF_MEMORY: + return E_OUT_OF_MEMORY; + case UI_NOTIFICATION_ERROR_DB_FAILED: + return E_DATABASE; + case UI_NOTIFICATION_ERROR_NO_SUCH_FILE: + return E_SYSTEM; + case UI_NOTIFICATION_ERROR_INVALID_STATE: + return E_SYSTEM; + default: + return E_SYSTEM; + } +} + +ui_notification_progress_type_e +ConvertToNotificationProgressType(int progressType) +{ + switch (progressType) + { + case ONGOING_ACTIVITY_TYPE_TEXT: + return UI_NOTIFICATION_PROGRESS_TYPE_PERCENTAGE; + case ONGOING_ACTIVITY_TYPE_PROGRESS_BYTE: + return UI_NOTIFICATION_PROGRESS_TYPE_SIZE; + case ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE: + return UI_NOTIFICATION_PROGRESS_TYPE_PERCENTAGE; + default: + return UI_NOTIFICATION_PROGRESS_TYPE_PERCENTAGE; + } +} + +bool +IsPosted(ui_notification_h handle) +{ + struct ui_notification_s + { + void* raw_handle; + bool ongoing; + bool posted; + bool removed; + char *icon; + struct tm *time; + char *title; + char *content; + service_h service; + char *sound; + bool vibration; + }; + + if (handle == NULL) + { + return false; + } + + ui_notification_s* pStruct = reinterpret_cast(handle); + + return pStruct->posted; +} + +} + +namespace Tizen { namespace App +{ + +_NotificationManagerImpl::_NotificationManagerImpl(void) +: __pNotificationManager(null) +{ +} + +_NotificationManagerImpl::~_NotificationManagerImpl(void) +{ +} + +result +_NotificationManagerImpl::Construct(void) +{ + result r = E_SUCCESS; + + __pNotificationManager = new (std::nothrow) _NotificationManagerProxy; + SysTryReturnResult(NID_APP, __pNotificationManager != null, E_OUT_OF_MEMORY, "__pNotificationManagerProxy creation failed."); + + r = __pNotificationManager->Construct(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "__pNotificationManager->Construct() failed [%s].", GetErrorMessage(r)); + + return E_SUCCESS; + +CATCH: + delete __pNotificationManager; + __pNotificationManager = null; + + return r; +} + +const _NotificationManagerImpl* +_NotificationManagerImpl::GetInstance(const NotificationManager& notiMgr) +{ + return notiMgr.__pNotificationManagerImpl; +} + +_NotificationManagerImpl* +_NotificationManagerImpl::GetInstance(NotificationManager& notiMgr) +{ + return notiMgr.__pNotificationManagerImpl; +} + +int +_NotificationManagerImpl::GetBadgeNumber(void) const +{ + int count = -1; + notification_get_badge(NULL, NOTIFICATION_GROUP_ID_NONE, &count); + return count; +} + +result +_NotificationManagerImpl::OngoingImpl(const String& messageText, const String& launchArguments) const +{ + return NotifyImpl(messageText, -1, launchArguments, true); +} + +result +_NotificationManagerImpl::OngoingImpl(const AppId& appId, const String& messageText, const String& launchArguments) const +{ + + return NotifyImpl(appId, messageText, -1, launchArguments, true); +} + +result +_NotificationManagerImpl::NotifyImpl(const String& messageText, int badgeNumber, + const String& launchArguments, + bool isOngoing) const +{ + result r = E_SUCCESS; + int retcode = 0; + char* pMsg = null; + ui_notification_h core = NULL; + char* pkgname = NULL; + bundle* pKb = NULL; + service_h svc = NULL; + _AppArg arg; + + if (!messageText.IsEmpty()) + { + SysTryReturnResult(NID_APP, + messageText.GetLength() <= MAX_NOTIFICATION_MESSAGE_LENGTH, E_INVALID_ARG, + "MessageText is greater than MAX_NOTIFICATION_MESSAGE_LENGTH."); + + retcode = ui_notification_create(isOngoing, &core); + SysTryReturnResult(NID_APP, retcode == UI_NOTIFICATION_ERROR_NONE, E_SYSTEM, "Notification creation error : 0x%x.", retcode); + + pMsg = _StringConverter::CopyToCharArrayN(messageText); + + int ret = ui_notification_set_content(core, pMsg); + SysTryLog(NID_APP, ret == UI_NOTIFICATION_ERROR_NONE, "Setting notification content failure : %d.", ret); + + app_get_package(&pkgname); + SysTryCatch(NID_APP, pkgname != NULL, r = E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Cannot acquire package name for current application."); + + r = arg.Construct(launchArguments); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + pKb = arg.GetBundle(); + service_create_request(pKb, &svc); + + service_set_package(svc, pkgname); + r = ConvertNotificationResult(ui_notification_set_service(core, svc)); + SysTryLog(NID_APP, !IsFailed(r), "[%s] Notification set service failed.", GetErrorMessage(r)); + + SysLog(NID_APP, "Sending notification[%ls] for package %s.", messageText.GetPointer(), pkgname); + + r = ConvertNotificationResult(ui_notification_post(core)); + SysTryLog(NID_APP, !IsFailed(r), "[%s] Notification post failure.", GetErrorMessage(r)); + } + + if (badgeNumber >= 0) + { + notification_set_badge(NULL, NOTIFICATION_GROUP_ID_NONE, badgeNumber); + SysLog(NID_APP, "Badge number is set to %d.", badgeNumber); + } + +CATCH: + delete[] pMsg; + if (pkgname) + { + free(pkgname); + } + + if (core) + { + ui_notification_destroy(core); + } + service_destroy(svc); + return r; +} + +result +_NotificationManagerImpl::NotifyImpl(const AppId& appId, const String& messageText, int badgeNumber, + const String& launchArguments, + bool isOngoing) const +{ + result r = E_SUCCESS; + int retcode = 0; + char* pMsg = null; + char* pIcon = NULL; + char* pName = NULL; + ui_notification_h core = NULL; + char buffer[256]; + bundle* pKb = NULL; + service_h svc = NULL; + _AppArg arg; + + memset(buffer, 0, 256); + + bool b = _Aul::IsInstalled(appId); + + SysTryReturnResult(NID_APP, b == true, E_APP_NOT_INSTALLED, "The application %ls is not installed", appId.GetPointer()); + + if (!isOngoing || !messageText.IsEmpty()) + { + SysTryReturnResult(NID_APP, + messageText.GetLength() <= MAX_NOTIFICATION_MESSAGE_LENGTH, E_INVALID_ARG, + "MessageText is greater than MAX_NOTIFICATION_MESSAGE_LENGTH."); + + retcode = ui_notification_create(isOngoing, &core); + SysTryReturnResult(NID_APP, retcode == UI_NOTIFICATION_ERROR_NONE, E_SYSTEM, "Notification creation error : 0x%x.", retcode); + + pMsg = _StringConverter::CopyToCharArrayN(messageText); + + int ret = ui_notification_set_content(core, pMsg); + SysTryLog(NID_APP, ret == UI_NOTIFICATION_ERROR_NONE, "Setting notification content failure : %d.", ret); + + snprintf(buffer, 256, "%ls", appId.GetPointer()); + + app_manager_get_app_icon_path(buffer, &pIcon); + r = ConvertNotificationResult(ui_notification_set_icon(core, pIcon)); + SysTryLog(NID_APP, !IsFailed(r), "[%s] Notification set icon failed.", GetErrorMessage(r)); + + app_manager_get_app_name(buffer, &pName); + r = ConvertNotificationResult(ui_notification_set_title(core, pName)); + SysTryLog(NID_APP, !IsFailed(r), "[%s] Notification set title failed.", GetErrorMessage(r)); + + r = arg.Construct(launchArguments); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + pKb = arg.GetBundle(); + service_create_request(pKb, &svc); + + service_set_app_id(svc, buffer); + r = ConvertNotificationResult(ui_notification_set_service(core, svc)); + SysTryLog(NID_APP, !IsFailed(r), "[%s] Notification set service failed.", GetErrorMessage(r)); + + SysLog(NID_APP, "Sending notification[%ls] for package %s.", messageText.GetPointer(), buffer); + + r = ConvertNotificationResult(ui_notification_post(core)); + SysTryLog(NID_APP, !IsFailed(r), "[%s] Notification post failure.", GetErrorMessage(r)); + } + + if (badgeNumber >= 0) + { + notification_set_badge(buffer, NOTIFICATION_GROUP_ID_NONE, badgeNumber); + SysLog(NID_APP, "Badge number is set to %d.", badgeNumber); + } + +CATCH: + delete[] pMsg; + + if (core) + { + ui_notification_destroy(core); + } + + if (pIcon) + { + free(pIcon); + } + + if (pName) + { + free(pName); + } + service_destroy(svc); + return r; +} + + +result +_NotificationManagerImpl::Notify(int badgeNumber) const +{ + SysTryReturnResult(NID_APP, badgeNumber >= 0, E_INVALID_ARG, "BadgeNumber is less than 0."); + + if (badgeNumber > MAX_NOTIFICATION_BADGE_NUMBER) + { + badgeNumber = MAX_NOTIFICATION_BADGE_NUMBER; + } + + String messageText = String(L""); + String appMessage = String(L""); + + return NotifyImpl(messageText, badgeNumber, appMessage, false); +} + +result +_NotificationManagerImpl::Notify(const String& messageText) const +{ + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + + String appMessage = String(L""); + + return NotifyImpl(messageText, -1, appMessage, false); +} + +result +_NotificationManagerImpl::Notify(const String& messageText, int badgeNumber) const +{ + SysTryReturnResult(NID_APP, badgeNumber >= 0, E_INVALID_ARG, "BadgeNumber is less than 0."); + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + + if (badgeNumber > MAX_NOTIFICATION_BADGE_NUMBER) + { + badgeNumber = MAX_NOTIFICATION_BADGE_NUMBER; + } + + String appMessage = String(L""); + + return NotifyImpl(messageText, badgeNumber, appMessage, false); +} + +result +_NotificationManagerImpl::Notify(const String& messageText, int badgeNumber, const String& launchArguments) const +{ + SysTryReturnResult(NID_APP, badgeNumber >= 0, E_INVALID_ARG, "BadgeNumber is less than 0."); + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + SysTryReturnResult(NID_APP, + launchArguments != null && launchArguments.GetLength() > 0, E_INVALID_ARG, + "launchArguments is less than 0."); + + SysTryReturnResult(NID_APP, + launchArguments.GetLength() <= MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH, E_INVALID_ARG, + "launchArguments is greater than MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH."); + + if (badgeNumber > MAX_NOTIFICATION_BADGE_NUMBER) + { + badgeNumber = MAX_NOTIFICATION_BADGE_NUMBER; + } + + return NotifyImpl(messageText, badgeNumber, launchArguments, false); +} + +int +_NotificationManagerImpl::GetBadgeNumber(const AppId& appId) const +{ + bool b = _Aul::IsInstalled(appId); + + SysTryReturn(NID_APP, b == true, -1, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The application %ls is not installed", + appId.GetPointer()); + + char buffer[256]; + int count = -1; + + memset(buffer, 0, 256); + + snprintf(buffer, 256, "%ls", appId.GetPointer()); + + notification_get_badge(buffer, NOTIFICATION_GROUP_ID_NONE, &count); + + return count; +} + + +result +_NotificationManagerImpl::NotifyOnBehalf(const AppId& appId, int badgeNumber) const +{ + SysTryReturnResult(NID_APP, badgeNumber >= 0, E_INVALID_ARG, "BadgeNumber is less than 0."); + + String messageText = String(L""); + String appMessage = String(L""); + return NotifyImpl(appId, messageText, badgeNumber, appMessage); +} + +result +_NotificationManagerImpl::NotifyOnBehalf(const AppId& appId, const String& messageText) const +{ + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + + return NotifyImpl(appId, messageText, -1, String(L"")); +} + +result +_NotificationManagerImpl::NotifyOnBehalf(const AppId& appId, const String& messageText, int badgeNumber) const +{ + SysTryReturnResult(NID_APP, badgeNumber >= 0, E_INVALID_ARG, "BadgeNumber is less than 0."); + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + + return NotifyImpl(appId, messageText, badgeNumber, String(L"")); +} + +result +_NotificationManagerImpl::NotifyOnBehalf(const AppId& appId, const String& messageText, const String& launchArguments) const +{ + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + SysTryReturnResult(NID_APP, launchArguments.GetLength() > 0, E_INVALID_ARG, "launchArguments is less than 0."); + SysTryReturnResult(NID_APP, + launchArguments.GetLength() <= MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH, E_INVALID_ARG, + "launchArguments is greater than MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH."); + + return NotifyImpl(appId, messageText, -1, launchArguments); +} + +result +_NotificationManagerImpl::NotifyOnBehalf(const AppId& appId, const String& messageText, int badgeNumber, + const String& launchArguments) const +{ + SysTryReturnResult(NID_APP, badgeNumber >= 0, E_INVALID_ARG, "BadgeNumber is less than 0."); + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + SysTryReturnResult(NID_APP, launchArguments.GetLength() > 0, E_INVALID_ARG, "launchArguments is less than 0."); + SysTryReturnResult(NID_APP, + launchArguments.GetLength() <= MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH, E_INVALID_ARG, + "launchArguments is greater than MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH."); + + return NotifyImpl(appId, messageText, badgeNumber, launchArguments); +} + +result +_NotificationManagerImpl::NotifyOngoingActivity(const String& messageText) const +{ + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + + return OngoingImpl(messageText, String(L"")); +} + +result +_NotificationManagerImpl::NotifyOngoingActivity(const String& messageText, const String& launchArguments) const +{ + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + SysTryReturnResult(NID_APP, launchArguments.GetLength() > 0, E_INVALID_ARG, "launchArguments is less than 0."); + SysTryReturnResult(NID_APP, + launchArguments.GetLength() <= MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH, E_INVALID_ARG, + "launchArguments is greater than MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH."); + + return OngoingImpl(messageText, launchArguments); +} + +result +_NotificationManagerImpl::NotifyOngoingActivityOnBehalf(const AppId& appId, const String& messageText) const +{ + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + + return OngoingImpl(appId, messageText, String(L"")); +} + +result +_NotificationManagerImpl::NotifyOngoingActivityOnBehalf(const AppId& appId, const String& messageText, + const String& launchArguments) const +{ + SysTryReturnResult(NID_APP, messageText.GetLength() > 0, E_INVALID_ARG, "MessageText is less than 0."); + SysTryReturnResult(NID_APP, launchArguments.GetLength() > 0, E_INVALID_ARG, "launchArguments is less than 0."); + SysTryReturnResult(NID_APP, + launchArguments.GetLength() <= MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH, E_INVALID_ARG, + "launchArguments is greater than MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH."); + + return OngoingImpl(appId, messageText, launchArguments); +} + +result +_NotificationManagerImpl::RemoveOngoingActivityNotification(void) +{ + result r = E_SUCCESS; + + notification_error_e err = notification_delete_all_by_type(NULL, NOTIFICATION_TYPE_ONGOING); + switch (err) + { + case NOTIFICATION_ERROR_NONE: + r = E_SUCCESS; + break; + + case NOTIFICATION_ERROR_INVALID_DATA: + r = E_INVALID_ARG; + break; + + default: + r = E_SYSTEM; + break; + } + + return r; +} + +result +_NotificationManagerImpl::RemoveOngoingActivityNotificationOnBehalf(const AppId& appId) +{ + return __pNotificationManager->RemoveNotification(appId, true); +} + +result +_NotificationManagerImpl::RemoveNotification(void) +{ + result r = E_SUCCESS; + + notification_error_e err = notification_delete_all_by_type(NULL, NOTIFICATION_TYPE_NOTI); + switch (err) + { + case NOTIFICATION_ERROR_NONE: + r = E_SUCCESS; + break; + + case NOTIFICATION_ERROR_INVALID_DATA: + r = E_INVALID_ARG; + break; + + default: + r = E_SYSTEM; + break; + } + + return r; +} + +result +_NotificationManagerImpl::RemoveNotificationOnBehalf(const AppId& appId) +{ + return __pNotificationManager->RemoveNotification(appId,false); +} + +}; +}; // Tizen::App diff --git a/src/app/FApp_NotificationManagerIpcMessages.cpp b/src/app/FApp_NotificationManagerIpcMessages.cpp new file mode 100644 index 0000000..85cf259 --- /dev/null +++ b/src/app/FApp_NotificationManagerIpcMessages.cpp @@ -0,0 +1,46 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationManagerIpcMessages.cpp + * @brief This file contains IPC message class generated by macros. + */ + +#define IPC_MESSAGE_IMPL +#include "FApp_NotificationManagerIpcMessages.h" + +// Generate constructors. +#include "ipc/struct_constructor_macros.h" +#include "FApp_NotificationManagerIpcMessages.h" +// Generate destructors. + +#include "ipc/struct_destructor_macros.h" +#include "FApp_NotificationManagerIpcMessages.h" + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC +{ +#include "FApp_NotificationManagerIpcMessages.h" +} // namespace IPC + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC +{ +#include "FApp_NotificationManagerIpcMessages.h" +} // namespace IPC diff --git a/src/app/FApp_NotificationManagerProxy.cpp b/src/app/FApp_NotificationManagerProxy.cpp new file mode 100644 index 0000000..2491d26 --- /dev/null +++ b/src/app/FApp_NotificationManagerProxy.cpp @@ -0,0 +1,88 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationManagerProxy.cpp + * @brief This is the implementation for the _NotificationManagerProxy.cpp class. + */ + +#include +#include + +#include +#include +#include + +#include "FApp_NotificationManagerIpcMessages.h" +#include "FApp_NotificationManagerProxy.h" +#include "FApp_NotificationManagerEventParamTraits.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace App +{ + +_NotificationManagerProxy::_NotificationManagerProxy(void) + : __pIpcClient(null) +{ +} + +_NotificationManagerProxy::~_NotificationManagerProxy(void) +{ +} + +result +_NotificationManagerProxy::Construct() +{ + __pIpcClient = new (std::nothrow) Tizen::Io::_IpcClient(); + SysTryReturnResult(NID_APP, __pIpcClient != null, E_OUT_OF_MEMORY, "_IpcClient creation failed."); + + result r = __pIpcClient->Construct("osp.app.ipcserver.notificationmanager"); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "_IpcClient constructing failed [%s].", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_NotificationManagerProxy::NotifyMessage(const AppId& appId, const NotificationMessage& notiMessage, bool Ongoing) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) NotificationManager_NotifyMessage(appId, notiMessage, Ongoing, &response)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + + SysTryReturn(NID_APP, !IsFailed(r), r, r, "__pIpcClient->SendRequest is failed. (%s)", GetErrorMessage(r)); + + return response; +} + +result +_NotificationManagerProxy::RemoveNotification(const AppId& appId, bool Ongoing) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) NotificationManager_RemoveNotification(appId, Ongoing, &response)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + + SysTryReturn(NID_APP, !IsFailed(r), r, r, "__pIpcClient->SendRequest is failed. (%s)", GetErrorMessage(r)); + + return response; +} + +} } // Tizen::App diff --git a/src/app/FApp_NotificationManagerProxy.h b/src/app/FApp_NotificationManagerProxy.h new file mode 100644 index 0000000..76ce27a --- /dev/null +++ b/src/app/FApp_NotificationManagerProxy.h @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationManagerProxy.h + * @brief This is the header file of the _NotificationManagerProxy class. + */ + +#ifndef _FAPP_INTERNAL_NOTIFICATION_MANAGER_PROXY_H_ +#define _FAPP_INTERNAL_NOTIFICATION_MANAGER_PROXY_H_ + +#include +#include +#include +#include + +#include "FApp_Types.h" + +namespace Tizen { namespace Io { class _IpcClient; } } + +namespace Tizen { namespace App +{ + +class NotificationMessage; + +/** + * @class _NotificationManagerProxy + * @brief + * @since 2.1 + */ +class _NotificationManagerProxy + : public Tizen::Base::Object +{ +public: + _NotificationManagerProxy(void); + virtual ~_NotificationManagerProxy(void); + + result Construct(void); + + result NotifyMessage(const AppId& appId, const NotificationMessage& message, bool Ongoing); + result RemoveNotification(const AppId& appId, bool Ongoing); + + +private: + _NotificationManagerProxy(const _NotificationManagerProxy& rhs); + + _NotificationManagerProxy& operator =(const _NotificationManagerProxy& rhs); + +private: + Tizen::Io::_IpcClient* __pIpcClient; + +}; // _NotificationManagerProxy + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_NOTIFICATION_MANAGER_PROXY_H_ diff --git a/src/app/FApp_NotificationMessageImpl.cpp b/src/app/FApp_NotificationMessageImpl.cpp new file mode 100644 index 0000000..bf8bce2 --- /dev/null +++ b/src/app/FApp_NotificationMessageImpl.cpp @@ -0,0 +1,366 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationMessageImpl.cpp + * @brief This is the placeholder for _NotificationMessageImpl class. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include "FApp_NotificationMessageImpl.h" + + +using namespace Tizen::Base; +using namespace Tizen::Io; + +namespace Tizen { namespace App +{ + +_NotificationMessageImpl::_NotificationMessageImpl(bool appBinding) + : __appBinding(true) + , __badgeNumber(-1) + , __badgeOffset(0) + , __progressValue(-1) + , __activityType(ONGOING_ACTIVITY_TYPE_TEXT) +{ +} + +_NotificationMessageImpl::_NotificationMessageImpl(const _NotificationMessageImpl& notificationMessage) + : __appBinding(notificationMessage.__appBinding) + , __badgeNumber(notificationMessage.__badgeNumber) + , __badgeOffset(notificationMessage.__badgeOffset) + , __progressValue(notificationMessage.__progressValue) + , __activityType(notificationMessage.__activityType) + , __alertText(notificationMessage.__alertText) + , __appMessage(notificationMessage.__appMessage) + , __titleText(notificationMessage.__titleText) + , __iconFilePath(notificationMessage.__iconFilePath) + , __soundFilePath(notificationMessage.__soundFilePath) +{ +} + +_NotificationMessageImpl::~_NotificationMessageImpl() +{ +} + +_NotificationMessageImpl& +_NotificationMessageImpl::operator =(const _NotificationMessageImpl& notificationMessage) +{ + if (this != ¬ificationMessage) + { + __appBinding = notificationMessage.__appBinding; + __badgeNumber = notificationMessage.__badgeNumber; + __badgeOffset = notificationMessage.__badgeOffset; + __progressValue = notificationMessage.__progressValue; + __activityType = notificationMessage.__activityType; + __alertText = notificationMessage.__alertText; + __appMessage = notificationMessage.__appMessage; + __titleText = notificationMessage.__titleText; + __iconFilePath = notificationMessage.__iconFilePath; + __soundFilePath = notificationMessage.__soundFilePath; + } + return *this; +} + +bool +_NotificationMessageImpl::Equals(const Object& rhs) const +{ + const NotificationMessage* pMsg = dynamic_cast(&rhs); + if (pMsg == null) + { + return false; + } + + const _NotificationMessageImpl* pMsgImpl = pMsg->__pNotificationMessageImpl; + if (pMsgImpl == this) + { + return true; + } + + if (__appBinding != pMsgImpl->__appBinding) + { + return false; + } + + if (__badgeNumber != pMsgImpl->__badgeNumber) + { + return false; + } + + if (__badgeOffset != pMsgImpl->__badgeOffset) + { + return false; + } + + if (__progressValue != pMsgImpl->__progressValue) + { + return false; + } + + if (__activityType != pMsgImpl->__activityType) + { + return false; + } + + if (GetHashCode() != pMsgImpl->GetHashCode()) + { + return false; + } + + if (__alertText != pMsgImpl->__alertText) + { + return false; + } + + if (__appMessage != pMsgImpl->__appMessage) + { + return false; + } + + if (__titleText != pMsgImpl->__titleText) + { + return false; + } + + if (__iconFilePath != pMsgImpl->__iconFilePath) + { + return false; + } + + if (__soundFilePath != __soundFilePath) + { + return false; + } + + return true; +} + +int +_NotificationMessageImpl::GetHashCode(void) const +{ + return Boolean(__appBinding).GetHashCode() + ^ Integer(__badgeNumber).GetHashCode() + ^ Integer(__badgeOffset).GetHashCode() + ^ Integer(__progressValue).GetHashCode() + ^ Integer(__activityType).GetHashCode() + ^ __alertText.GetHashCode() + ^ __appMessage.GetHashCode() + ^ __titleText.GetHashCode() + ^ __iconFilePath.GetHashCode() + ^ __soundFilePath.GetHashCode(); +} + +int +_NotificationMessageImpl::GetBadgeNumber(void) const +{ + return __badgeNumber; +} + +result +_NotificationMessageImpl::SetBadgeNumber(int badgeNumber) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_APP, badgeNumber >= 0 && badgeNumber <= MAX_NOTIFICATION_BADGE_NUMBER, E_INVALID_ARG, + "BadgeNumber is less than 0 or greater than MAX_NOTIFICATION_BADGE_NUMBER."); + + __badgeOffset = 0; + __badgeNumber = badgeNumber; + return r; +} + +int +_NotificationMessageImpl::GetBadgeOffset() const +{ + return __badgeOffset; +} + +result +_NotificationMessageImpl::SetBadgeOffset(int badgeOffset) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_APP, badgeOffset >= 0 && badgeOffset <= MAX_NOTIFICATION_BADGE_NUMBER, E_INVALID_ARG, + "BadgeOffset is less than 0 or greater than MAX_NOTIFICATION_BADGE_NUMBER."); + + __badgeNumber = -1; + __badgeOffset = badgeOffset; + return r; +} + +String +_NotificationMessageImpl::GetAlertText() const +{ + return __alertText; +} + +result +_NotificationMessageImpl::SetAlertText(const String& alertText) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_APP, alertText.GetLength() > 0 && alertText.GetLength() <= MAX_NOTIFICATION_MESSAGE_LENGTH, E_INVALID_ARG, + "AlertText is greater than MAX_NOTIFICATION_MESSAGE_LENGTH."); + + __alertText = alertText; + return r; +} + +String +_NotificationMessageImpl::GetAppMessage() const +{ + return __appMessage; +} + + +result +_NotificationMessageImpl::SetAppMessage(const String& appMessage) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_APP, appMessage.GetLength() <= MAX_NOTIFICATION_MESSAGE_LENGTH, E_INVALID_ARG, + "AppMessage is greater than MAX_NOTIFICATION_MESSAGE_LENGTH."); + SysTryReturnResult(NID_APP, __appBinding, E_INVALID_OPERATION, + "The Notification instance is not bound to Application"); + + __appMessage = appMessage; + return r; +} + +String +_NotificationMessageImpl::GetTitleText() const +{ + return __titleText; +} + +result +_NotificationMessageImpl::SetTitleText(const String& titleText) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_APP, titleText.GetLength() <= MAX_NOTIFICATION_MESSAGE_LENGTH, E_INVALID_ARG, + "TitleText is greater than MAX_NOTIFICATION_MESSAGE_LENGTH."); + __titleText = titleText; + return r; +} + +String +_NotificationMessageImpl::GetIconFilePath() const +{ + return __iconFilePath; +} + +result +_NotificationMessageImpl::SetIconFilePath(const String& iconFilePath) +{ + result r = E_SUCCESS; + bool isExist = false; + + isExist = File::IsFileExist(iconFilePath); + SysTryReturnResult(NID_APP, isExist, E_INVALID_ARG,"The Specified File is Invalid"); + + __iconFilePath = iconFilePath; + return r; +} + +String +_NotificationMessageImpl::GetSoundFilePath() const +{ + return __soundFilePath; +} + +result +_NotificationMessageImpl::SetSoundFilePath(const String& soundFilePath) +{ + result r = E_SUCCESS; + bool isExist = false; + + isExist = File::IsFileExist(soundFilePath); + SysTryReturnResult(NID_APP, isExist, E_INVALID_ARG,"The Specified File is Invalid"); + + __soundFilePath = soundFilePath; + return r; +} + +OngoingActivityType +_NotificationMessageImpl::GetOngoingActivityType() const +{ + return __activityType; +} + +result +_NotificationMessageImpl::SetOngoingActivityType(OngoingActivityType activityType) +{ + result r = E_SUCCESS; + + // to prevent weired gcc optimization for enum type + int type = static_cast(activityType); + + switch (type) + { + case ONGOING_ACTIVITY_TYPE_TEXT: + break; + case ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE: + SysTryReturnResult(NID_APP, __progressValue == -1 || (__progressValue >= 0 && __progressValue <= 100), E_INVALID_STATE, "Incompatible progress value %d.", __progressValue); + break; + case ONGOING_ACTIVITY_TYPE_PROGRESS_BYTE: + break; + default: + SetLastResult(E_INVALID_STATE); + SysLogException(NID_APP, E_INVALID_STATE, "Invalid activity type %d.", type); + return E_INVALID_STATE; + } + + __activityType = activityType; + return r; +} + +int +_NotificationMessageImpl::GetOngoingActivityProgressValue() const +{ + return __progressValue; +} + +result +_NotificationMessageImpl::SetOngoingActivityProgressValue(int progressValue) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_APP, progressValue >= 0, E_INVALID_ARG,"The progress value is less than 0"); + + // use int type instead of OngoingActivityType to evade weired gcc optimization + int activitytype = static_cast(GetOngoingActivityType()); + SysTryReturnResult(NID_APP, activitytype > ONGOING_ACTIVITY_TYPE_TEXT && activitytype <= ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE, + E_INVALID_STATE,"Invalid activity Type %d.", activitytype); + + if (activitytype == ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE) + { + SysTryReturnResult(NID_APP, progressValue <= 100, E_INVALID_ARG,"Invalid Progress value"); + } + __progressValue = progressValue; + return r; +} + +bool +_NotificationMessageImpl::IsAppBinding()const +{ + return __appBinding; +} + +}; +}; // Tizen::App diff --git a/src/app/FApp_NotificationMessageImpl.h b/src/app/FApp_NotificationMessageImpl.h new file mode 100644 index 0000000..8bc7725 --- /dev/null +++ b/src/app/FApp_NotificationMessageImpl.h @@ -0,0 +1,333 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationMessageImpl.h + * @brief This is the header file for the %_NotificationMessageImpl class. + */ + +#ifndef _FAPP_INTERNAL_NOTIFICATION_MESSAGE_IMPL_H_ +#define _FAPP_INTERNAL_NOTIFICATION_MESSAGE_IMPL_H_ + +#include +#include +#include + +namespace Tizen { namespace App +{ + +class NotificationMessage; + +class _NotificationMessageImpl + : public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.1 + */ + _NotificationMessageImpl(bool appBinding); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_NotificationMessageImpl(void); + + /** + * This is the copy constructor for this class. + * + * @since 2.1 + * + * @param[in] rhs An instance of NotificationMessage + */ + _NotificationMessageImpl(const _NotificationMessageImpl& notificationMessage); + + /** + * This is the assignment operator. + * + * @since 2.1 + * + * @param[in] rhs An instance of NotificationMessage + */ + _NotificationMessageImpl& operator =(const _NotificationMessageImpl& notificationMessage); + + /** + * Checks whether the specified instance of %NotificationMessage equals the current instance. + * + * @since 2.1 + * + * @return @c true if the specified instance equals the current instance, @n + * else @c false + * @param[in] rhs An instance of %NotificationMessage + * @remarks The method returns @c false if the specified object is not %NotificationMessage. + */ + virtual bool Equals(const Object& rhs) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.1 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Gets the badge number of the application icon. + * + * @since 2.1 + * + * @return The current badge number + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. @n + * In case of failure, this method returns @c -1. + */ + int GetBadgeNumber(void) const; + + /** + * Gets the badge number of the application icon. + * + * @since 2.1 + * + * @return The current badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c value is less than 0, or greater than App::MAX_NOTIFICATION_BADGE_NUMBER. + * @remarks The specific error code can be accessed using the GetLastResult() method. @n + * In case of failure, this method returns @c -1. + */ + result SetBadgeNumber(int badgeNo); +/** + * Gets the badge number offset of the notification message. + * + * @since 2.1 + * + * @return The badge offset value + */ + int GetBadgeOffset(void) const; + + /** + * Sets a badge number offset of the notification message. @n + * %NotificationMessage has either badge number or badge number offset. + * If the badge number offset is set using SetBadgeOffset(), then previous badge number value is cleared. + * + * @since 2.1 + * + * @return An error code + * @param[in] value The badge number value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The absolute value of the specified @c value is greater than App::MAX_NOTIFICATION_BADGE_NUMBER. + * @see SetBadgeNumber() + */ + result SetBadgeOffset(int value); + + /** + * Gets the alert text of the notification message. + * + * @since 2.1 + * + * @return The alert text + */ + Tizen::Base::String GetAlertText(void) const; + + /** + * Sets an alert text of the notification message. + * + * @since 2.1 + * + * @return An error code + * @param[in] text The alert text + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of @c text is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result SetAlertText(const Tizen::Base::String& text); + + /** + * Gets the application message of the notification message.@n + * This message is delivered to the application as the launch arguments. + * + * @since 2.1 + * + * @return The message for application + */ + Tizen::Base::String GetAppMessage(void) const; + + /** + * Sets the application message of the notification message.@n + * This message is delivered to the application as the launch arguments. + * + * @since 2.1 + * + * @return An error code + * @param[in] appMessage The message for the application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of @c appMessage is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_INVALID_OPERATION This instance is not bound to application. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks This method returns E_INVALID_OPERATION if %NotificationMessage instance is not bound to application. + */ + result SetAppMessage(const Tizen::Base::String& appMessage); + + /** + * Gets the title text of the notification message. + * + * @since 2.1 + * + * @return The title text + */ + Tizen::Base::String GetTitleText(void) const; + + /** + * Sets an alert text of the notification message. + * + * @since 2.1 + * + * @return An error code + * @param[in] title The title text + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of @c title is greater than App::MAX_NOTIFICATION_TITLE_LENGTH. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result SetTitleText(const Tizen::Base::String& title); + + /** + * Gets the file path of the icon image for the notification message. + * + * @since 2.1 + * + * @return The file path of the icon image + */ + Tizen::Base::String GetIconFilePath(void) const; + + /** + * Sets a file path of the icon image for the notification message. + * + * @since 2.1 + * + * @return An error code + * @param[in] iconPath The file path of the icon image + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified path is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result SetIconFilePath(const Tizen::Base::String& iconPath); + + /** + * Gets the file path of the sound file to be played for the notification message. + * + * @since 2.1 + * + * @return The file path of the sound file + */ + Tizen::Base::String GetSoundFilePath(void) const; + + /** + * Sets a file path of the sound file to be played for the notification message. @n + * The sound file should be wave file format. + * + * @since 2.1 + * + * @return An error code + * @param[in] soundPath The file path of the sound file + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified path is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks If the format of the sound file is not valid, then the sound file is not played properly when the notification message is shown. + */ + result SetSoundFilePath(const Tizen::Base::String& soundPath); + + /** + * Gets the notification type for ongoing-activity notification. + * + * @since 2.1 + * + * @return ongoing-activity notification type + * @remarks This information is only meaningful when the NotificationMessage instance is delivered to NotificationManager::NotifyOngoingActivity() method. + * @see NotificationManager::NotifyOngoingActivity(), SetOngoingActivityType() + */ + OngoingActivityType GetOngoingActivityType(void) const; + + /** + * Sets the notification type for ongoing-activity notification. + * + * @since 2.1 + * + * @return An error code + * @param[in] type ongoing-activity notification type + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Current progress value is not compatible to the specified type + * @remarks This information is only meaningful when the NotificationMessage instance is delivered to NotificationManager::NotifyOngoingActivity() method. + * @see NotificationManager::NotifyOngoingActivity(), SetOngoingActivityProgressValue() + */ + result SetOngoingActivityType(OngoingActivityType type = ONGOING_ACTIVITY_TYPE_TEXT); + + /** + * Gets the progress value for the ongoing-activity notification. + * + * @since 2.1 + * + * @return The progress value + */ + int GetOngoingActivityProgressValue(void) const; + + /** + * Updates the progress value to the specified value. + * + * @since 2.1 + * + * @return An error code + * @param[in] value The value of the progress + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - @c value is less than 0. + * - @c value does not lie between 0 and 100 for App::ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * OngoingActivityType should be either App::ONGOING_ACTIVITY_TYPE_PROGRESS_BYTE or App::ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE. + */ + result SetOngoingActivityProgressValue(int value); + + /** + * Gets the appBinding value for the notification. + * + * @since 2.1 + * + * @return The appBinding value + */ + bool IsAppBinding() const; + +private: + bool __appBinding; + int __badgeNumber; + int __badgeOffset; + int __progressValue; + OngoingActivityType __activityType; + Tizen::Base::String __alertText; + Tizen::Base::String __appMessage; + Tizen::Base::String __titleText; + Tizen::Base::String __iconFilePath; + Tizen::Base::String __soundFilePath; + +}; //_NotificationMessageImpl + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_NOTIFICATION_MESSAGE_IMPL_H_ diff --git a/src/app/FApp_PackageManagerIpcMessages.cpp b/src/app/FApp_PackageManagerIpcMessages.cpp new file mode 100644 index 0000000..793a229 --- /dev/null +++ b/src/app/FApp_PackageManagerIpcMessages.cpp @@ -0,0 +1,46 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_PackageManagerIpcMessages.cpp + * @brief This file contains IPC message class generated by macros. + */ + +#define IPC_MESSAGE_IMPL +#include "FApp_PackageManagerIpcMessages.h" + +// Generate constructors. +#include "ipc/struct_constructor_macros.h" +#include "FApp_PackageManagerIpcMessages.h" +// Generate destructors. + +#include "ipc/struct_destructor_macros.h" +#include "FApp_PackageManagerIpcMessages.h" + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC +{ +#include "FApp_PackageManagerIpcMessages.h" +} // namespace IPC + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC +{ +#include "FApp_PackageManagerIpcMessages.h" +} // namespace IPC diff --git a/src/app/FApp_PackageManagerProxy.cpp b/src/app/FApp_PackageManagerProxy.cpp new file mode 100755 index 0000000..85ab784 --- /dev/null +++ b/src/app/FApp_PackageManagerProxy.cpp @@ -0,0 +1,92 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_PackageManagerProxy.cpp + * @brief This is the implementation for the _PackageManagerProxy.cpp class. + */ + +#include +#include + +#include +#include +#include +#include +#include + +#include "FApp_PackageManagerIpcMessages.h" +#include "FApp_PackageManagerProxy.h" + +using namespace Tizen::Base; +using namespace Tizen::App::Package; + +namespace Tizen { namespace App +{ + +_PackageManagerProxy::_PackageManagerProxy(void) + : __pIpcClient(null) +{ +} + +_PackageManagerProxy::~_PackageManagerProxy(void) +{ +} + +result +_PackageManagerProxy::Construct() +{ + __pIpcClient = new (std::nothrow) Tizen::Io::_IpcClient(); + SysTryReturnResult(NID_APP, __pIpcClient != null, E_OUT_OF_MEMORY, "_IpcClient creation failed."); + + result r = __pIpcClient->Construct("osp.app.ipcserver.packagemanager"); + SysTryReturn(NID_APP, !IsFailed(r), r, r, "_IpcClient constructing failed [%s].", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_PackageManagerProxy::InstallPackage(const PackageId& packageId, const String& packagePath, IPackageInstallationResponseListener* pListener) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, "_PackageManagerProxy::InstallPackage"); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) PackageManager_InstallPackage(packageId, packagePath, (int) pListener, &response)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + + SysTryReturn(NID_APP, !IsFailed(r), r, r, "__pIpcClient->SendRequest is failed. (%s)", GetErrorMessage(r)); + + return response; +} + +result +_PackageManagerProxy::UninstallPackage(const PackageId& packageId, IPackageUninstallationResponseListener* pListener) +{ + SysTryReturnResult(NID_APP, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + SysLog(NID_APP, "_PackageManagerProxy::UninstallPackage"); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) PackageManager_UninstallPackage(packageId, (int)pListener, &response)); + result r = __pIpcClient->SendRequest(*pMsg.get()); + + SysTryReturn(NID_APP, !IsFailed(r), r, r, "__pIpcClient->SendRequest is failed. (%s)", GetErrorMessage(r)); + + return response; +} + +} } // Tizen::App diff --git a/src/app/FApp_ServiceAppImpl.cpp b/src/app/FApp_ServiceAppImpl.cpp new file mode 100644 index 0000000..0eb07de --- /dev/null +++ b/src/app/FApp_ServiceAppImpl.cpp @@ -0,0 +1,227 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_ServiceAppImpl.cpp + * @brief This is the implementation for the _ServiceAppImpl class. + */ + +#include +#include + +#include +#include +#include + +#include + +#include "FApp_AppInfo.h" +#include "FApp_AppImpl.h" +#include "FApp_ServiceAppImpl.h" +#include "FAppPkg_PackageManagerImpl.h" +#include "FApp_AppManagerImpl.h" +#include "FApp_TemplateUtil.h" + +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +const wchar_t USE_UI_KEY[] = L"UseUi"; +const wchar_t USE_UI_VAL_TRUE[] = L"True"; + +static const RequestId HANDLER_REQUEST_ALARMID = 2; + +namespace Tizen { namespace App +{ + +_ServiceAppImpl* _ServiceAppImpl::__pServiceAppImpl = null; + + +_ServiceAppImpl::_ServiceAppImpl(ServiceApp* pServiceApp) + : __pAppImpl(_AppImpl::GetInstance()) + , __pServiceApp(pServiceApp) +{ + __pServiceAppImpl = this; + SysTryReturnVoidResult(NID_APP, __pAppImpl, E_INVALID_STATE, "[E_INVALID_STATE] Getting internal instance failed."); +} + + +_ServiceAppImpl::~_ServiceAppImpl(void) +{ + __pServiceAppImpl = null; +} + + +bool +_ServiceAppImpl::OnCreate(void) +{ + SysLog(NID_APP, "Platform creation event."); + + _AppInfo::SetAppState(INITIALIZING); + + return true; +} + + +void +_ServiceAppImpl::OnService(service_s* service, bool initial) +{ + SysLog(NID_APP, "Service requested."); + char* pOperation = null; + int errVal = service_get_operation(service, &pOperation); + + if ( (errVal == SERVICE_ERROR_NONE) && (!strcmp(pOperation, "osp.appsvc.operation.ALARM")) ) + { + char* pAlarmId = NULL; + + + errVal = service_get_extra_data(service, SERVICE_DATA_ALARM_ID, &pAlarmId); + if (errVal == SERVICE_ERROR_NONE) + { + int alarmId = atoi(pAlarmId); + + String* pAlarmStr = new (std::nothrow) String(pAlarmId); + ArrayList alarmArg; + alarmArg.Add(*pAlarmStr); + __pServiceApp->OnUserEventReceivedN(HANDLER_REQUEST_ALARMID, &alarmArg); + } + + if (pAlarmId != NULL) + { + free(pAlarmId); + } + } +} + +void +_ServiceAppImpl::OnTerminate(void) +{ + SysLog(NID_APP, "Termination event 0x%x state", _AppInfo::GetAppState()); + + if (_AppInfo::GetAppState() == TERMINATED) + { + return; + } + + _AppInfo::SetAppState(TERMINATING); + + if (OnServiceAppImplTerminating(false) != true) + { + SysLog(NID_APP, "[E_SYSTEM] The Termination of application failed."); + } + + _AppInfo::SetAppState(TERMINATED); +} + + +void +_ServiceAppImpl::OnResume(void) +{ + SysLog(NID_APP, "System resume event on 0x%x state", _AppInfo::GetAppState()); +} + + +void +_ServiceAppImpl::OnPause(void) +{ + SysLog(NID_APP, "System pause event on 0x%x state", _AppInfo::GetAppState()); +} + + +void +_ServiceAppImpl::OnDeviceOrientationChanged(app_device_orientation_e orientation) +{ + SysLog(NID_APP, "System device orientation changed event on 0x%x state", _AppInfo::GetAppState()); +} + + +long +_ServiceAppImpl::OnWindowHandleRequest(void) +{ + return -1; +} + +_ServiceAppImpl* +_ServiceAppImpl::GetInstance(void) +{ + return __pServiceAppImpl; +} + + +ServiceApp* +_ServiceAppImpl::GetServiceAppInstance(void) +{ + return __pServiceApp; +} + +bool +_ServiceAppImpl::OnAppInitializing(void) +{ + const String& packageId = _AppInfo::GetPackageId(); + const String& exeName = _AppInfo::GetAppExecutableName(); + + HashMapT* pInfo = _PackageManagerImpl::GetInstance()->GetPackageAppFeatureMapN(packageId, exeName); + + if (pInfo) + { + _AppFeatureInfoImpl* pFeature = null; + + result r = pInfo->GetValue(USE_UI_KEY, pFeature); + + if (r == E_SUCCESS) + { + const String& val = pFeature->GetValue(); + if (val == USE_UI_VAL_TRUE) + { + SysLog(NID_APP, "Using remote ui on service application."); + + _LibraryImpl& lib = _AppManagerImpl::GetInstance()->GetUiLibraryImpl(); + result (*pInit)(void) = null; + + pInit = reinterpret_cast(lib.GetProcAddress(L"InitializeUiFramework")); + if (pInit) + { + r = (*pInit)(); + SysLog(NID_APP, "[%s] UI initialized.", GetErrorMessage(r)); + } + } + } + + _DeleteCollectionMapValue(*pInfo); + delete pInfo; + } + + SysTryReturn(NID_APP, __pServiceApp != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting ServiceApp instance failed."); + return __pServiceApp->OnAppInitializing(*(AppRegistry::GetInstance())); +} + +bool +_ServiceAppImpl::OnAppInitialized(void) +{ + SysTryReturn(NID_APP, __pServiceApp != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting ServiceApp instance failed."); + return __pServiceApp->OnAppInitialized(); +} + +bool +_ServiceAppImpl::OnServiceAppImplTerminating(bool forcedTermination) +{ + SysTryReturn(NID_APP, __pServiceApp != null, false, E_INVALID_STATE, "[E_INVALID_STATE] Getting ServiceApp instance failed."); + return __pServiceApp->OnAppTerminating(*(AppRegistry::GetInstance()), forcedTermination); +} + +} } //Tizen::App diff --git a/src/app/FApp_SqlDataControlImpl.cpp b/src/app/FApp_SqlDataControlImpl.cpp new file mode 100644 index 0000000..35d0e38 --- /dev/null +++ b/src/app/FApp_SqlDataControlImpl.cpp @@ -0,0 +1,598 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_SqlDataControlImpl.cpp + * @brief This is the implementation for the %_SqlDataControlImpl class. + */ + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "FApp_AppControlManager.h" +#include "FApp_AppManagerProxy.h" +#include "FApp_SqlDataControlImpl.h" +#include "FApp_AppArg.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::App; +using namespace Tizen::Io; + +namespace Tizen { namespace App +{ + +// private +_SqlDataControlImpl::_SqlDataControlImpl(void) + : __appId(L"") + , __providerId(L"") + , __access(_DATACONTROL_ACCESS_UNDEFINED) + , __pListener(null) +{ +} + +_SqlDataControlImpl::~_SqlDataControlImpl(void) +{ +} + +_SqlDataControlImpl* +_SqlDataControlImpl::GetInstance(SqlDataControl& dc) +{ + return dc.__pSqlDataControlImpl; +} + +const _SqlDataControlImpl* +_SqlDataControlImpl::GetInstance(const SqlDataControl& dc) +{ + return dc.__pSqlDataControlImpl; +} + +result +_SqlDataControlImpl::StartSqlDataControl(int type, const IList* pDataList, ISqlDataControlResponseListener* pListener, + int* pReq) +{ + result r = E_SUCCESS; + + _AppArg* pArg = new (std::nothrow) _AppArg; // XXX: pArg will be released in _AppManagerImpl::LaunchApp(). + SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "insufficient memory"); + + pArg->Construct(*this, static_cast <_DataControlRequestType>(type), pDataList); + + _AppControlManager* pAppManagerImpl = _AppControlManager::GetInstance(); + int req = -1; + + if (__pListener) + { + SysLog(NID_APP, "listener address: 0x%x", (void*) __pListener); + + // reqId is system-wide id because the bundle is system-wide. + _AppControlManager::_RequestGuard reqObj = _AppControlManager::_RequestGuard(*pAppManagerImpl, pArg, SqlDataControlCallback, __pListener, -1); + req = reqObj.GetRequestNumber(); + + r = pAppManagerImpl->LaunchApp(__appId, pArg, req); + SysTryCatch(NID_APP, r == E_SUCCESS, reqObj.Invalidate(), r, "[%s] Propagating.", GetErrorMessage(r)); + + if (pReq) + { + *pReq = req; + } + } + else + { + r = pAppManagerImpl->LaunchApp(__appId, pArg); + } + + { + // registers to server + _IAppManager* pMgr = _AppManagerProxy::GetService(); + + // actually register, not launch + if (pMgr) + { + pMgr->LaunchApplication(__appId, null, req); + } + } + +CATCH: + + return r; +} + +result +_SqlDataControlImpl::Select(const String& dataId, const IList* pColumnList, const String* pWhere, + const String *pOrder, RequestId& reqId, int pageNo, int countPerPage) +{ + SysTryReturnResult(NID_APP, pageNo > 0, E_INVALID_ARG, "The specified pageNo parameter is less than 1"); + SysTryReturnResult(NID_APP, countPerPage > 0, E_INVALID_ARG, "The specified countPerPage parameter is less than 1"); + SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_READ) > 0, E_ILLEGAL_ACCESS, + "The SELECT query is not permitted by DataControl provider."); + + const String* pColumn = null; + int id = 0; + result r = E_SUCCESS; + SysLog(NID_APP, "[DC_CALLER] SqlDataControl SELECT"); + + ArrayList* pArgList = new ArrayList(); + pArgList->Construct(); + + pArgList->Add(*(new String(dataId))); // list(0): data ID + + if (pColumnList != null) + { + int columnCount = pColumnList->GetCount(); + SysTryCatch(NID_APP, columnCount > 0, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The specified pColumnList parameter is empty."); + + pArgList->Add(*(new String(Integer::ToString(columnCount)))); // list(1): selected column count + SysLog(NID_APP, "[DC_CALLER] selected column count: %d", columnCount); + + int i = 0; + while (i < columnCount) // list(2): column list + { + pColumn = dynamic_cast< const String* >(pColumnList->GetAt(i)); + SysTryCatch(NID_APP, pColumn != null, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not String class."); + + pArgList->Add(*(new String(*pColumn))); + SysLog(NID_APP, "[DC_CALLER] column[%d]: %ls", i, pColumn->GetPointer()); + i++; + } + } + else + { + pArgList->Add(*(new String(L"NULL"))); + } + + if (pWhere != null) // list(3): where clause + { + pArgList->Add(*(new String(*pWhere))); + SysLog(NID_APP, "[DC_CALLER] pWhere: %ls", pWhere->GetPointer()); + } + else + { + pArgList->Add(*(new String(L"NULL"))); + } + + if (pOrder != null) // list(4): order clause + { + pArgList->Add(*(new String(*pOrder))); + SysLog(NID_APP, "[DC_CALLER] pOrder: %ls", pOrder->GetPointer()); + } + else + { + pArgList->Add(*(new String(L"NULL"))); + } + + pArgList->Add(*(new String(Integer::ToString(pageNo)))); // list(5): page number + + pArgList->Add(*(new String(Integer::ToString(countPerPage)))); // list(6): count per page + + r = StartSqlDataControl(_DATACONTROL_REQUEST_TYPE_SQL_QUERY, pArgList, __pListener, &id); + + reqId = static_cast< RequestId >(id); + + SysLog(NID_APP, "[DC_CALLER] dataId: %ls, pColumnList: 0x%x, pWhere: 0x%x, pOrder: 0x%x, reqId: %d, pageNo: %d, countPerPage: %d", + dataId.GetPointer(), pColumnList, pWhere, pOrder, reqId, pageNo, countPerPage); + + // fall through +CATCH: + pArgList->RemoveAll(true); + delete pArgList; + + return r; +} + +result +_SqlDataControlImpl::SqlDataControlCallback(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop) +{ + ArrayList* pResultList = null; + ArrayList* pOrigList = null; + String* pResult = null; + String* pRequestType = null; + String* pReqId = null; + String* pProviderId = null; + String* pDataId = null; + String* pErrorMsg = null; + String* pTmpPath = null; + String* pInsertRowId = null; + _DataControlResultSetEnumerator* pResultSetEnum = null; + int requestType = 0; + int reqId = 0; + int providerRes = 0; + bool providerResult = true; + bundle* origBundle = null; + bundle* resBundle = null; + result r = E_SUCCESS; + + SysTryReturnResult(NID_APP, pResArg != null, E_INVALID_ARG, "Empty result callback."); + SysLog(NID_APP, "appsvc result value: %d", res); + + resBundle = pResArg->GetBundle(); + if (resBundle) + { + ISqlDataControlResponseListener* pListener = static_cast< ISqlDataControlResponseListener* >(data); + + if (pListener != null && typeid(pListener) == typeid(ISqlDataControlResponseListener*)) + { + const char* p = null; + + // result list + pResultList = _AppArg::GetListN(resBundle, OSP_K_ARG); + SysTryCatch(NID_APP, pResultList, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + + pResult = dynamic_cast (pResultList->GetAt(0)); + SysTryCatch(NID_APP, pResult, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + Integer::Parse(*pResult, providerRes); + providerResult = static_cast< bool >(providerRes); + + pErrorMsg = dynamic_cast< String* >(pResultList->GetAt(1)); + SysTryCatch(NID_APP, pErrorMsg, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + + origBundle = pArg->GetBundle(); + + // request info + p = appsvc_get_data(origBundle, OSP_K_DATACONTROL_REQUEST_TYPE); + SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + pRequestType = new (std::nothrow) String(p); + SysTryCatch(NID_APP, pRequestType, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + Integer::Parse(*pRequestType, requestType); + + p = appsvc_get_data(origBundle, OSP_K_REQUEST_ID); + SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + pReqId = new (std::nothrow) String(p); + SysTryCatch(NID_APP, pReqId, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + Integer::Parse(*pReqId, reqId); + + p = appsvc_get_data(origBundle, OSP_K_DATACONTROL_PROVIDER); + SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + pProviderId = new (std::nothrow) String(p); + SysTryCatch(NID_APP, pProviderId, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + + pOrigList = _AppArg::GetListN(origBundle, OSP_K_ARG); + SysTryCatch(NID_APP, pOrigList, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + pDataId = dynamic_cast (pOrigList->GetAt(0)); + SysTryCatch(NID_APP, pDataId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle"); + + SysLog(NID_APP, "providerResult: %ld, requestType: %d, reqId: %d, providerId: %ls, dataId: %ls, errorMsg: %ls ", + providerRes, requestType, reqId, pProviderId->GetPointer(), pDataId->GetPointer(), pErrorMsg->GetPointer()); + + switch (static_cast <_DataControlRequestType>(requestType)) + { + case _DATACONTROL_REQUEST_TYPE_SQL_QUERY: + { + pResultSetEnum = new (std::nothrow) _DataControlResultSetEnumerator; + SysTryCatch(NID_APP, pResultSetEnum, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory was insufficient."); + + if (providerResult == true) + { + pTmpPath = dynamic_cast< String* >(pResultList->GetAt(2)); // result list[2] + SysTryCatch(NID_APP, pTmpPath, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + + SysLog(NID_APP, "tempPath: %ls", pTmpPath->GetPointer()); + if (pTmpPath->Equals(L"NoResultSet", true) == false) // Result set exists + { + pResultSetEnum->SetPath(*pTmpPath); + } + } + + pListener->OnSqlDataControlSelectResponseReceived(static_cast (reqId), *pProviderId, + *pDataId, *pResultSetEnum, providerResult, pErrorMsg); + + if (pTmpPath) + { + r = File::Remove(*pTmpPath); // Remove temporary file after releasing _ResultSetEnumerator. + SysTryLog(NID_APP, !IsFailed(r), "Failed to remove temp file for result set: %ls", pTmpPath->GetPointer()); + } + + delete pResultSetEnum; + break; + } + case _DATACONTROL_REQUEST_TYPE_SQL_INSERT: + { + long long insertRowId = -1; + if (providerResult == true) + { + pInsertRowId = dynamic_cast< String* >(pResultList->GetAt(2)); // result list[2] + SysTryCatch(NID_APP, pInsertRowId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result"); + + LongLong::Parse(*pInsertRowId, insertRowId); + } + + pListener->OnSqlDataControlInsertResponseReceived(static_cast (reqId), *pProviderId, + *pDataId, insertRowId, providerResult, pErrorMsg); + break; + } + case _DATACONTROL_REQUEST_TYPE_SQL_UPDATE: + pListener->OnSqlDataControlUpdateResponseReceived(static_cast (reqId), *pProviderId, + *pDataId, providerResult, pErrorMsg); + break; + case _DATACONTROL_REQUEST_TYPE_SQL_DELETE: + pListener->OnSqlDataControlDeleteResponseReceived(static_cast (reqId), *pProviderId, + *pDataId, providerResult, pErrorMsg); + break; + default: + break; + } + + pResultList->RemoveAll(true); + delete pResultList; + + pOrigList->RemoveAll(true); + delete pOrigList; + + delete pRequestType; + delete pReqId; + delete pProviderId; + } + } + + return E_SUCCESS; + +CATCH: + delete pResultSetEnum; + + if (pResultList) + { + pResultList->RemoveAll(true); + delete pResultList; + } + + if (pOrigList) + { + pOrigList->RemoveAll(true); + delete pOrigList; + } + + delete pRequestType; + delete pReqId; + delete pProviderId; + + return r; +} + +result +_SqlDataControlImpl::Insert(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& insertMap, + RequestId& reqId) +{ + SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS, + "The INSERT query is not permitted by DataControl provider."); + + int columnCount = 0; + int id = 0; + int i = 0; + result r = E_SUCCESS; + SysLog(NID_APP, "[DC_CALLER] SqlDataControl INSERT"); + + columnCount = insertMap.GetCount(); + SysTryReturnResult(NID_APP, columnCount > 0, E_INVALID_ARG, "The specified insertMap parameter is empty."); + + ArrayList* pArgList = new ArrayList(); + pArgList->Construct(); + + pArgList->Add(*(new String(dataId))); // list(0): data ID + + pArgList->Add(*(new String(Integer::ToString(columnCount)))); // list(1): inserted column count + SysLog(NID_APP, "[DC_CALLER] inserted column count: %d", columnCount); + + IMapEnumerator* pMapEnum = const_cast< IMap* >(&insertMap)->GetMapEnumeratorN(); + while (pMapEnum->MoveNext() == E_SUCCESS) // list(2): column-value pairs + { + String* pColumn = dynamic_cast< String* >(pMapEnum->GetKey()); + SysTryCatch(NID_APP, pColumn != null, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not String class."); + + pArgList->Add(*(new String(*pColumn))); + SysLog(NID_APP, "[DC_CALLER] pColumn[%d]: %ls", i, pColumn->GetPointer()); + + String* pValue = dynamic_cast< String* >(pMapEnum->GetValue()); + SysTryCatch(NID_APP, pValue != null, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not String class."); + + pArgList->Add(*(new String(*pValue))); + SysLog(NID_APP, "[DC_CALLER] pValue[%d]: %ls", i, pValue->GetPointer()); + + i++; + } + + r = StartSqlDataControl(_DATACONTROL_REQUEST_TYPE_SQL_INSERT, pArgList, __pListener, &id); + + reqId = static_cast< RequestId >(id); + + SysLog(NID_APP, "[DC_CALLER] dataId: %ls, insertMap: 0x%x, reqId: %d", dataId.GetPointer(), &insertMap, reqId); + + // fall through +CATCH: + pArgList->RemoveAll(true); + delete pArgList; + + delete pMapEnum; + + return r; +} + +result +_SqlDataControlImpl::Update(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& updateMap, + const Tizen::Base::String* pWhere, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS, + "The UPDATE query is not permitted by DataControl provider."); + + int columnCount = 0; + int id = 0; + int i = 0; + result r = E_SUCCESS; + SysLog(NID_APP, "[DC_CALLER] SqlDataControl UPDATE"); + + columnCount = updateMap.GetCount(); + SysTryReturnResult(NID_APP, columnCount > 0, E_INVALID_ARG, "The specified insertMap parameter is empty."); + + ArrayList* pArgList = new ArrayList(); + pArgList->Construct(); + + pArgList->Add(*(new String(dataId))); // list(0): data ID + + pArgList->Add(*(new String(Integer::ToString(columnCount)))); // list(1): updated column count + SysLog(NID_APP, "[DC_CALLER] updated column count: %d", columnCount); + + IMapEnumerator* pMapEnum = const_cast< IMap* >(&updateMap)->GetMapEnumeratorN(); + while (pMapEnum->MoveNext() == E_SUCCESS) // list(2): column-value pairs + { + String* pColumn = dynamic_cast< String* >(pMapEnum->GetKey()); + SysTryCatch(NID_APP, pColumn != null, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not String class."); + + pArgList->Add(*(new String(*pColumn))); + SysLog(NID_APP, "[DC_CALLER] pColumn[%d]: %ls", i, pColumn->GetPointer()); + + String* pValue = dynamic_cast< String* >(pMapEnum->GetValue()); + SysTryCatch(NID_APP, pValue != null, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not String class."); + + pArgList->Add(*(new String(*pValue))); + SysLog(NID_APP, "[DC_CALLER] pValue[%d]: %ls", i, pValue->GetPointer()); + + i++; + } + + if (pWhere != null) // list(3): where clause + { + pArgList->Add(*(new String(*pWhere))); + SysLog(NID_APP, "[DC_CALLER] pWhere: %ls", pWhere->GetPointer()); + } + else + { + pArgList->Add(*(new String(L"NULL"))); + } + + r = StartSqlDataControl(_DATACONTROL_REQUEST_TYPE_SQL_UPDATE, pArgList, __pListener, &id); + + reqId = static_cast< RequestId >(id); + + SysLog(NID_APP, "[DC_CALLER] dataId: %ls, updateMap: 0x%x, pWhere: 0x%x, reqId: %d", + dataId.GetPointer(), &updateMap, pWhere, reqId); + + // fall through +CATCH: + pArgList->RemoveAll(true); + delete pArgList; + + delete pMapEnum; + + return r; +} + +result +_SqlDataControlImpl::Delete(const Tizen::Base::String& dataId, const Tizen::Base::String* pWhere, RequestId& reqId) +{ + SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS, + "The DELETE query is not permitted by DataControl provider."); + + int id = 0; + result r = E_SUCCESS; + SysLog(NID_APP, "[DC_CALLER] SqlDataControl DELETE"); + + ArrayList* pArgList = new ArrayList(); + pArgList->Construct(); + + pArgList->Add(*(new String(dataId))); // list(0): data ID + + if (pWhere != null) // list(1): where clause + { + pArgList->Add(*(new String(*pWhere))); + SysLog(NID_APP, "[DC_CALLER] pWhere: %ls", pWhere->GetPointer()); + } + else + { + pArgList->Add(*(new String(L"NULL"))); + } + + r = StartSqlDataControl(_DATACONTROL_REQUEST_TYPE_SQL_DELETE, pArgList, __pListener, &id); + + reqId = static_cast< RequestId >(id); + + SysLog(NID_APP, "[DC_CALLER] dataId: %ls, pWhere: 0x%x, reqId: %d", dataId.GetPointer(), pWhere, reqId); + + pArgList->RemoveAll(true); + delete pArgList; + + return r; +} + +result +_SqlDataControlImpl::SetSqlDataControlResponseListener(ISqlDataControlResponseListener* pListener) +{ + __pListener = pListener; + + return E_SUCCESS; +} + +// private +SqlDataControl* +_SqlDataControlImpl::CreateSqlDataControl(const String& appId, const String& providerId, const String& access) +{ + SqlDataControl* pDc = null; + _SqlDataControlImpl* pDcImpl = null; + + pDc = new (std::nothrow) SqlDataControl; + SysTryReturn(NID_APP, pDc != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory was insufficient"); + + pDcImpl = _SqlDataControlImpl::GetInstance(*pDc); + pDcImpl->__appId = appId; + pDcImpl->__providerId = providerId; + + if (access == L"readonly") + { + pDcImpl->__access = _DATACONTROL_ACCESS_READ; + } + else if (access == L"writeonly") + { + pDcImpl->__access = _DATACONTROL_ACCESS_WRITE; + } + else if (access == L"readwrite") + { + pDcImpl->__access = _DATACONTROL_ACCESS_READWRITE; + } + else + { + pDcImpl->__access = _DATACONTROL_ACCESS_UNDEFINED; + SysLog(NID_IO, "The accessibility of DataControl provider is invalid."); + } + + return pDc; +} + +}} // Tizen::App + diff --git a/src/app/FApp_SqlDataControlImpl.h b/src/app/FApp_SqlDataControlImpl.h new file mode 100644 index 0000000..4134208 --- /dev/null +++ b/src/app/FApp_SqlDataControlImpl.h @@ -0,0 +1,99 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_SqlDataControlImpl.h + * @brief This is the header file for the %_SqlDataControlImpl class. + */ + +#ifndef _FAPP_INTERNAL_SQL_DATA_CONTROL_IMPL_H_ +#define _FAPP_INTERNAL_SQL_DATA_CONTROL_IMPL_H_ + +#include + +#include +#include +#include + +#include "FApp_AppManagerImpl.h" + +namespace Tizen { namespace Base +{ +namespace Collection +{ +class IList; +class IMap; +} +}} + +namespace Tizen { namespace App +{ + +class ISqlDataControlResponseListener; +class _AppArg; + +class _SqlDataControlImpl + : public Tizen::Base::Object +{ + +public: + virtual ~_SqlDataControlImpl(void); + + static _SqlDataControlImpl* GetInstance(SqlDataControl& dc); + + static const _SqlDataControlImpl* GetInstance(const SqlDataControl& dc); + + result Select(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IList* pColumnList, + const Tizen::Base::String* pWhere, const Tizen::Base::String *pOrder, RequestId& reqId, + int pageNo = 1, int countPerPage = 20); + + result Insert(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& insertMap, RequestId& reqId); + + result Update(const Tizen::Base::String& dataId, const Tizen::Base::Collection::IMap& updateMap, + const Tizen::Base::String* pWhere, RequestId& reqId); + + result Delete(const Tizen::Base::String& dataId, const Tizen::Base::String* pWhere, RequestId& reqId); + + result SetSqlDataControlResponseListener(ISqlDataControlResponseListener* pListener); + + static result SqlDataControlCallback(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop); + +private: + _SqlDataControlImpl(void); + + static SqlDataControl* CreateSqlDataControl(const Tizen::Base::String& appId, const Tizen::Base::String& providerId, + const Tizen::Base::String& access); + + result StartSqlDataControl(int type, const Tizen::Base::Collection::IList* pDataList, + ISqlDataControlResponseListener* pListener, int* pReq); + +private: + Tizen::Base::String __appId; + Tizen::Base::String __providerId; + int __access; + ISqlDataControlResponseListener* __pListener; + + friend class SqlDataControl; + friend class _AppManagerImpl; + friend class _AppArg; + +}; // _SqlDataControlImpl + +}} // Tizen::App + +#endif // _FAPP_INTERNAL_SQL_DATA_CONTROL_IMPL_H_ + diff --git a/src/app/inc/FAppNotificationMessage.h b/src/app/inc/FAppNotificationMessage.h new file mode 100644 index 0000000..1406802 --- /dev/null +++ b/src/app/inc/FAppNotificationMessage.h @@ -0,0 +1,340 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppNotificationMessage.h + * @brief This is the header file for the %NotificationMessage class. + * + * This header file contains the declarations of the %NotificationMessage class. + */ + +#ifndef _FAPP_NOTIFICATION_MESSAGE_H_ +#define _FAPP_NOTIFICATION_MESSAGE_H_ + +#include +#include +#include + +namespace Tizen { namespace App +{ + +/* + * @class NotificationMessage + * @brief This class provides methods for handling a notification message. + * + * @since 2.1 + * + * @final This class is not intended for extension. + * + * The %NotificationMessage class provides methods for handling a notification message. The %NotificationMessage instance corresponds to each notification item + * in the notification area after it is posted. %NotificationMessage is either bound to the application or not and the associated + * application is launched by selecting the bound %NotificationMessage in the notification area. + * + * For more information about the class features, see Notifications. + * + * @see Tizen::App::NotificationManager + */ +class _OSP_EXPORT_ NotificationMessage + : public Tizen::Base::Object +{ + +public: + /** + * Initializes this instance of %NotificationMessage with the specified appBinding. + * + * @since 2.1 + * + * @param[in] appBinding Set to @c true to bind %NotificationMessage to the destination application, @n + * else @c false + * @remarks Selecting the posted notification in the notification area leads to launch of the associated application + * if %NotificationMessage is bound to the destination application. + */ + NotificationMessage(bool appBinding = true); + + /** + * Copying of objects using this copy constructor is allowed. + * + * @since 2.1 + * + * @param[in] rhs An instance of %NotificationMessage + */ + NotificationMessage(const NotificationMessage& rhs); + + /** + * Copying of objects using this copy assignment operator is allowed. + * + * @since 2.1 + * + * @param[in] rhs An instance of %NotificationMessage + */ + NotificationMessage& operator =(const NotificationMessage& rhs); + + /** + * This destructor overrides Tizen::Base::Object::~Object(). + * + * @since 2.1 + */ + virtual ~NotificationMessage(void); + + /** + * Checks whether the specified instance of %NotificationMessage equals the current instance. + * + * @since 2.1 + * + * @return @c true if the specified instance equals the current instance, @n + * else @c false + * @param[in] rhs An instance of %NotificationMessage + * @remarks The method returns @c false if the specified object is not %NotificationMessage. + */ + virtual bool Equals(const Object& rhs) const; + + /** + * Gets the hash value of the current instance. + * + * @since 2.1 + * + * @return The hash value of the current instance + */ + virtual int GetHashCode(void) const; + + /** + * Gets the badge number of the notification message. + * + * @since 2.1 + * + * @return The badge number value + * @remarks If the badge number is not set, then this method returns @c -1. + */ + int GetBadgeNumber(void) const; + + /** + * Sets the badge number of the notification message. @n + * %NotificationMessage has either badge number or badge number offset. + * If the badge number is set using %SetBadgeNumber(), then previous badge offset value is set to @c 0. + * + * @since 2.1 + * + * @return An error code + * @param[in] value The badge number value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c value is less than @c 0 or greater than App::MAX_NOTIFICATION_BADGE_NUMBER. + */ + result SetBadgeNumber(int value); + + /** + * Gets the badge number offset of the notification message. + * + * @since 2.1 + * + * @return The badge offset value + */ + int GetBadgeOffset(void) const; + + /** + * Sets the badge number offset of the notification message. @n + * %NotificationMessage has either badge number or badge number offset. + * If the badge number offset is set using %SetBadgeOffset(), then previous badge number value is set to @c -1 and ignored. @n + * + * When posting the notification message, badge offset value is added to the current badge number, + * which can be acquired by NotificationManager::GetBadgeNumber(). Setting badge offset to @c 0 + * means explicitly specifying not to change the current badge value with the notification message. + * + * @since 2.1 + * + * @return An error code + * @param[in] value The badge number value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The absolute value of the specified @c value is greater than App::MAX_NOTIFICATION_BADGE_NUMBER. + * @remarks Even though this method does not return E_INVALID_ARG, it does not guarantee the success of NotificationManager::Notify(). + * @see SetBadgeNumber(), NotificationManager::GetBadgeNumber(), NotificationManager::Notify() + */ + result SetBadgeOffset(int value); + + /** + * Gets the alert text of the notification message. + * + * @since 2.1 + * + * @return The alert text + */ + Tizen::Base::String GetAlertText(void) const; + + /** + * Sets an alert text of the notification message. + * + * @since 2.1 + * + * @return An error code + * @param[in] text The alert text + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c text is empty or the length of @c text is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result SetAlertText(const Tizen::Base::String& text); + + /** + * Gets the application message of the notification message. @n + * This message is delivered to the application as launch arguments. + * + * @since 2.1 + * + * @return The message for application + */ + Tizen::Base::String GetAppMessage(void) const; + + /** + * Sets the application message of the notification message. @n + * This message is delivered to the application as launch arguments. + * + * @since 2.1 + * + * @return An error code + * @param[in] appMessage The message for the application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of @c appMessage is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_INVALID_OPERATION This instance is not bound to the application. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks This method returns E_INVALID_OPERATION if %NotificationMessage instance is not bound to the application. + */ + result SetAppMessage(const Tizen::Base::String& appMessage); + + /** + * Gets the title text of the notification message. + * + * @since 2.1 + * + * @return The title text + */ + Tizen::Base::String GetTitleText(void) const; + + /** + * Sets the title text of the notification message. + * + * @since 2.1 + * + * @return An error code + * @param[in] title The title text + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The length of @c title is greater than App::MAX_NOTIFICATION_TITLE_LENGTH. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result SetTitleText(const Tizen::Base::String& title); + + /** + * Gets the file path of the icon image for the notification message. + * + * @since 2.1 + * + * @return The file path of the icon image + */ + Tizen::Base::String GetIconFilePath(void) const; + + /** + * Sets the file path of the icon image for the notification message. + * + * @since 2.1 + * + * @return An error code + * @param[in] iconPath The file path of the icon image + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified path is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result SetIconFilePath(const Tizen::Base::String& iconPath); + + /** + * Gets the file path of the sound file to be played for the notification message. + * + * @since 2.1 + * + * @return The file path of the sound file + */ + Tizen::Base::String GetSoundFilePath(void) const; + + /** + * Sets the file path of the sound file to be played for the notification message. @n + * The sound file should be wave file format. + * + * @since 2.1 + * + * @return An error code + * @param[in] soundPath The file path of the sound file + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified path is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @remarks If the format of the sound file is not valid, then the sound file is not played properly when the notification message is shown. + */ + result SetSoundFilePath(const Tizen::Base::String& soundPath); + + /** + * Gets the notification type for the ongoing activity notification. + * + * @since 2.1 + * + * @return The ongoing activity notification type + * @remarks This information is only meaningful when the %NotificationMessage instance is delivered to the NotificationManager::NotifyOngoingActivity() method. + * @see NotificationManager::NotifyOngoingActivity(), SetOngoingActivityType() + */ + OngoingActivityType GetOngoingActivityType(void) const; + + /** + * Sets the notification type for the ongoing activity notification. + * + * @since 2.1 + * + * @return An error code + * @param[in] type The ongoing activity notification type + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The current progress value is not compatible to the specified @c type. + * @remarks This information is only meaningful when the %NotificationMessage instance is delivered to the NotificationManager::NotifyOngoingActivity() method. + * @see NotificationManager::NotifyOngoingActivity(), SetOngoingActivityProgressValue() + */ + result SetOngoingActivityType(OngoingActivityType type = ONGOING_ACTIVITY_TYPE_TEXT); + + /** + * Gets the progress value for the ongoing activity notification. + * + * @since 2.1 + * + * @return The progress value + */ + int GetOngoingActivityProgressValue(void) const; + + /** + * Sets the progress value with the specified value. + * + * @since 2.1 + * + * @return An error code + * @param[in] value The progress value + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c value is less than @c 0, or + * the specified @c value does not lie between @c 0 and @c 100 for App::ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * OngoingActivityType must be either App::ONGOING_ACTIVITY_TYPE_PROGRESS_BYTE or App::ONGOING_ACTIVITY_TYPE_PROGRESS_PERCENTAGE. + */ + result SetOngoingActivityProgressValue(int value); + +private: + class _NotificationMessageImpl * __pNotificationMessageImpl; + + friend class _NotificationMessageImpl; +}; // NotificationMessage + +} } // Tizen::App + +#endif // _FAPP_NOTIFICATION_MESSAGE_H_ diff --git a/src/app/inc/FAppPkg_PackageAppInfoImpl.h b/src/app/inc/FAppPkg_PackageAppInfoImpl.h new file mode 100755 index 0000000..0da0521 --- /dev/null +++ b/src/app/inc/FAppPkg_PackageAppInfoImpl.h @@ -0,0 +1,384 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppPkg_PackageAppInfoImpl.h + * @brief This is the header file for the _PackageAppInfoImpl class. + */ + +#ifndef _FAPP_PKG_INTERNAL_APP_INFO_IMPL_H_ +#define _FAPP_PKG_INTERNAL_APP_INFO_IMPL_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace App { namespace Package +{ + +class _LaunchConditionInfoImpl; +class _NotificationInfoImpl; +class _AppFeatureInfoImpl; +class _DataControlInfoImpl; +class _AppControlResolutionInfoImpl; +class _AppControlCapabilityInfoImpl; +class _AppControlInfoImpl; + +class _OSP_EXPORT_ _PackageAppInfoImpl + : public Tizen::Base::Object +{ +public: + const AppId& GetAppId(void) const; + result SetAppId(const AppId& appId); + + const Tizen::Base::String& GetAppName(void) const; + result SetAppName(const Tizen::Base::String& appName); + + const Tizen::Base::String& GetAppDisplayName(void) const; + result SetAppDisplayName(const Tizen::Base::String& appDiplayName); + + const Tizen::Base::String& GetAppMenuIconPath(void) const; + result SetAppMenuIconPath(const Tizen::Base::String& iconPath); + + const Tizen::Base::String& GetAppSettingIconPath(void) const; + result SetAppSettingIconPath(const Tizen::Base::String& appSettingIcon); + + const Tizen::Base::String& GetAppNotificationIconPath(void) const; + result SetAppNotificationIconPath(const Tizen::Base::String& notificationIconPath); + + Tizen::Base::Collection::ArrayList* GetAppCategoryListN(void) const; + + bool IsMenuIconVisible(void) const; + result SetMenuIconVisible(bool visible); + + bool IsMainApp(void) const; + result SetMainApp(bool mainApp); + + static _PackageAppInfoImpl* GetInstance(PackageAppInfo* pPackageAppInfo); + + result Construct(const AppId& appId); + + // to be reviewed + _PackageAppInfoImpl(void); + virtual ~_PackageAppInfoImpl(void); + + const Tizen::Base::String& GetName(void) const; + result SetName(const Tizen::Base::String& name); + + const Tizen::Base::String& GetType(void) const; + result SetType(const Tizen::Base::String& type); + + const Tizen::Base::String& GetDefault(void) const; + result SetDefault(const Tizen::Base::String& defaultApp); + + Tizen::Base::Collection::ArrayList* GetLaunchConditionListN(void) const; + Tizen::Base::Collection::ArrayList* GetLaunchConditionList(void) const; + result AddLaunchCondition(const Tizen::App::Package::_LaunchConditionInfoImpl& launchCondition); + + Tizen::Base::Collection::ArrayList* GetNotificationListN(void) const; + Tizen::Base::Collection::ArrayList* GetNotificationList(void) const; + result AddNotification(const Tizen::App::Package::_NotificationInfoImpl& notification); + + Tizen::Base::Collection::ArrayList* GetAppFeatureListN(void) const; + Tizen::Base::Collection::ArrayList* GetAppFeatureList(void) const; + Tizen::Base::Collection::HashMapT* GetAppFeatureMapN(void) const; + result AddAppFeature(const Tizen::App::Package::_AppFeatureInfoImpl& appFeature); + + Tizen::Base::Collection::ArrayList* GetDataControlListN(void) const; + Tizen::Base::Collection::ArrayList* GetDataControlList(void) const; + result AddDataControl(Tizen::App::Package::_DataControlInfoImpl* pDataControl); + + Tizen::Base::Collection::ArrayList* GetAppControlListN(void) const; + Tizen::Base::Collection::ArrayList* GetAppControlList(void) const; + result AddAppControl(Tizen::App::Package::_AppControlInfoImpl* pAppControl); + + const Tizen::Base::String& GetPackageName(void) const; + result SetPackageName(const Tizen::Base::String& packageName); + + const Tizen::Base::String& GetMainmenuIcon(void) const; + result SetMainmenuIcon(const Tizen::Base::String& icon); + + const Tizen::Base::String& GetSettingIcon(void) const; + result SetSettingIcon(const Tizen::Base::String& icon); + + const Tizen::Base::String& GetQuickpanelIcon(void) const; + result SetQuickpanelIcon(const Tizen::Base::String& icon); + + bool IsMainmenuVisible(void) const; + result SetMainmenuVisible(bool visible); + + // to be reviewed + result AddName(const Tizen::Base::String& language, const Tizen::Base::String& name); + Tizen::Base::Collection::HashMap* GetNameList(void) const; + + int GetUniqueId(void) const; + int GetPkgId(void) const; + + result SetUniqueId(int id); + result SetPkgId(int id); + + result AddAppControl(void); + + int GetAppFeature(void) const; + result SetAppFeature(int feature); + +private: + static int CategoryHandler(const char* pCategoryName, void* pUserData); + +private: + _PackageAppInfoImpl(const _PackageAppInfoImpl& value); + _PackageAppInfoImpl& operator =(const _PackageAppInfoImpl& source); + + AppId __appId; + Tizen::Base::String __appName; + Tizen::Base::String __appDiplayName; + Tizen::Base::String __appIconPath; + Tizen::Base::String __appSettingIconPath; + Tizen::Base::String __appNotificationIconPath; + + bool __launchingIconVisible; + bool __mainApp; + + Tizen::Base::String __name; + Tizen::Base::String __type; + Tizen::Base::String __default; + + Tizen::Base::Collection::ArrayList* __pLaunchConditionImplList; + Tizen::Base::Collection::ArrayList* __pNotificationImplList; + Tizen::Base::Collection::ArrayList* __pAppFeatureImplList; + Tizen::Base::Collection::ArrayList* __pDataControlImplList; + Tizen::Base::Collection::ArrayList* __pAppControlImplList; + + Tizen::Base::String __mainmenuIcon; + Tizen::Base::String __settingIcon; + Tizen::Base::String __tickerIcon; + Tizen::Base::String __quickpanelIcon; + Tizen::Base::String __launchImageIcon; + + Tizen::Base::String __packageName; + Tizen::Base::Collection::HashMap* __pNameList; + + int __uniqueId; + int __pkgId; + + // to be reviewed + int __appFeature; + + void* __pAppInfoHandle; + + friend class PackageAppInfo; + +}; // _PackageAppInfoImpl + +class _OSP_EXPORT_ _LaunchConditionInfoImpl + : public Tizen::Base::Object +{ +public: + _LaunchConditionInfoImpl(void); + virtual ~_LaunchConditionInfoImpl(void); + + const Tizen::Base::String& GetName(void) const; + result SetName(const Tizen::Base::String& name); + + const Tizen::Base::String& GetValue(void) const; + result SetValue(const Tizen::Base::String& value); + +private: + _LaunchConditionInfoImpl(const _LaunchConditionInfoImpl& value); + _LaunchConditionInfoImpl& operator =(const _LaunchConditionInfoImpl& source); + + Tizen::Base::String __name; + Tizen::Base::String __value; + +}; // _LaunchConditionInfoImpl + +class _OSP_EXPORT_ _NotificationInfoImpl + : public Tizen::Base::Object +{ +public: + _NotificationInfoImpl(void); + virtual ~_NotificationInfoImpl(void); + + const Tizen::Base::String& GetName(void) const; + result SetName(const Tizen::Base::String& name); + + const Tizen::Base::String& GetValue(void) const; + result SetValue(const Tizen::Base::String& value); + +private: + _NotificationInfoImpl(const _NotificationInfoImpl& value); + _NotificationInfoImpl& operator =(const _NotificationInfoImpl& source); + + Tizen::Base::String __name; + Tizen::Base::String __value; +}; // _NotificationInfoImpl + +class _OSP_EXPORT_ _AppFeatureInfoImpl + : public Tizen::Base::Object +{ +public: + _AppFeatureInfoImpl(void); + virtual ~_AppFeatureInfoImpl(void); + + const Tizen::Base::String& GetName(void) const; + result SetName(const Tizen::Base::String& name); + + const Tizen::Base::String& GetValue(void) const; + result SetValue(const Tizen::Base::String& value); + +private: + _AppFeatureInfoImpl(const _AppFeatureInfoImpl& value); + _AppFeatureInfoImpl& operator =(const _AppFeatureInfoImpl& source); + + Tizen::Base::String __name; + Tizen::Base::String __value; + +}; // _AppFeatureInfoImpl + +class _OSP_EXPORT_ _DataControlTypeImpl + : public Tizen::Base::Object +{ +public: + _DataControlTypeImpl(void); + virtual ~_DataControlTypeImpl(void); + + const Tizen::Base::String& GetType(void) const; + result SetType(const Tizen::Base::String& type); + + const Tizen::Base::String& GetAccess(void) const; + result SetAccess(const Tizen::Base::String& access); + +private: + _DataControlTypeImpl(const _DataControlTypeImpl& value); + _DataControlTypeImpl& operator =(const _DataControlTypeImpl& source); + + Tizen::Base::String __type; + Tizen::Base::String __access; + +}; // _DataControlTypeImpl + +class _OSP_EXPORT_ _DataControlInfoImpl + : public Tizen::Base::Object +{ +public: + _DataControlInfoImpl(void); + virtual ~_DataControlInfoImpl(void); + + const Tizen::Base::String& GetProviderId(void) const; + result SetProviderId(const Tizen::Base::String& providerId); + + Tizen::Base::Collection::ArrayList* GetControlTypeList(void) const; + result AddControlType(_DataControlTypeImpl* pControlType); + +private: + _DataControlInfoImpl(const _DataControlInfoImpl& value); + _DataControlInfoImpl& operator =(const _DataControlInfoImpl& source); + + Tizen::Base::String __providerId; + Tizen::Base::Collection::ArrayList* __pControlTypeList; + +}; // _DataControlInfoImpl + +class _OSP_EXPORT_ _AppControlResolutionInfoImpl + : public Tizen::Base::Object +{ +public: + _AppControlResolutionInfoImpl(void); + virtual ~_AppControlResolutionInfoImpl(void); + + Tizen::Base::String* GetUriScheme(void) const; + result SetUriScheme(Tizen::Base::String* pUriScheme); + + Tizen::Base::String* GetMimeType(void) const; + result SetMimeType(Tizen::Base::String* pMimeType); + +private: + _AppControlResolutionInfoImpl(const _AppControlResolutionInfoImpl& value); + _AppControlResolutionInfoImpl& operator =(const _AppControlResolutionInfoImpl& source); + + Tizen::Base::String* __pUriScheme; + Tizen::Base::String* __pMimeType; + +}; // _AppControlResolutionInfoImpl + +class _OSP_EXPORT_ _AppControlCapabilityInfoImpl + : public Tizen::Base::Object +{ +public: + _AppControlCapabilityInfoImpl(void); + virtual ~_AppControlCapabilityInfoImpl(void); + + int GetUniqueId(void) const; + result SetUniqueId(int uniqueId); + + int GetAppControlId(void) const; + result SetAppControlId(int uniqueId); + + const Tizen::Base::String& GetOperationId(void) const; + result SetOperationId(const Tizen::Base::String& operationId); + + Tizen::Base::Collection::ArrayList* GetResolutionList(void) const; + result AddResolution(_AppControlResolutionInfoImpl* pResolution); + +private: + _AppControlCapabilityInfoImpl(const _AppControlCapabilityInfoImpl& value); + _AppControlCapabilityInfoImpl& operator =(const _AppControlCapabilityInfoImpl& source); + + int __uniqueId; + int __appControlId; + Tizen::Base::String __operationId; + Tizen::Base::Collection::ArrayList* __pResolutionList; + +}; // _AppControlCapabilityInfoImpl + +class _OSP_EXPORT_ _AppControlInfoImpl + : public Tizen::Base::Object +{ +public: + _AppControlInfoImpl(void); + virtual ~_AppControlInfoImpl(void); + + int GetUniqueId(void) const; + result SetUniqueId(int uniqueId); + + const Tizen::Base::String& GetProviderId(void) const; + result SetProviderId(const Tizen::Base::String& providerId); + + const Tizen::Base::String& GetCategory(void) const; + result SetCategory(const Tizen::Base::String& category); + + Tizen::Base::Collection::ArrayList* GetCapabilityList(void) const; + result AddCapability(_AppControlCapabilityInfoImpl* pCapability); + +private: + _AppControlInfoImpl(const _AppControlInfoImpl& value); + _AppControlInfoImpl& operator =(const _AppControlInfoImpl& source); + + int __uniqueId; + Tizen::Base::String __providerId; + Tizen::Base::String __category; + Tizen::Base::Collection::ArrayList* __pCapabilityList; + +}; // _AppControlInfoImpl + +} } } // Tizen::App::Package + +#endif // _FAPP_PKG_INTERNAL_APP_INFO_IMPL_H_ diff --git a/src/app/inc/FAppPkg_PackageInfoImpl.h b/src/app/inc/FAppPkg_PackageInfoImpl.h new file mode 100755 index 0000000..ef9c287 --- /dev/null +++ b/src/app/inc/FAppPkg_PackageInfoImpl.h @@ -0,0 +1,229 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppPkg_PackageInfoImpl.h + * @brief This is the header file for the _PackageInfoImpl class. + */ + +#ifndef _FAPP_PKG_INTERNAL_PACKAGE_INFO_IMPL_H_ +#define _FAPP_PKG_INTERNAL_PACKAGE_INFO_IMPL_H_ + +#include + +#include +#include +#include +#include + +#include + +namespace Tizen { namespace App +{ +class _AppManagerProxy; +}} + +namespace Tizen { namespace App { namespace Package +{ + +class PackageInfo; +class _PackageAppInfoImpl; + +class _OSP_EXPORT_ _PackageInfoImpl + : public Tizen::Base::Object +{ +public: + const PackageId& GetId(void) const; + result SetId(const PackageId& id); + + const Tizen::Base::String& GetVersion(void) const; + result SetVersion(const Tizen::Base::String& version); + + PackageType GetType(void) const; + result SetType(PackageType packageType); + + const Tizen::Base::String& GetDisplayName(void) const; + result SetDisplayName(const Tizen::Base::String& displayName); + + const Tizen::Base::String& GetDescription(void) const; + result SetDescription(const Tizen::Base::String& description); + + const Tizen::Base::String& GetAuthor(void) const; + result SetAuthor(const Tizen::Base::String& author); + + const Tizen::Base::String& GetUrl(void) const; + result SetUrl(const Tizen::Base::String& url); + + const Tizen::Base::DateTime& GetInstallationTime(void) const; + result SetInstallationTime(const Tizen::Base::DateTime& installationTime); + + bool IsInstalledInExternalStorage(void) const; + result SetInstalledInExternalStorage(bool externalStorage); + + bool IsUninstallable(void) const; + result SetUninstallable(bool uninstallable); + + bool IsMovable(void) const; + result SetMovable(bool movable); + + bool IsDownloaded(void) const; + result SetDownloaded(bool downloaded); + + long long GetSize(void) const; + long long GetDataSize(void) const; + + const AppId& GetMainAppId(void) const; + result SetMainAppId(const AppId& appId); + + const PackageId& GetStoreClientId(void) const; + result SetStoreClientId(const PackageId& packageId); + + Tizen::Base::Collection::ArrayList* GetPackageAppInfoListN(void) const; + Tizen::App::Package::PackageAppInfo* GetPackageAppInfoN(const AppId& appId) const; + + static int PackageAppInfoListHandler(const pkgmgrinfo_appinfo_h handle, void* pUser_data); + + // to be reviewed + _PackageInfoImpl(void); + virtual ~_PackageInfoImpl(void); + + const Tizen::Base::String& GetAppId(void) const; + result SetAppId(const Tizen::Base::String& id); + + const Tizen::Base::String& GetAppVersion(void) const; + result SetAppVersion(const Tizen::Base::String& version); + + const Tizen::Base::String& GetAppType(void) const; + result SetAppType(const Tizen::Base::String& appType); + + const Tizen::Base::String& GetAppMimeType(void) const; + result SetAppMimeType(const Tizen::Base::String& appMimeType); + + const Tizen::Base::String& GetAppApiVersion(void) const; + result SetAppApiVersion(const Tizen::Base::String& appApiVersion); + + const Tizen::Base::String& GetAppName(void) const; + result SetAppName(const Tizen::Base::String& appName); + + const Tizen::Base::String& GetAppDescription(void) const; + result SetAppDescription(const Tizen::Base::String& appDescription); + + const Tizen::Base::String& GetAppVendor(void) const; + result SetAppVendor(const Tizen::Base::String& appVendor); + + const Tizen::Base::String& GetAppUrl(void) const; + result SetAppUrl(const Tizen::Base::String& AppUrl); + + const Tizen::Base::String& GetAppCid(void) const; + result SetAppCid(const Tizen::Base::String& appCid); + + const Tizen::Base::String& GetAppRootPath(void) const; + result SetAppRootPath(const Tizen::Base::String& rootPath); + + int GetAppStorageType(void) const; + result SetAppStorageType(int storageType); + + int GetCertType(void) const; + result SetCertType(int certType); + + Tizen::Base::Collection::ArrayList* GetAppInfoListN(void) const; + Tizen::Base::Collection::ArrayList* GetAppInfoList(void); + result AddAppInfo(const Tizen::App::Package::_PackageAppInfoImpl& appInfoImpl); + + result GetPrivileges(Tizen::Base::String& privileges, Tizen::Base::String& hmacPrivileges); + result GetPrivilegesValue(Tizen::Base::String& privileges, Tizen::Base::String& hmacPrivileges) const; + result SetPrivilegesValue(const Tizen::Base::String& privileges, const Tizen::Base::String& hmacPrivileges); + + int GetApiVisibility() const; + + const Tizen::Base::String& GetAppIconPath(void) const; + result SetAppIconPath(const Tizen::Base::String& appIconPath); + + const Tizen::Base::DateTime& GetAppInstallationTime(void) const; + result SetAppInstallationTime(const Tizen::Base::DateTime& installationTime); + + result GetUiScalabilityInfo(Tizen::Base::String& baseScreenSize, Tizen::Base::String& coordinateSystem, Tizen::Base::String& logicalCoordinate) const; + + // to be reviewed + const Tizen::Base::String& GetAppPackageName(void); + + const Tizen::Base::String& GetApiVersion(void) const; + result SetApiVersion(const Tizen::Base::String& apiVersion); + + const Tizen::Base::String& GetName(void) const; + result SetName(const Tizen::Base::String& name); + + result Construct(const PackageId& packageId); + + int GetUniqueId(void) const; + + static _PackageInfoImpl* GetInstance(PackageInfo* pPackageInfo); + static const _PackageInfoImpl* GetInstance(const PackageInfo* pPackageInfo); + +private: + static bool GetPackageAppInfo(const pkgmgrinfo_appinfo_h handle, PackageAppInfo* pPackageAppInfo); + +private: + Tizen::Base::String __id; + Tizen::Base::String __version; + Tizen::Base::String __type; + Tizen::Base::String __appMimeType; + Tizen::Base::String __appApiVersion; + Tizen::Base::String __displayName; + Tizen::Base::String __description; + Tizen::Base::String __author; + Tizen::Base::String __url; + Tizen::Base::String __appCid; + Tizen::Base::String __appParentId; + Tizen::Base::String __appRootPath; + Tizen::Base::String __appIconPath; + Tizen::Base::DateTime __dateTime; + + int __appReadOnlySize; + int __appDataSize; + int __appStorageType; + int __appState; + int __certType; + + AppId __mainAppId; + PackageId __storeClientId; + + Tizen::Base::Collection::ArrayList* __pAppInfoImplList; + Tizen::Base::String __privileges; + Tizen::Base::String __hmacPrivileges; + + // to be reviewed + Tizen::Base::String __appPackageName; + + pkgmgrinfo_pkginfo_h __packageInfoHandle; + bool __uninstallable; + bool __movable; + bool __downloaded; + bool __iconAvailable; + bool __externalStorage; + + PackageType __packageType; + + PackageInfo* __pPackageInfo; + + friend class PackageInfo; + +}; // _PackageInfoImpl + +} } } // Tizen::App::Package + +#endif //_FAPP_PKG_INTERNAL_PACKAGE_INFO_IMPL_H_ diff --git a/src/app/inc/FAppPkg_PackageManagerImpl.h b/src/app/inc/FAppPkg_PackageManagerImpl.h new file mode 100755 index 0000000..9c2c830 --- /dev/null +++ b/src/app/inc/FAppPkg_PackageManagerImpl.h @@ -0,0 +1,193 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FAppPkg_PackageManagerImpl.h + * @brief This is the header file for the _PackageManagerImpl class. + */ + +#ifndef _FAPP_PKG_INTERNAL_PACKAGE_MANAGER_IMPL_H_ +#define _FAPP_PKG_INTERNAL_PACKAGE_MANAGER_IMPL_H_ + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ +class IEventArg; +}}} + +namespace Tizen { namespace Io +{ +class Database; +class DbStatement; +class DbEnumerator; +}} + +namespace Tizen { namespace App { namespace Package +{ + +class _PackageInfoImpl; +class IPackageInstallationEventListener; +class IPackageInstallationResponseListener; +class IPackageUninstallationResponseListener; + +static const int MAX_DATABASE_RETRY_COUNT = 30; +extern const wchar_t PACKAGE_DATABASE_FILE_NAME[]; + +enum PackageStorageType +{ + PACKAGE_STORAGE_TYPE_INTERNAL, + PACKAGE_STORAGE_TYPE_EXTERNAL, +}; + +class _PackageManagerEventArg + : public Tizen::Base::Runtime::IEventArg +{ +public: + _PackageManagerEventArg() + : __install(true) + { + } + + PackageId __packageId; + Tizen::Base::String __eventKey; + Tizen::Base::String __eventValue; + bool __install; +}; + +class _PackageManagerEvent + : public Tizen::Base::Runtime::_Event +{ +public: + _PackageManagerEvent() + : __pListener(null) + { + } + + IPackageInstallationEventListener* __pListener; + +public: + result Construct(void) + { + return _Event::Initialize(); + } + +protected: + virtual void FireImpl(Tizen::Base::Runtime::IEventListener& listener, const Tizen::Base::Runtime::IEventArg& arg); +}; + +class _OSP_EXPORT_ _PackageManagerImpl + : public Tizen::Base::Object +{ +public: + static PackageId GetPackageIdByAppId(const AppId& appId); + + result AddEventListener(IPackageInstallationEventListener* pListener, int priority = 2); + result RemoveEventListener(IPackageInstallationEventListener* pListener); + + Tizen::App::Package::PackageInfo* GetPackageInfoN(const PackageId& packageId) const; + Tizen::App::Package::PackageAppInfo* GetPackageAppInfoN(const AppId& appId) const; + Tizen::Base::Collection::IList* GetPackageInfoListN(void) const; + + bool IsPackageInstalled(const PackageId& packageId) const; + + result InstallPackage(const PackageId& packageId, const Tizen::Base::String& packagePath, Tizen::App::Package::IPackageInstallationResponseListener* pListener); + result UninstallPackage(const PackageId& packageId, Tizen::App::Package::IPackageUninstallationResponseListener* pListener); + + result MoveToExternalStorage(const PackageId& packageId); + result MoveToInternalStorage(const PackageId& packageId); + + static _PackageManagerImpl* GetInstance(void); + + void SendPackageEvent(PackageType type, const PackageId& packageId, const char* eventKey, const char* eventValue); + + Tizen::Base::String* GetAppIdOfDataControlN(const Tizen::Base::String& providerId); + + result CreatePackageTables(void); + + Tizen::App::Package::PackageInfo* GetPackageInfoN(const Tizen::Base::String& providerId, const Tizen::Base::String& operationId) const; + Tizen::App::Package::PackageInfo* GetPackageInfoN(PackageType packageType, const Tizen::Base::String& packageName) const; + + static int PackageInfoEventHandler(const pkgmgrinfo_pkginfo_h handle, void* pUser_data); + + Tizen::Base::Collection::IList* GetFilteredAppIdListN(const Tizen::Base::String& feature, const Tizen::Base::String& value) const; + Tizen::Base::Collection::IList* GetDataControlInfoN(const Tizen::Base::String& providerId, const Tizen::Base::String& type) const; + Tizen::Base::Collection::IMap* GetUiThemeListN(const PackageId& packageId) const; + + result RegisterPackageInfo(Tizen::App::Package::_PackageInfoImpl& pkgInfoImpl); + result UnregisterPackageInfo(const PackageId& packageId); + Tizen::Base::Collection::ArrayList* GetPackageAppInfoImplListN(const PackageId& packageId) const; + Tizen::Base::Collection::ArrayList* GetPackageAppFeatureListN(const PackageId& packageId, const Tizen::Base::String& executableName) const; + Tizen::Base::Collection::HashMapT* GetPackageAppFeatureMapN(const PackageId& packageId, const Tizen::Base::String& executableName) const; + Tizen::Base::Collection::ArrayList* GetAppLaunchConditionListN(const Tizen::Base::String& packageName) const; + + result GetPackageName(const PackageId& packageId, const Tizen::Base::String* pName, char* pPackageName, int bufferSize); + Tizen::Base::String GetDefaultAppExecutableName(const PackageId& packageId); + + static bool IsAppInstalled(const AppId& appId); + + static Tizen::Io::DbStatement* CreateStatementN(Tizen::Io::Database& db, const Tizen::Base::String& query); + static Tizen::Io::DbEnumerator* ExecuteStatementN(Tizen::Io::Database& db, const Tizen::Io::DbStatement* pStmt); + +private: + result Construct(void); + + _PackageManagerImpl(void); + virtual ~_PackageManagerImpl(void); + + result GetAppInfo(int uniqueId, Tizen::App::Package::_PackageAppInfoImpl& appInfo) const; + + result RegisterAppInfoList(int id, Tizen::Base::Collection::ArrayList* pList); + result RegisterLaunchConditionList(int id, Tizen::Base::Collection::ArrayList* pList); + result RegisterNotificationList(int id, Tizen::Base::Collection::ArrayList* pList); + result RegisterAppFeatureList(int id, Tizen::Base::Collection::ArrayList* pList); + result RegisterDataControlList(int id, Tizen::Base::Collection::ArrayList* pList); + result RegisterPrivileges(int id, const Tizen::Base::String& privileges, const Tizen::Base::String& hmacPrivileges, int certType); + + int FindRecord(const Tizen::Base::String& tableName, const Tizen::Base::String& columnName, const Tizen::Base::String& value) const; + result GetRecord(const Tizen::Base::String& tableName, int uniqueId, const Tizen::Base::String& columnName, Tizen::Base::String& value) const; + + static int PackageEventHandler(int req_id, const char* pkg_type, const char* pkg_name, const char* key, const char* val, const void* pmsg, void* data); + static int InstallationEventHandler(int reqId, const char* pType, const char* pPackageId, const char* pKey, const char* pVal, const void* pMsg, void* pData); + static int UninstallationEventHandler(int reqId, const char* pType, const char* pPackageId, const char* pKey, const char* pVal, const void* pMsg, void* pData); + +protected: + friend class PackageManager; + +private: + void* __pRequestClient; + void* __pListeningClient; + Tizen::Io::Database* __pDb; + static Tizen::Base::Collection::HashMap __installationList; + Tizen::Base::Collection::LinkedListT <_PackageManagerEvent*> __packageEventListenerList; + +}; // _PackageManagerImpl + +} } } // Tizen::App::Package + +#endif // _FAPP_PKG_INTERNAL_PACKAGE_MANAGER_IMPL_H_ diff --git a/src/app/inc/FApp_AppArg.h b/src/app/inc/FApp_AppArg.h new file mode 100644 index 0000000..2340fdd --- /dev/null +++ b/src/app/inc/FApp_AppArg.h @@ -0,0 +1,222 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppArg.h + * @brief This is the header file of the _AppArg class. + * + * This header file contains the declarations of the _AppArg class. + */ + +#ifndef _FAPP_INTERNAL_APP_ARG_H_ +#define _FAPP_INTERNAL_APP_ARG_H_ + +#include + +#include +#include + +#include "FApp_Types.h" + +namespace Tizen { namespace Base { namespace Collection { +class ArrayList; +class IList; +class HashMap; +}}} + +namespace Tizen { namespace App +{ + +class _AppControlImpl; +class _SqlDataControlImpl; +class _MapDataControlImpl; + +enum _DataControlRequestType +{ + _DATACONTROL_REQUEST_TYPE_UNDEFINED = 0, + _DATACONTROL_REQUEST_TYPE_SQL_QUERY, + _DATACONTROL_REQUEST_TYPE_SQL_INSERT, + _DATACONTROL_REQUEST_TYPE_SQL_UPDATE, + _DATACONTROL_REQUEST_TYPE_SQL_DELETE, + _DATACONTROL_REQUEST_TYPE_MAP_QUERY, + _DATACONTROL_REQUEST_TYPE_MAP_INSERT, + _DATACONTROL_REQUEST_TYPE_MAP_UPDATE, + _DATACONTROL_REQUEST_TYPE_MAP_DELETE +}; + +#define OSP_K_CALLER_TYPE "__OSP_CALLER_TYPE__" +#define OSP_K_LAUNCH_TYPE "__OSP_LAUNCH_TYPE__" +#define OSP_K_ARG "__OSP_ARGS__" +#define OSP_K_COND "__OSP_COND_NAME__" +#define OSP_K_APPID "__OSP_APPID__" +#define OSP_K_REQUEST_ID "__OSP_REQUEST_ID__" +#define OSP_K_APPCONTROL_INTERNAL_OPERATION "__OSP_APPCONTROL_INTERNAL_INTERNAL_OPERATION__" +#define OSP_K_DATACONTROL_PROVIDER "__OSP_DATACONTROL_PROVIDER__" +#define OSP_K_DATACONTROL_REQUEST_TYPE "__OSP_DATACONTROL_REQUEST_TYPE__" + +/** + * @class _AppArg + * @brief + * @since 2.1 + */ +class _OSP_EXPORT_ _AppArg +{ +public: + _AppArg(void); + + ~_AppArg(void); + + result Construct(const Tizen::Base::String& argText); + + result Construct(const Tizen::Base::Collection::IList* pList); + + result Construct(const Tizen::Base::String* pUri, const Tizen::Base::String* pMime, const Tizen::Base::Collection::IMap* pMap); + + result Construct(const _AppControlImpl& ac, const Tizen::Base::Collection::IList* pList); + + result Construct(const _AppControlImpl& ac, const Tizen::Base::String* pUri, const Tizen::Base::String* pMime, const Tizen::Base::Collection::IMap* pMap); + + result Construct(const _SqlDataControlImpl& dc, _DataControlRequestType requestType, const Tizen::Base::Collection::IList* pList); + + result Construct(const _MapDataControlImpl& dc, _DataControlRequestType requestType, const Tizen::Base::Collection::IList* pList); + + result ConstructResult(const _AppArg& arg, const Tizen::Base::Collection::IList* pList); + + result ConstructResult(const _AppArg& arg, const Tizen::Base::Collection::IMap* pMap); + + result Construct(bundle* b); + + result ConstructForAppLaunchCondition(const Tizen::Base::String& condition, const Tizen::Base::Collection::IList* pList); + + Tizen::Base::Collection::ArrayList* GetArgListN(int num) const; + + Tizen::Base::Collection::ArrayList* GetArgListN(void) const; + + Tizen::Base::Collection::HashMap* GetArgMapN(void) const; + + Tizen::Base::String GetValue(const char* key) const; + + bundle* GetBundle(void) const + { + return __pBundle; + } + + _AppHandler GetHandler(void) const + { + return GetHandler(__pBundle); + } + + AppId GetCallerAppId(void) const; + + int GetCallerPid(void) const + { + return GetCallerPid(__pBundle); + } + + AppId GetCalleeAppId(void) const; + + void Print() const + { + Print(__pBundle); + } + + void UpdateAppId(const AppId& appId) + { + UpdateAppId(__pBundle, appId); + } + + void UpdateRequestId(int reqId) + { + UpdateRequestId(__pBundle, reqId); + } + + result UpdateWindowHandle(long handle) + { + return UpdateWindowHandle(__pBundle, handle); + } + + static int GetCallerPid(bundle* b); + + static void Print(bundle* b); + + static void PrintSvcHandle(void* svc); + + static _AppHandler GetHandler(bundle* b); + + static bundle* GetBundleFromSvc(void* svc); + + static Tizen::Base::String GetRequestId(int num); + + static int GetRequestId(const Tizen::Base::String& id); + + static void UpdateAppId(bundle* b, const AppId& appid); + + static int GetRequestIdFromBundle(bundle* p); + + static void UpdateRequestId(bundle* b, int reqId); + + static result UpdateWindowHandle(bundle* b, long handle); + + static Tizen::Base::Collection::ArrayList* GetListN(bundle* b, const char* key); + + static result AddStrMap(bundle* b, const Tizen::Base::Collection::IMap* pMap); + + static result FillMapFromList(Tizen::Base::Collection::IMap* pMap, const Tizen::Base::Collection::IList* pList); + + static result FillLegacyAppControlResult(Tizen::Base::Collection::IList& list, int res, const Tizen::Base::Collection::IMap* pMap, const Tizen::Base::String& aId); +private: + _AppArg(const _AppArg& value); + + _AppArg& operator =(const _AppArg& source); + + static result CreateLaunchArg(bundle* b, const Tizen::Base::String& arg); + + static result CreateLaunchArg(bundle* b, const Tizen::Base::Collection::IList* pList); + + static result CreateAppControlArg(bundle* b, const _AppControlImpl& ac, const Tizen::Base::Collection::IList* pList); + + static result CreateAppControlArg(bundle* b, const _AppControlImpl& ac, const Tizen::Base::String* pUri, const Tizen::Base::String* pMime, const Tizen::Base::Collection::IMap* pList); + + static result CreateSqlDataControlArg(bundle* b, const _SqlDataControlImpl& dc, _DataControlRequestType requestType, const Tizen::Base::Collection::IList* pList); + + static result CreateMapDataControlArg(bundle* b, const _MapDataControlImpl& dc, _DataControlRequestType requestType, const Tizen::Base::Collection::IList* pList); + + static result CreateAppLaunchConditionArg(bundle* b, const Tizen::Base::String& condition, const Tizen::Base::Collection::IList* pList); + + static result CreateResultArg(bundle* b, const Tizen::Base::Collection::IList* pList); + + static result CreateResultArg(bundle* b, const Tizen::Base::Collection::IMap* pList); + + static result AddStrArray(bundle* b, const char* key, const Tizen::Base::Collection::IList* pList); + + static result AddStrArray(bundle* b, const Tizen::Base::String& key, const Tizen::Base::Collection::IList* pList); + + static bundle* CreateBundleFromSvc(void* svc); + + static inline void AddListFromBundle(Tizen::Base::Collection::ArrayList* pList, bundle* b, const char* key); + + static result SetArgList(bundle* pBundle, Tizen::Base::Collection::ArrayList* pList); + + static result SetArgMap(bundle* pBundle, Tizen::Base::Collection::HashMap* pList); + +private: + bundle* __pBundle; +}; // _AppArg + +} } // Tizen::App + +#endif //_FAPP_INTERNAL_APP_ARG_H_ diff --git a/src/app/inc/FApp_AppControlEvent.h b/src/app/inc/FApp_AppControlEvent.h new file mode 100644 index 0000000..4498974 --- /dev/null +++ b/src/app/inc/FApp_AppControlEvent.h @@ -0,0 +1,53 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlEvent.h + * @brief This is the header file of _AppControlEvent + */ + +#ifndef _FAPP_INTERNAL_APP_CONTROL_EVENT_H_ +#define _FAPP_INTERNAL_APP_CONTROL_EVENT_H_ + +#include +#include +#include + +namespace Tizen { namespace App +{ + +/** +* @class _AppControlEvent +* @brief This class contains application control event +* @since 1.0 +*/ +class _AppControlEvent + : public Tizen::Base::Runtime::_Event +{ +public: + result Construct(void) + { + return _Event::Initialize(); + } + +protected: + void FireImpl(Tizen::Base::Runtime::IEventListener& lstener, const Tizen::Base::Runtime::IEventArg& arg); +}; // _AppControlEvent + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_CONTROL_EVENT_H_ diff --git a/src/app/inc/FApp_AppControlImpl.h b/src/app/inc/FApp_AppControlImpl.h new file mode 100755 index 0000000..fc51ce9 --- /dev/null +++ b/src/app/inc/FApp_AppControlImpl.h @@ -0,0 +1,292 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlImpl.h + * @brief This is the header file for the _AppControlImpl class. + */ + +#ifndef _FAPP_INTERNAL_APP_CONTROL_IMPL_H_ +#define _FAPP_INTERNAL_APP_CONTROL_IMPL_H_ + +#include +#include + +#include +#include +#include +#include + +#include "FApp_AppManagerImpl.h" + +namespace Tizen { namespace Base { class String; } } +namespace Tizen { namespace Base { namespace Collection { class IList; } } } + +namespace Tizen { namespace App +{ + +class AppControl; +class IAppControlEventListener; +class IAppControlResponseListener; +class _AppArg; + +enum _AppControlType +{ + _APPCONTROL_TYPE_NONE = 0, + _APPCONTROL_TYPE_NATIVE = 2, + _APPCONTROL_TYPE_OSP = 3, +}; + +enum _AppControlProperty +{ + _APPCONTROL_PROPERTY_NONE = 0x0, + _APPCONTROL_PROPERTY_PUBLIC = 0x01, + _APPCONTROL_PROPERTY_PERSISTENT_DLL = 0x08, + _APPCONTROL_PROPERTY_SLP = 0x100, + _APPCONTROL_PROPERTY_OSP = 0x200, + _APPCONTROL_PROPERTY_ALIAS = 0x400, + _APPCONTROL_PROPERTY_APPID_CHANGE = 0x800, +}; + +class _OSP_EXPORT_ _AppControlImpl + : public Tizen::Base::Object +{ +public: + /** + * AppControl delegate constructor + */ + static AppControl* CreateN(const Tizen::Base::String& path, const Tizen::Base::String& aId, const Tizen::Base::String& oId, const Tizen::Base::String& name, int prop); + + /** + * AppControl delegate constructor + */ + static AppControl* CreateN(const AppId& appId, const Tizen::Base::String& operationId, bool changeAppId); + + /** + * AppControl delegate constructor + */ + static AppControl* CreateN(const AppControl& ac); + + /** + * Internal GetImpl() method. + */ + static const _AppControlImpl* GetInstance(const AppControl& ac); + + /** + * Internal GetImpl() method. + */ + static _AppControlImpl* GetInstance(AppControl& ac); + + /** + * Starts the resolved application control. @n + * Once the application starts, it goes to the background and the target + * application control is displayed. + * + * @return An error code + * @param[in] pDataList The data list to deliver to the resolved application control @n + * The maximum size of the list is 4096 bytes. + * @param[in] pListener The application control callback listener @n + * Some application controls need to get the callback result by implementing + * the IAppControlEventListener interface. + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The size of @c pDataList has exceeded the maximum limit. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The target application control resource is not found. + * @exception E_IN_PROGRESS The application control is in progress: @n + * - The application has already started an _AppControlImpl. @n + * - The target application has already started. + * @exception E_SYSTEM A system error has occurred. + * @remarks If the %IAppControlEventListener instance (@c pListener) needs to get the + * callback result for an application control, it should be valid till + * IAppControlEventListener::OnAppControlCompleted() is invoked. + * For example, a form object listener should not be deleted before the + * system invokes IAppControlEventListener::OnAppControlCompleted(). + */ + result Start(const Tizen::Base::Collection::IList* pDataList, IAppControlEventListener* pListener); + + /** + * Starts the found application control. @n + * Once the found application starts, the calling application goes to the background and the found + * application is displayed. + * + * @return An error code + * @param[in] pUriData A pointer to the URI data + * @param[in] pDataType A pointer to the MIME type (RFC 2046) data + * @param[in] pExtraData The Tizen::Base::String key and Tizen::Base::String value pair map to deliver to the resolved application @n + * The maximum size is 16 kilo bytes. + * @param[in] pListener The application control callback listener @n + * Some application need to get the result by implementing the IAppControlResponseListener interface. + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The size of @c pExtraData has exceeded the maximum limit. + * @exception E_OBJ_NOT_FOUND The target application control is not found. + * @exception E_IN_PROGRESS The application control is in progress: @n + * - The application has already started an %AppControl. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @remarks If the calling application needs to get some result for application control, + * it must be valid till %IAppControlResponseListener::OnAppControlCompleteResponseReceived() is invoked. + * For example, a form object listener must not be deleted before the + * system invokes %IAppControlResponseListener::OnAppControlCompleteResponseReceived(). + * @see IAppControlResponseListener, AppManager::FindAppControlN(), AppManager::FindAppControlsN() + */ + result Start(const Tizen::Base::String* pUriData, const Tizen::Base::String* pDataType, const Tizen::Base::Collection::IMap* pExtraData, IAppControlResponseListener* pListener); + + /** + * Gets the name of the application that provides the features represented by this %_AppControlImpl instance. + * + * @return The name of the application providing this %_AppControlImpl instance + */ + Tizen::Base::String GetAppName(void); + + /** + * Gets the associated application ID. @n + * + * @return The application control ID + */ + Tizen::Base::String GetAppId(void) const; + + /** + * Gets the associated application control provider ID. @n + * + * @return The application control provider ID + */ + const Tizen::Base::String& GetAppControlProviderId(void) const; + + /** + * Gets the associated operation ID. @n + * + * @return The operation ID + */ + const Tizen::Base::String& GetOperationId(void) const; + + /** + * Returns the associated application control categories. + * + * @return A pointer to the list of application control categories, @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetCategoryListN(void) const; + + /** + * Stops the activated application control. @n + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The application control is not permitted to call this method. + * @remarks This method is asynchronous. + */ + result Stop(void); + + /** + * Finds the matching application control with given operation ID, URI pattern, data type and category and + * starts the found one. @n + * If there are more than one application controls found, then the selection is shown for user and the one that the user selects is started. + * When the found application control is started, the URI pattern, MIME type, and extra data is delivered via IAppControlProviderEventListener. + * + * @return An error code + * @param[in] pOperationId The operation ID + * @param[in] pUriPattern A URI pattern which is used for application control resolution and to be delivered as the argument + * @param[in] pDataType The MIME type (RFC 2046) or file extension @n + * The '.' prefix must be used when specifying the file extension. + * @param[in] pCategory The application control category + * @param[in] pExtraData The extra collection data to be delivered to the resolved application @n + * The maximum size is 16 kilo bytes. + * @param[in] pListener A listener that gets notified + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The size of @c pDataList has exceeded the maximum limit. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_SYSTEM The method cannot proceed due to a severe system error. + * @see IAppControlResponseListener, IAppControlProviderEventListener + */ + static result FindAndStart(const Tizen::Base::String& operationId, const Tizen::Base::String* pUriPattern, const Tizen::Base::String* pDataType, const Tizen::Base::String* pCategory, const Tizen::Base::Collection::IMap* pExtraData, IAppControlResponseListener* pListener); + + /** + * Stops the event listener for receiving application control result. + * + * @param[in] pListener The listener to stop receiving the application control result + */ + static void StopAppControlResponseListener(IAppControlResponseListener* pListener); + + static result StartImplicit(bundle* pBundle, const Tizen::Base::Collection::IList* pDataList, IAppControlEventListener* pListener); + + static result StartImplicit(bundle* pBundle, const Tizen::Base::Collection::IMap* pData, IAppControlResponseListener* pListener); + + bool IsPublic(void) const + { + return (_property & _APPCONTROL_PROPERTY_PUBLIC); + } + + void SetProperty(int prop) + { + _property |= prop; + } + +private: + _AppControlImpl(const AppControl& value); + + /** + * This is the default constructor for this class. + */ + _AppControlImpl(void); + + _AppControlImpl(const _AppControlImpl& rhs); + + _AppControlImpl& operator =(const _AppControlImpl& rhs); + + /** + * This is the destructor for this class. + */ + virtual ~_AppControlImpl(void); + + result StartOsp(const Tizen::Base::Collection::IList* pDataList, IAppControlEventListener* pListener); + + result StartOsp(const Tizen::Base::String* pUriData, const Tizen::Base::String* pMimeType, const Tizen::Base::Collection::IMap* pExtraData, IAppControlResponseListener* pListener); + + result StartNative(const Tizen::Base::Collection::IList* pDataList, IAppControlEventListener* pListener); + + result StartNative(const Tizen::Base::String* pUriData, const Tizen::Base::String* pMimeType, const Tizen::Base::Collection::IMap* pExtraData, IAppControlResponseListener* pListener); + + static result InvokeStartAppControl(Tizen::Base::Runtime::_LibraryImpl& lib, int req, const Tizen::Base::String& appId, const Tizen::Base::String& oId, const Tizen::Base::String* pUri, const Tizen::Base::String* pMime, const Tizen::Base::Collection::IMap* pMap); + + static result InvokeStartAppControl(Tizen::Base::Runtime::_LibraryImpl& lib, int req, const Tizen::Base::String& appId, const Tizen::Base::String& oId, const Tizen::Base::Collection::IList* pList); + + static result AppControlCbLegacy(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop); + + static result AppControlCb(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop); + +protected: + const AppControl& _appControl; + + Tizen::Base::String _path; + Tizen::Base::String _provider; + Tizen::Base::String _opId; + Tizen::Base::String _appName; + int _reqId; + int _property; + int _processId; + + friend class AppControl; + friend class _AppArg; +}; // _AppControlImpl + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_CONTROL_IMPL_H_ diff --git a/src/app/inc/FApp_AppControlManager.h b/src/app/inc/FApp_AppControlManager.h new file mode 100755 index 0000000..adce2a7 --- /dev/null +++ b/src/app/inc/FApp_AppControlManager.h @@ -0,0 +1,295 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppControlManager.h + * @brief This is the header file for the _AppControlManager class. + */ + +#ifndef _FAPP_INTERNAL_APP_CONTROL_MANAGER_H_ +#define _FAPP_INTERNAL_APP_CONTROL_MANAGER_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FApp_Types.h" +#include "FApp_AppControlEvent.h" +#include "FApp_IAppControlSysEventListener.h" +#include "FApp_AppManagerEvent.h" +#include "FApp_IAppManagerServiceEventListener.h" +#include "FApp_RequestManagerT.h" + +namespace Tizen { namespace Base +{ +class String; +namespace Runtime +{ +class _LibraryImpl; +} +namespace Collection +{ +class IMap; +} +}} +namespace Tizen { namespace Io +{ +class DataControlResultSet; +class _DataControlResultSetImpl; +}} + +namespace Tizen { namespace App +{ + +class _IAppManager; +class _ConditionManagerProxy; +class _AppArg; +class _AppControlEventArg; +class _IAppManagerEventListener; +class _AppManagerEventArg; +class _AppMessageImpl; + +typedef result (*LaunchCbType)(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop); + +typedef void (*AppSvcResFn)(void* b, int requestCode, service_result_e res, void* data); + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// _LaunchInfo handles the launch request from this process +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +const long LAUNCH_INFO_MAGIC = 0x494C; + +class _LaunchInfo +{ +public: + _LaunchInfo(_AppArg* pArg, LaunchCbType pCb, void* pData, int prop) + : magic(LAUNCH_INFO_MAGIC) + , reqId(-1) + , pArg(pArg) + , launchCb(pCb) + , pUserData(pData) + , property(prop) + { + } + + ~_LaunchInfo(void); + +private: + _LaunchInfo(const _LaunchInfo& rhs); + _LaunchInfo& operator =(const _LaunchInfo& rhs); + +public: + const long magic; + int reqId; + _AppArg* pArg; + const LaunchCbType launchCb; + void* pUserData; + const int property; +}; // _LaunchInfo + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// _InAppRequestManager manges In-process AppControl request +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +struct _InProcessInfo +{ +public: + _InProcessInfo(const Tizen::Base::String& aId, const Tizen::Base::String& oId, int prop, bool legacy, Tizen::Base::Runtime::_LibraryImpl& lib, Tizen::Base::Runtime::IEventListener* pListener) + : reqId(-1) + , providerId(aId) + , operationId(oId) + , property(prop) + , pLib(&lib) + , pListener(pListener) + , isLegacy(legacy) + { + } + + ~_InProcessInfo(void); + +private: + _InProcessInfo(const _InProcessInfo& rhs); + _InProcessInfo& operator =(const _InProcessInfo& rhs); + +public: + int reqId; + const Tizen::Base::String providerId; + const Tizen::Base::String operationId; + const int property; + Tizen::Base::Runtime::_LibraryImpl* pLib; // non-empty + Tizen::Base::Runtime::IEventListener* pListener; + bool isLegacy; +}; // _InProcessInfo + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// _RequestManager manges out-of-process launch request and handles the return arguments +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +class _ResultInfo +{ +public: + _ResultInfo(_AppArg& arg) + : reqId(-1) + , arg(arg) + { + } + + ~_ResultInfo(void) + { + } + +private: + _ResultInfo(const _ResultInfo& rhs); + _ResultInfo& operator =(const _ResultInfo& rhs); + +public: + int reqId; + _AppArg& arg; +}; // _ResultInfo + +// partial specialization +template<> inline void _RequestManagerT<_ResultInfo>::RemoveItem(int reqId) +{ + // 1st request is launch request itself and do not remove it ever. + if (reqId == 0) + { + return; + } + + _ResultInfo* pItem = FindItem(reqId); + if (pItem) + { + __requestList.Remove(reqId); + delete pItem; + } +} + + +class _OSP_EXPORT_ _AppControlManager + : public Tizen::Base::Object + , public _IAppControlSysEventListener + , virtual public Tizen::Base::Runtime::IEventListener +{ +public: + class _RequestGuard + { + public: + _RequestGuard(_AppControlManager& mgr, _AppArg* pArg, LaunchCbType pCb, void* pData, int prop) + : __mgr(mgr) + , __req(mgr.AddLaunchRequest(pArg, pCb, pData, prop)) + { + } + + ~_RequestGuard(void) + { + } + + int + GetRequestNumber(void) const + { + return __req; + } + + void + Invalidate(void) + { + __mgr.RemoveLaunchRequest(__req); + } + + private: + _AppControlManager& __mgr; + const int __req; + }; + + static _AppControlManager* GetInstance(void); + + virtual void OnAppControlEventReceivedN(int reqId, _AppArg* pAppArg, int res); + + virtual void OnAppControlEventReceivedN(int reqId, int res, const Tizen::Base::Collection::IMap* pArgs); + + virtual void OnAppControlEventReceivedN(int reqId, const AppId& appId, const Tizen::Base::String& operationId); + + _OSP_LOCAL_ result SendAppControlEvent(Tizen::Base::Runtime::IEventArg& arg); + + _OSP_LOCAL_ result RegisterRequest(service_s* service, int& req, _AppHandler& handler); + + _OSP_LOCAL_ void RemoveResultRequest(int reqId) + { + __resultManager.RemoveItem(reqId); + } + + const _AppArg* FindResultRequest(int reqId) const; + + void FinishAppControl(int reqId, int res, const Tizen::Base::Collection::IMap* pArg); + + result LaunchApp(const AppId& appId, _AppArg* pArg, int req = -1); + int Launch(const AppId& appId, _AppArg* pArg, int req = -1); + + result LaunchAppImplicit(_AppArg* pArg, int req); + + result LaunchPkg(const char* pkg_name, const char* op, const char* mime, const char* uri, AppSvcResFn pCb, void* data); + + result LaunchPkg(_AppMessageImpl& msg, const char* pkg_name, const char* op, const char* mime, const char* uri, AppSvcResFn pCb, void* data); + + int Launch(_AppMessageImpl& msg, const char* pkg_name, const char* op, const char* mime, const char* uri, AppSvcResFn pCb, void* data); + result LaunchAppWithCondition(const AppId& appId, const Tizen::Base::String& executableName, const Tizen::Base::String& condition, Tizen::Base::Collection::IList* pArgs); + + result SendAppControlStartResponse(int req, const char* pValue, const char* pOp); + + static bool IsAllowedAppControl(const wchar_t aTable[][2][64], int count, const Tizen::Base::String& aId, const Tizen::Base::String& oId); + + static result GetMimeFromExt(const Tizen::Base::String& ext, Tizen::Base::String& out); + +private: + _OSP_LOCAL_ _AppControlManager(void); + + _OSP_LOCAL_ virtual ~_AppControlManager(void); + + _AppControlManager(const _AppControlManager& rhs); + + _AppControlManager& operator =(const _AppControlManager& rhs); + + _OSP_LOCAL_ int AddLaunchRequest(_AppArg* pArg, LaunchCbType pCb, void* data, int prop = -1); + + _OSP_LOCAL_ void RemoveLaunchRequest(int req); + +private: + _AppControlEvent __appControlEvent; + _RequestManagerT<_LaunchInfo> __launchManager; + _RequestManagerT<_InProcessInfo> __inAppManager; + _RequestManagerT<_ResultInfo> __resultManager; + + //friend class AppManager; + friend class _AppControlImpl; + //friend class _SqlDataControlImpl; + //friend class _MapDataControlImpl; + friend class _DataControlProviderManagerImpl; + friend class _AppControlProviderManagerImpl; + friend class Tizen::Io::_DataControlResultSetImpl; +}; // _AppControlManager + +}} // Tizen::App + +#endif // _FAPP_INTERNAL_APP_CONTROL_MANAGER_H_ diff --git a/src/app/inc/FApp_AppImpl.h b/src/app/inc/FApp_AppImpl.h new file mode 100644 index 0000000..2797212 --- /dev/null +++ b/src/app/inc/FApp_AppImpl.h @@ -0,0 +1,466 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppImpl.h + * @brief This is the header file for the _AppImpl class. + */ + +#ifndef _FAPP_INTERNAL_APP_IMPL_H_ +#define _FAPP_INTERNAL_APP_IMPL_H_ + +#include + +#include +#include +#include + +#include "FApp_Types.h" +#include "FApp_AppUserEvent.h" +#include "FApp_IAppUserEventListener.h" + +namespace Tizen { namespace Base { namespace Runtime +{ +class IEventListener; +}}} + +namespace Tizen { namespace App { namespace Package +{ +class PackageInfo; +}}} + +namespace Tizen { namespace App +{ + +class IAppCheckpointEventListener; +class ISqlDataControlProviderEventListener; +class IMapDataControlProviderEventListener; +class IAppControlProviderEventListener; +class IAppLaunchConditionEventListener; +class _AppArg; +class _IAppImpl; + +/** + * @class _AppImpl + * @brief This class is the Impl class of a App class. + * @since 2.1 + * + * This class is the Impl class of a App class. + */ +class _OSP_EXPORT_ _AppImpl + : public Tizen::Base::Object + , public _IAppUserEventListener + , virtual public Tizen::Base::Runtime::IEventListener +{ +public: + typedef result (_AppImpl::*AppRequestHandlerType)(service_s*, int, _AppHandler); + + /** + * Initializes this instance of _AppImpl with the specified arguments + * + * @since 2.1 + * @return An error code + * @param[in] pArgs A pointer to the list that contains the String instances of launch arguments + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance is in an invalid state. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + result Construct(const Tizen::Base::Collection::IList* pArgs); + + /** + * Executes an application implemented by inheriting App class. + * This method must be called from the UiApp or ServiceApp. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INIT_FAILED The initialization failure during OnAppInitializing(). + * @exception E_SYSTEM A system error has occurred. + */ + result Execute(_IAppImpl* pIAppImpl); + + /** + * Returns the _AppImpl's instance pointer. + * + * @since 2.1 + * @return A pointer to the %_AppImpl instance, @n + * else @c null if it fails + */ + static _AppImpl* GetInstance(); + + /** + * Returns the App's instance pointer. + * + * @since 2.1 + * @return A pointer to the %App instance, @n + * else @c null if it fails + */ + App* GetAppInstance(); + + /** + * Returns the status of the termination request + * + * @since 2.1 + * @return @c true if the termination is requested, @n + * else @c false + */ + static bool IsTerminationRequested(void); + + /** + * Called when the application is started + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static bool OnCreate(void* user_data); + + /** + * Called when other application send the launch request to the application + * + * @since 2.1 + * @param[in] service The handle to the service + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static void OnService(service_s* service, void* user_data); + + /** + * Called when the application is completely obscured by another application and becomes invisible + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static void OnPause(void* user_data); + + /** + * Called when the application becomes visible + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static void OnResume(void* user_data); + + /** + * Called once after the main loop of application exits + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static void OnTerminate(void* user_data); + + /** + * Called when an orintation event occurs. + * + * @since 2.1 + * @param[in] orientation The information about the orientation event + */ + static void OnDeviceOrientationChanged(app_device_orientation_e orientation, void* user_data); + + /** + * Called when the system memory is running low + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static void OnLowMemory(void* user_data); + + /** + * Called when the battery power is running low + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static void OnLowBattery(void* user_data); + + /** + * Called when language setting changes + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static void OnLanguageChanged(void* user_data); + + /** + * Called when region format setting changes + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + static void OnRegionFormatChanged(void* user_data); + + /** + * Set Listener + * + * @since 2.1 + * @return An error code + * @param[in] appEvent _AppEvent event type + * @param[in] pListener Listener to set + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance is in an invalid state. + */ + result SetListener(_AppEvent appEvent, Tizen::Base::Runtime::IEventListener* pListener); + + result SetSqlDataControlProviderEventListener(ISqlDataControlProviderEventListener* pListener); + + result SetMapDataControlProviderEventListener(IMapDataControlProviderEventListener* pListener); + + result SetAppControlProviderEventListener(IAppControlProviderEventListener* pListener); + + result SetAppControlProviderInternalEventListener(IAppControlProviderEventListener* pListener); + + result SetAppLaunchConditionEventListener(IAppLaunchConditionEventListener* pListener); + + /** + * Called when the application's initialization is finished. @n + * After this method succeeds, the application's state changes to Tizen::App::AppState::RUNNING. + * If the method fails, the application's state changes to Tizen::App::AppState::TERMINATING and call OnAppTerminating() subsequently. + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + bool OnAppInitialized(void); + + /** + * Called when a checkpoint event occurs + * + * @since 2.1 + */ + void OnAppCheckpoint(void); + + /** + * Registers app request + * + * @since 2.1 + * @return An error code + * @param[in] service service handle + * @param[out] req request number + * @param[out] reason launch reason + * @exception E_SUCCESS The method is successful. + */ + result RegisterAppRequest(service_s* service, int& req, _AppHandler& reason); + + /** + * Gets the window handle if exists. + * + * @since 2.1 + */ + long GetWindowHandle(void) const; + + + void OnBatteryLevelChanged(Tizen::System::BatteryLevel batteryLevel); + + static void OnPowerOffNotiReceived(void* pData); + +private: + /** + * This is the default constructor for this class. + * + * @since 2.1 + */ + _AppImpl(void); + + /** + * This is the constructor for this class. + * + * @since 2.1 + */ + _AppImpl(App* pApp); + + /** + * This is the copy constructor for the this class. + */ + _AppImpl(const _AppImpl& value); + + /** + * This is the assignment operator for this class. + */ + _AppImpl& operator =(const _AppImpl& source); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_AppImpl(void); + + /** + * Gets the list of the launch arguments. @n + * + * @since 2.1 + * @return A pointer to the list that contains the String instances of launch arguments + */ + Tizen::Base::Collection::IList* GetAppArgumentListN(void) const; + + /** + * Terminates the application while it is running. @n + * The OnAppTerminating() method is called after this method is executed successfully. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE This instance is in an invalid state. + */ + result Terminate(void); + + /** + * Calles the application's initialization routine. @n + * After this method succeeds, the application's state changes to Tizen::App::AppState::RUNNING. + * If the method fails, the application's state changes to Tizen::App::AppState::TERMINATING and call OnAppTerminating() subsequently. + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + bool OnAppInitializing(void); + + /** + * Called when the application is requested to terminate. @n + * Return @c false if you don't want your application to terminate. @n + * If the method returns @c true, the application's state changes to Tizen::App::AppState::TERMINATING and call OnAppTerminating() subsequently. + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + bool OnAppWillTerminate(void); + + /** + * Sends the user event to the application itself and not to other application. + * + * @since 2.1 + * @return An error code + * @param[in] requestId The user defined event ID + * @param[in] pArgs A pointer to an argument list of type String + * @exception E_SUCCESS The method is successful. + */ + result SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs); + + /** + * Called asynchronously when the user event is sent by the SendUserEvent() method. @n + * The request ID and argument format for the user event can be defined as per the requirement. + * + * @since 2.1 + * @param[in] requestId The user defined event ID + * @param[in] pArgs A pointer to an argument list of type String + */ + virtual void OnUserEventReceivedN(RequestId requestId, Tizen::Base::Collection::IList* pArgs); + + /** + * Called asynchronously when AppControl provider event is received. + * + * @since 2.1 + */ + void OnAppControlRequestReceived(const _AppArg& arg, RequestId reqId); + + /** + * Called asynchronously when DataControl provider event is received. + * + * @since 2.1 + * @param[in] arg The launch argument + */ + void OnDataControlRequestReceived(const _AppArg& arg, RequestId reqId); + + /** + * Called asynchronously when conditional app launch event is received. + * + * @since 2.1 + */ + void OnConditionRequestReceived(const _AppArg& arg, RequestId reqId); + + /** + * Handles AppControl/DataControl request + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is succesful. + */ + result HandleAppRequest(service_s* service, int req, _AppHandler reason); + + /** + * Handles legacy UserEvent request + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is succesful. + */ + result HandleLegacyAppRequest(service_s* service, int req, _AppHandler reason); + + /** + * Dummy implementation for app event request + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + */ + result HandleDummyAppRequest(service_s* service, int req, _AppHandler reason); + + /** + * Set legacy app service handler + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + */ + result SetLegacyRequestHandler(void); + + static bool ConfirmAppService(void); + +private: + static _AppImpl* __pAppImpl; + + _AppUserEvent __appUserEvent; + + IAppCheckpointEventListener* __pCheckpointEventListener; + + ISqlDataControlProviderEventListener* __pSqlDataControlProviderEventListener; + + IMapDataControlProviderEventListener* __pMapDataControlProviderEventListener; + + IAppControlProviderEventListener* __pAppControlProviderEventListener; + IAppControlProviderEventListener* __pAppControlProviderInternalEventListener; + + IAppLaunchConditionEventListener* __pAppLaunchConditionEventListener; + + App* __pApp; + + _IAppImpl* __pIAppImpl; + + AppRequestHandlerType __pRequestHandler; + + AppRequestHandlerType __pLegacyRequestHandler; + + static bool __isTerminationRequested; + + friend class App; +}; // _AppImpl + +} } //Tizen::App + +#endif // _FAPP_INTERNAL_APP_IMPL_H_ diff --git a/src/app/inc/FApp_AppInfo.h b/src/app/inc/FApp_AppInfo.h new file mode 100644 index 0000000..8efffdc --- /dev/null +++ b/src/app/inc/FApp_AppInfo.h @@ -0,0 +1,262 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppInfo.h + * @brief This is the header file of the _AppInfo class. + */ + +#ifndef _FAPP_INTERNAL_APP_INFO_H_ +#define _FAPP_INTERNAL_APP_INFO_H_ + +#include +#include +#include + +#include + +#include "FApp_Types.h" + +namespace Tizen { namespace Base { class String; } } + +namespace Tizen { namespace App +{ + +/** + * @class _AppInfo + */ +class _OSP_EXPORT_ _AppInfo +{ +public: + /** + * Retrieves class instance. + * + * @return A pointer to the %_AppInfo instance, @n + * else @c null if it fails + */ + _OSP_LOCAL_ static _AppInfo* GetAppInfo(void); + + /** + * Gets the Api version of current application. + * + * @return The Api version + */ + static Tizen::Base::_ApiVersion GetApiVersion(void); + + /** + * Checkes whether the compatibility mode is on or not. + * + * @return @true if the compatibility mode is on else false + */ + static bool IsOspCompat(void); + + /** + * Sets the Api version of current application. + * + * @return An error code + * @param[in] apiVersion Api version + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + static result SetApiVersion(Tizen::Base::_ApiVersion apiVersion); + + /** + * Gets the current process Id. + * + * @return The process Id + */ + static int GetProcessId(void); + + /** + * Gets the directory file descriptor of application's root directory where the application is installed. + * + * @return The file descriptor of the application's root directory + * @remarks This file descriptor is read only. + */ + static int GetAppRootDirFd(void); + + /** + * Gets the application's Id. + * + * @return The application Id + */ + static const AppId& GetAppId(void); + + /** + * Gets the application's Id. + * + * @return The application Id + */ + static const AppId& GetApplicationId(void); + + /** + * Gets the application's Id. + * + * @return The application Id + */ + static const AppId& GetPackageId(void); + + /** + * Gets the application executable name. + * + */ + static const Tizen::Base::String& GetAppExecutableName(void); + + /** + * Checkes whether the application is submode or not. + * + * @return @true if the compatibility mode is on else false + */ + static bool IsSubMode(void); + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // Gets the path of application's root directory where the application is installed. + // + // @return The path of the application's root directory + // + static Tizen::Base::String GetAppRootPath(void); + + /** + * Gets the application's name. + * + * @return The application name + */ + static Tizen::Base::String GetAppName(void); + + /** + * Gets the application's version. + * + * @return The application version + */ + static Tizen::Base::String GetAppVersion(void); + + /** + * Gets the current state of the application. + * + * @return The current state of the application + */ + static AppState GetAppState(void); + + /** + * Sets the current state of the application. + * + * @param appState The current state of the application + */ + static void SetAppState(AppState appState); + + /** + * Gets the current type of the application. + * + * @return The current type of the application + */ + static _AppType GetAppType(void); + + /** + * Sets the current type of the application. + * + * @param appType The current type of the application + */ + static void SetAppType(_AppType appType); + + /** + * Gets the argument count. + * + * @return argc + */ + _OSP_LOCAL_ static int GetArgc(void); + + /** + * Gets the argument. + * + * @return argv + */ + _OSP_LOCAL_ static char** GetArgv(void); + + /** + * Gets the application handler type. + * + * @return appHandlerType + */ + _OSP_LOCAL_ static int GetAppHandlerType(void); + + /** + * Sets the application handler type. + * + * @param appHandlerType + */ + _OSP_LOCAL_ static void SetAppHandlerType(int appHandlerType); + + /** + * Gets the parent window handle. + * + * @return window handle + */ + static unsigned int GetParentWindowHandle(void); + + /** + * Sets the parent window handle. + */ + static void SetParentWindowHandle(unsigned int handle); + + /** + * Update package info + */ + static void UpdatePackageInfo(bool update); + + _OSP_LOCAL_ result Construct(const char* appId, const char* exeName, int argc, char* pArgv[]); + + _OSP_LOCAL_ result Construct(const char* appId, const char* appRoot, _AppType type = _APP_TYPE_UI_APP); + +private: + _OSP_LOCAL_ _AppInfo(void); + + _OSP_LOCAL_ ~_AppInfo(void); + + _AppInfo(const _AppInfo& value); + + _AppInfo& operator =(const _AppInfo& source); + + _OSP_LOCAL_ static Tizen::Base::_ApiVersion GetApiVersionFromStr(const char* pVer); + + _OSP_LOCAL_ result UpdateAppInfoFromPackageInfo(const PackageId& packageId); + +private: + AppState __appState; + _AppType __appType; + int __appRootDirFd; + int __appHandlerType; + int __parentWindowHandle; + Tizen::Base::_ApiVersion __apiVersion; + AppId __appId; + PackageId __packageId; + Tizen::Base::String __appExecutableName; + Tizen::Base::String __appRootPath; + Tizen::Base::String* __pAppName; + Tizen::Base::String* __pAppVersion; + int __argc; + char** __pArgv; + bool __isPackageInfoInitialized; + bool __isOspCompat; + bool __isSubMode; +}; // _AppInfo + +}} // Tizen::App + +#endif //_FAPP_INTERNAL_APP_INFO_H_ diff --git a/src/app/inc/FApp_AppLaunchCondition.h b/src/app/inc/FApp_AppLaunchCondition.h new file mode 100644 index 0000000..724dfd2 --- /dev/null +++ b/src/app/inc/FApp_AppLaunchCondition.h @@ -0,0 +1,148 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IConditionalOperation.h + * @brief This is the header file of the _AppLaunchCondition class. + * + * This header file contains the declarations of the _AppLaunchCondition class + */ + +#ifndef _FAPP_INTERNAL_CONDITIONAL_OPERATION_H_ +#define _FAPP_INTERNAL_CONDITIONAL_OPERATION_H_ + + +#include +#include +#include +#include +#include +#include + +#include + +namespace Tizen { namespace App { + + +/** + * @class _AppLaunchCondition + * @brief This class abstracts information for conditional app launch + * @since 2.1 + */ +class _OSP_EXPORT_ _AppLaunchCondition + : public Tizen::Base::Object +{ +public: + /** + * Gets the application ID of the target application. + * + * @return application ID + * @since 2.1 + */ + AppId GetAppId(void) const; + + /** + * Gets registered condition string. + * @return condition string + * + * @since 2.1 + */ + Tizen::Base::String GetConditionString(void) const; + + /** + * Sets userdata + * + * @param[in] pUserData The pointer to userdata of this instance + * Userdata can be context or handle. (ex, Alarm instance, Timer handle, etc) + * @since 2.1 + * @see GetUserData + */ + result SetUserData(const Object* pUserData); + + /** + * Gets userdata + * + * @return The pointer to userdata of this instance. + * You can cancel or delete plugin dependent information using this pointer in overridden function _AppLaunchConditionBase::Unregister. + * @since 2.1 + * @see SetUserData + */ + Object* GetUserData(void) const; + + +private: + /** + * This is the constructor for this class. + * + * @since 2.1 + */ + _AppLaunchCondition(void); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_AppLaunchCondition(void); + + /** + * Initializes this instance of _AppLaunchCondition with the specified parameter + * + * @since 2.1 + * @return An error code + * @param[in] appId The application's ID to be executed conditionally + * @param[in] condition The launch condition for the application + * @param[in] pArguments A pointer to the list of string arguments that has a maximum size of @c 1024 bytes @n + * The default value is @c null. + * @param[in] option The launch option (currently only AppManager::LAUNCH_OPTION_DEFAULT is available) + * @param[in] pRegSectionName The section name in the registry. + This value is used to find a registry section by condition string and remove it easily. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + + * @see Tizen::App::AppManager::RegisterAppLaunch() + */ + result Construct(const AppId& appId, const Tizen::Base::String& executableName, const Tizen::Base::String& conditionString, const Base::Collection::IList* pArgs, AppManager::LaunchOption option , const Tizen::Base::String* pRegSectionName = null); + +private: + _AppLaunchCondition(const _AppLaunchCondition& operation); + _AppLaunchCondition& operator =(const _AppLaunchCondition& operation); + + Tizen::Base::String GetExecutableName(void) const; + +private: + // app launch info + AppId __appId; + Tizen::Base::String __executableName; + Tizen::Base::Collection::ArrayList *__pArguments; + AppManager::LaunchOption __option; + + // condition info + Tizen::Base::String __conditionString; + const Object* __pUserData;///<< pointer to plugin's context or handle. (ex, Alarm instance, Timer handle, etc). You can cancel or delete registered operation using this value, when _AppLaunchConditionBase::Unregister implemented function is invoked. + + result CopyArgumentsDeeply(const Tizen::Base::Collection::IList *pArgs); + Tizen::Base::String __regSectionName; + + friend class _ConditionHandler; + friend class _ConditionManagerService; +}; //_AppLaunchCondition + + +}} + +#endif // _FAPP_INTERNAL_CONDITIONAL_OPERATION_H_ diff --git a/src/app/inc/FApp_AppLaunchConditionHandlerBase.h b/src/app/inc/FApp_AppLaunchConditionHandlerBase.h new file mode 100644 index 0000000..89795aa --- /dev/null +++ b/src/app/inc/FApp_AppLaunchConditionHandlerBase.h @@ -0,0 +1,133 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppLaunchConditionHandlerBase.h + * @brief This is the header file of the _AppLaunchConditionHandlerBase class. + * + * This header file contains the declarations of the _AppLaunchConditionHandlerBase class. + */ +#ifndef _FAPP_INTERNAL_APP_LAUNCH_CONDITION_HANDLER_BASE_H_ +#define _FAPP_INTERNAL_APP_LAUNCH_CONDITION_HANDLER_BASE_H_ + +#include +#include + +#include +#include "FApp_IAppLaunchConditionEventListener.h" +#include "FApp_AppLaunchCondition.h" + +namespace Tizen { namespace App { + + +/** + * @class _AppLaunchConditionHandlerBase + * @brief This class is the abstract base class of all conditional app launch handlers(plugin). + * @since 2.1 + * + * All conditional app launch handlers(plugin) should inherit this abstract class. + * and all plugins must provide both a creation and a destruction function like following. + * + * @code + * extern "C" _AppLaunchConditionHandlerBase* CreatePlugin() + * { + * return new (std::nothrow) _AlarmConditionHandler;// create and return your own class instance. + * } + * + * extern "C" void DestroyPlugin(_AppLaunchConditionHandlerBase* p) + * { + * delete p; + * } + * @endcode + */ +class _OSP_EXPORT_ _AppLaunchConditionHandlerBase + : public Tizen::Base::Object +{ +public: + /** + * This is the constructor for this class. + * + * @since 2.1 + */ + _AppLaunchConditionHandlerBase(void); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_AppLaunchConditionHandlerBase(void); + + /** + * Sets event listener instance. @n + * The listener can listen to OnAppLaunchConditionMet event. + * + * @since 2.1 + * @param[in] The operation registered conditional operation with current condition. + * @remark _ConditionManagerService uses this function to sets itself as listener. + */ + result SetEventListener(_IAppLaunchConditionEventListener& eventListener); + + /** + * Register app launch condition for the plug-in. + * + * @since 2.1 + * @return An error code + * @param[in] operation The conditional operation to register + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_FORMAT The specified condition format is invalid. + * @exception E_INVALID_CONDITION The specified condition format is valid but the condition has at least one or more invalid values. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * @remark Plugin should implement this register condition code + * _ConditionManagerService calls this method when RegisterAppLaunch method invoked. + * @see Unregister() + */ + virtual result Register( _AppLaunchCondition& condition) = 0;//, const Tizen::Base::Object*& pHandle) = 0; + + /** + * Unregister app launch condition for the plug-in. + * + * @since 2.1 + * @param[in] operation The conditional operation to register + * @remark Plugin should implement this unregister condition code + * _ConditionManagerService calls this method when UnregisterAppLaunch method invoked. + * @see Register() + */ + virtual result Unregister( _AppLaunchCondition& condition) = 0;//, const Tizen::Base::Object* pHandle) = 0; + + +protected: + /** + * Fires the OnAppLaunchConditionMet event. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The event handler isn't initialized yet. + * @param[in] operation The conditional operation registered. + * @see _IAppLaunchConditionEventListener::OnAppLaunchConditionMet + */ + result Fire(const _AppLaunchCondition& condition); + +private: + _IAppLaunchConditionEventListener* __pEventListener; +}; //_AppLaunchConditionHandlerBase + +}}//Tizen::App + +#endif // _FAPP_INTERNAL_APP_LAUNCH_CONDITION_HANDLER_BASE_H_ diff --git a/src/app/inc/FApp_AppManagerEvent.h b/src/app/inc/FApp_AppManagerEvent.h new file mode 100644 index 0000000..452687a --- /dev/null +++ b/src/app/inc/FApp_AppManagerEvent.h @@ -0,0 +1,60 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerEvent.h + * @brief This is the header file of _AppManagerEvent + */ + +#ifndef _FAPP_INTERNAL_APP_MANAGER_EVENT_H_ +#define _FAPP_INTERNAL_APP_MANAGER_EVENT_H_ + +#include +#include + +namespace Tizen { namespace App +{ + +/** +* @class _AppManagerEvent +* @brief This class contains application manager event +* @since 2.1 +*/ +class _AppManagerEvent + : public Tizen::Base::Runtime::_Event +{ +public: + enum _Type + { + _APP_MANAGER_EVENT_INVALID = 0, + _APP_MANAGER_EVENT_LAUNCHED, + _APP_MANAGER_EVENT_TERMINATED, + + // for range check. + _APP_MANAGER_EVENT_MAX + }; + + result Construct(void); + +protected: + void FireImpl(Tizen::Base::Runtime::IEventListener& lstener, const Tizen::Base::Runtime::IEventArg& arg); + +}; //_AppManagerEvent + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_MANAGER_EVENT_H_ diff --git a/src/app/inc/FApp_AppManagerEventArg.h b/src/app/inc/FApp_AppManagerEventArg.h new file mode 100644 index 0000000..0d8a7e8 --- /dev/null +++ b/src/app/inc/FApp_AppManagerEventArg.h @@ -0,0 +1,67 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerEventArg.h + * @brief This is the header file of _AppManagerEventArg class. + */ + +#ifndef _FAPP_INTERNAL_APP_MANAGER_EVENT_ARG_H_ +#define _FAPP_INTERNAL_APP_MANAGER_EVENT_ARG_H_ + +#include +#include +#include +#include + +#include "FApp_AppManagerEvent.h" + +namespace Tizen { namespace App +{ + +/** + * @class _AppManagerEventArg + * @brief + * @since 2.1 + * + */ +class _OSP_EXPORT_ _AppManagerEventArg + : public Tizen::Base::Object + , public Tizen::Base::Runtime::IEventArg +{ +public: + _AppManagerEventArg(void); + _AppManagerEventArg(const _AppManagerEventArg& value); + _AppManagerEventArg(const AppId& appId, _AppType appType, _AppManagerEvent::_Type eventType); + virtual ~_AppManagerEventArg(void); + + const AppId GetAppId(void) const; + _AppType GetAppType(void) const; + _AppManagerEvent::_Type GetEventType(void) const; + + _AppManagerEventArg& operator =(const _AppManagerEventArg& source); + +private: + AppId __appId; + _AppType __appType; + _AppManagerEvent::_Type __eventType; + +}; //_AppManagerEventArg + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_MANAGER_EVENT_ARG_H_ diff --git a/src/app/inc/FApp_AppManagerEventParamTraits.h b/src/app/inc/FApp_AppManagerEventParamTraits.h new file mode 100644 index 0000000..34add31 --- /dev/null +++ b/src/app/inc/FApp_AppManagerEventParamTraits.h @@ -0,0 +1,78 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IpcCommonParamTraits.h + * @brief This is the header file for common param traits. + */ + +#ifndef _FAPP_INTERNAL_APPMANAGER_EVENT_ARG_PARAM_TRAITS_H_ +#define _FAPP_INTERNAL_APPMANAGER_EVENT_ARG_PARAM_TRAITS_H_ + +#include "FBaseString.h" +#include "FBaseColIList.h" +#include "FBaseColArrayList.h" +#include "FIo_IpcCommonDataTypes.h" + +#include "base/tuple.h" +#include "ipc/ipc_param_traits.h" + +#include "FApp_AppManagerEventArg.h" + + +//namespace Tizen { namespace App { class _AppManagerEventArg; } } + +namespace IPC +{ +template <> +struct ParamTraits +{ + typedef Tizen::App::_AppManagerEventArg param_type; + + static void Write(Message* m, const param_type& p) + { + WriteParam(m, p.GetAppId()); + m->WriteInt(p.GetAppType()); + m->WriteInt(p.GetEventType()); + } + + static bool Read(const Message* m, void** iter, param_type* r) + { + Tizen::App::AppId appId; + int appType = Tizen::App::_APP_TYPE_UI_APP; + int eventType = Tizen::App::_AppManagerEvent::_APP_MANAGER_EVENT_INVALID; + + if (!ReadParam(m, iter, &appId)) + { + return false; + } + m->ReadInt(iter, &appType); + m->ReadInt(iter, &eventType); + + Tizen::App::_AppManagerEventArg arg(appId, static_cast(appType), static_cast(eventType)); + *r = arg; + + return true; + } + + static void Log(const param_type& p, std::string* l) + { + } +}; +} + +#endif //_FAPP_INTERNAL_APPMANAGER_EVENT_ARG_PARAM_TRAITS_H_ diff --git a/src/app/inc/FApp_AppManagerImpl.h b/src/app/inc/FApp_AppManagerImpl.h new file mode 100644 index 0000000..3e12526 --- /dev/null +++ b/src/app/inc/FApp_AppManagerImpl.h @@ -0,0 +1,387 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerImpl.h + * @brief This is the header file for the _AppManagerImpl class. + */ + +#ifndef _FAPP_INTERNAL_APP_MANAGER_IMPL_H_ +#define _FAPP_INTERNAL_APP_MANAGER_IMPL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FApp_Types.h" +#include "FApp_AppManagerEvent.h" +#include "FApp_IAppManagerServiceEventListener.h" + +namespace Tizen { namespace Base +{ +class String; +namespace Runtime +{ +class _LibraryImpl; +} +}} +namespace Tizen { namespace Io +{ +class DataControlResultSet; +class _DataControlResultSetImpl; +}} + +namespace Tizen { namespace App +{ + +class _IAppManager; +class _ConditionManagerProxy; +class _IAppManagerEventListener; +class _AppManagerEventArg; + +class _OSP_EXPORT_ _AppManagerImpl + : public Tizen::Base::Object + , public _IAppManagerServiceEventListener + , virtual public Tizen::Base::Runtime::IEventListener +{ +public: + static _AppManagerImpl* GetInstance(void); + + /** + * Finds the application control that the caller wants to start. @n + * It resolves the matched application control with the delivered application control provider ID and operation ID. + * + * @return A pointer to the newly created AppControl instance if a matched %AppControl is found, @n + * else @c null + * @param[in] providerId The provider ID + * @param[in] operationId The operation ID + */ + static AppControl* FindAppControlN(const AppId& providerId, const Tizen::Base::String& operationId); + + /** + * Returns a list of AppControl instances that match the specified operation ID, category, + * data type, and URI scheme. + * + * @return A pointer to the list of the %AppControl instances that matches the specified operation ID, category, URI scheme, and data type, @n + * else @c null if it fails + * @param[in] pOperationId The operation ID + * @param[in] pCategory The application control category + * @param[in] pDataType The MIME type (RFC 2046) or file extension @n + * The '.' prefix should be used when specifying the file extension. + * @param[in] pUriScheme The URI scheme + * + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG At least one of the The specified @c pOperationId, @c pCategory, @c pDataType, or @c pUriScheme should not be @c null. + * @exception E_INVALID_FORMAT The specified URI scheme is invalid (RFC 2396). + * @exception E_UNSUPPORTED_FORMAT The specified file extension for @c pDataType is not supported. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + static Tizen::Base::Collection::IList* FindAppControlsN(const Tizen::Base::String* pOperationId, const Tizen::Base::String* pCategory, const Tizen::Base::String* pDataType, const Tizen::Base::String* pUriScheme); + + /** + * Starts the application control if there is only one application control that matches the specified URI, operation ID, and data type. @n + * If there are more than one application controls, the one that the user selects is started. + * + * @return An error code + * @param[in] uri The URI that has a maximum size of @c 1024 bytes + * @param[in] pOperationId The operation ID + * @param[in] pDataType The MIME type (RFC 2046) or file extension @n + * The '.' prefix should be used for the @c dataType when specifying the file extension. + * @param[in] pListener A listener that gets notified when the resolved application control has started + * @exception E_SUCCESS The method is successful. + * @exception E_MAX_EXCEEDED The size of @c uri has exceeded the maximum limit. + * @exception E_UNSUPPORTED_FORMAT The specified file extension for @c pDataType is not supported. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_STATE The system pop-up cannot be launched. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_IN_PROGRESS The target application control is in progress. + * @exception E_SYSTEM A system error has occurred. + * @remarks The E_INVALID_STATE exception is thrown when the default form is not accessible. + */ + static result StartAppControl(const Tizen::Base::String& uri, const Tizen::Base::String* pOperationId, const Tizen::Base::String* pDataType, IAppControlListener* pListener); + + /** + * Starts the application control if there is only one application control that matches the specified operation ID, category, URI scheme, and data type. @n + * If there are more than one application controls, the one that the user selects is started. + * + * @return An error code + * @param[in] pOperationId The operation ID + * @param[in] pCategory The application control category + * @param[in] pDataType The MIME type (RFC 2046) or file extension @n + * The '.' prefix should be used when specifying the file extension. + * @param[in] pUriScheme The URI scheme + * @param[in] pDataList The data list to be delivered to the resolved application control @n + * It has a maximum size of @c 1024 bytes. + * @param[in] pListener A listener that gets notified when the resolved application control has started + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG At least one of the specified @c pOperationId, @c pCategory, @c pDataType, or @c pUriScheme should not be @c null. + * @exception E_MAX_EXCEEDED The size of @c pDataList has exceeded the maximum limit. + * @exception E_UNSUPPORTED_FORMAT The specified file extension for @c pDataType is not supported. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_STATE The system pop-up cannot be launched. + * @exception E_OBJ_NOT_FOUND The application control is not found. + * @exception E_IN_PROGRESS The target application control is in progress. + * @exception E_SYSTEM A system error has occurred. + * @remarks E_INVALID_STATE occurs when the default form is not accessible. + */ + static result StartAppControl(const Tizen::Base::String* pOperationId, const Tizen::Base::String* pCategory, const Tizen::Base::String* pDataType, const Tizen::Base::String* pUriScheme, const Tizen::Base::Collection::IList* pDataList, IAppControlListener* pListener); + + static SqlDataControl* GetSqlDataControlN(const Tizen::Base::String& providerId); + + static MapDataControl* GetMapDataControlN(const Tizen::Base::String& providerId); + + static result GetAppRootPath(const AppId& appId, Tizen::Base::String& appRootPath); + + /** + * Launches an application. @n + * The launch arguments are given as input parameters for App::OnUserEventReceivedN() or can be obtained by + * invoking Application::GetAppArgumentListN(), especially within Application::OnAppInitializing(). + * + * @return An error code + * @param[in] appId The application's ID to be executed + * @param[in] pArguments A pointer to the list of string arguments that has a maximum size of @c 1024 bytes @n + * The default value is @c null. + * @param[in] option The launch option (currently only AppManager::LAUNCH_OPTION_DEFAULT is available) + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OBJ_NOT_FOUND The target application is not installed. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_MAX_EXCEEDED The size of @c appId or @c pArguments has exceeded the maximum limit. + */ + result LaunchApplication(const AppId& appId, const Tizen::Base::Collection::IList* pArguments, AppManager::LaunchOption option); + + /** + * Launches an application. @n + * The launch arguments are given as input parameters for App::OnUserEventReceivedN() or can be obtained by + * invoking Application::GetAppArgumentListN(), especially within Application::OnAppInitializing(). + * + * @return An error code + * @param[in] appId The application's ID to be executed + * @param[in] option The launch option (currently only AppManager::LAUNCH_OPTION_DEFAULT is available) + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_APP_NOT_INSTALLED The target application is not installed. + */ + result LaunchApplication(const AppId& appId, AppManager::LaunchOption option); + + /** + * Terminates an application. + * + * @return An error code + * @param[in] appId The application's ID to be executed + * @param[in] pExecutableName The executable name + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OBJ_NOT_FOUND The application is not installed or not running. + */ + result TerminateApplication(const AppId& appId, const Tizen::Base::String* pExecutableName); + + /** + * Terminates all the applications in a package. + * + * @return An error code + * @param[in] packageId The package ID + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OBJ_NOT_FOUND The application is not installed or not running. + */ + result TerminateApplications(const PackageId& appId); + + /** + * Checks whether an application is running. + * + * @return @c true if the application is running, @n + * else @c false + * @param[in] appId The installed application ID + * @param[in] pExecutableName The executable name + */ + bool IsRunning(const AppId& appId, const Tizen::Base::String* pExecutableName) const; + + /** + * Returns a list of running applications at the time of invocation. + * + * @return A pointer to the running state application list (AppId), @n + * else @c null if an error occurs + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_STATE This instance is in an invalid state. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IList* GetRunningAppListN(void) const; + + /** + * Registers the specified application with a specific condition and launches it if the condition is met. @n + * If the requested application is already running, the application is notified via Application::OnUserEventReceivedN(). + * The launch arguments are specified as input parameters for Application::OnUserEventReceivedN() or can be obtained by + * invoking Application::GetAppArgumentListN(), especially within Application::OnAppInitializing(). + * + * @return An error code + * @param[in] appId The ID of the application registered for launch + * @param[in] condition The launch condition for the application @n + * The condition has L"Key='value'" format and is case-sensitive. @n + * For more information on the condition formats, see Registering a Launch Condition. + * @param[in] pArguments A list of string arguments that has a maximum size of @c 1024 bytes @n + * The parameter can also contain @c null. + * @param[in] option The launch option (currently only AppManager::LAUNCH_OPTION_DEFAULT is available) + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_ARG The launch condition is empty or too long (Maximum 400 bytes). + * @exception E_INVALID_FORMAT The specified condition format is invalid. + * @exception E_INVALID_CONDITION The specified condition format is valid but the condition has at least one or more invalid values. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_MAX_EXCEEDED The size of @c pArguments has exceeded the maximum limit. + * @exception E_SYSTEM A system error has occurred. + */ + result RegisterAppLaunch(const AppId& appId, const Tizen::Base::String& executableName, const Tizen::Base::String& condition, const Tizen::Base::Collection::IList* pArguments, AppManager::LaunchOption option); + + /** + * Unregisters the launch condition. + * + * @return An error code + * @param[in] appId The application ID + * @param[in] pCondition The launch condition to unregister @n + * If the parameter contains @c null, all the conditions are unregistered. + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_OBJ_NOT_FOUND The specified launch condition is not found. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result UnregisterAppLaunch(const AppId& appId, const Tizen::Base::String& executableName, const Tizen::Base::String* pCondition); + + /** + * Checks whether a previously registered launch condition is present for the specified application. + * + * @return @c true if a condition is already registered to the specified application with the specified condition, @n + * else @c false + * @param[in] appId The application ID + * @param[in] pCondition The launch condition to register for the specified @c appId @n + * If the parameter contains @c null, the method checks for any registered launch condition for the specified @c appId. + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + bool IsAppLaunchRegistered(const AppId& appId, const Tizen::Base::String& executableName, const Tizen::Base::String* pCondition = null); + + /** + * Sets a checkpoint event listener. @n + * The listener gets notified when a checkpoint event is fired. To unset the listener, pass a @c null value to the @c listener parameter. + * + * @return An error code + * @param[in] appEvent _AppEvent event type + * @param[in] pListener The listener to receive the checkpoint event + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_ALREADY_EXIST The listener is already set. + * @exception E_SYSTEM A system error has occurred. + * + */ + result SetEventListener(_AppEvent appEvent, Tizen::Base::Runtime::IEventListener* pListener); + + /** + * Adds a listener object. + * Added listener can listen to events when they are fired. + * + * @return An error code + * @param[in] listener Listener to add + * @exception E_SUCCESS This method was successful. + * @exception E_OBJ_ALREADY_EXIST The listener was already exist. + */ + result AddEventListener(_IAppManagerEventListener& listener); + + /** + * Adds a listener object. + * Added listener can listen to events when they are fired. + * + * @return An error code + * @param[in] listener Listener to add + * @exception E_SUCCESS This method was successful. + * @exception E_OBJ_ALREADY_EXIST The listener was already exist. + */ + result RemoveEventListener(_IAppManagerEventListener& listener); + + virtual result OnServiceEventReceived(const int clientId, const _AppManagerEventArg& arg); + + virtual result OnTerminateApplicationRequested(int clientId); + + static void SetAppManagerService(_IAppManager* pAppManager ); + + static result ExtractValues(AppId inAppId, AppId& outAppId, Tizen::Base::String& outExecutableName); + + _OSP_LOCAL_ Tizen::Base::Runtime::_LibraryImpl& GetUiLibraryImpl(void); + + static Tizen::Base::Runtime::_LibraryImpl& GetEcoreXLibraryImpl(void); + + static Tizen::Base::Runtime::_LibraryImpl& GetEcoreLibraryImpl(void); + + Tizen::Base::Runtime::_LibraryImpl& GetX11LibraryImpl(void); + + result AddActiveAppEventListener(IActiveAppEventListener& listener); + + result RemoveActiveAppEventListener(IActiveAppEventListener& listener); + + result GetActiveApp(AppId& appId); + + void FireActiveAppEvent(unsigned int xid, int pid, char* pAppName); + +private: + _OSP_LOCAL_ _AppManagerImpl(void); + + _OSP_LOCAL_ virtual ~_AppManagerImpl(void); + + _OSP_LOCAL_ result Construct(); + + _AppManagerImpl(const _AppManagerImpl& rhs); + + _AppManagerImpl& operator =(const _AppManagerImpl& rhs); + + _OSP_LOCAL_ _ConditionManagerProxy* GetConditionManagerProxy(void); + + unsigned int GetActiveWindow(void); + + int GetProcessId(unsigned int window); + +private: + _ConditionManagerProxy* __pConditionManager; + int __eventListenerCount; + Tizen::Base::Runtime::_LibraryImpl* __pUiLibrary; + Tizen::Base::Runtime::_LibraryImpl* __pX11Library; + static Tizen::Base::Runtime::_LibraryImpl* __pEcoreXLibrary; + static Tizen::Base::Runtime::_LibraryImpl* __pEcoreLibrary; + _AppManagerEvent __appManagerEvent; + Tizen::Base::Collection::LinkedListT __activeAppEventListenerList; + + friend class AppManager; + friend class _AppControlImpl; + friend class _SqlDataControlImpl; + friend class _MapDataControlImpl; + friend class _DataControlProviderManagerImpl; + friend class _AppControlProviderManagerImpl; + friend class _ActiveWindowEventListener; + friend class Tizen::Io::_DataControlResultSetImpl; +}; // _AppManagerImpl + +}} // Tizen::App + +#endif // _FAPP_INTERNAL_APP_MANAGER_IMPL_H_ diff --git a/src/app/inc/FApp_AppManagerIpcMessage.h b/src/app/inc/FApp_AppManagerIpcMessage.h new file mode 100644 index 0000000..b14817a --- /dev/null +++ b/src/app/inc/FApp_AppManagerIpcMessage.h @@ -0,0 +1,44 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerIpcMessage.h + * @brief This is the header file for the AppManagerService Ipc message types. + */ + +#include +#include +#include "FApp_Types.h" + +#include "ipc/ipc_message_macros.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FIo_IpcMessageStart.h" +#include "FApp_AppManagerEventParamTraits.h" + + +#define IPC_MESSAGE_START AppManagerServiceStart + +IPC_MESSAGE_CONTROL3(AppManager_LaunchApplication, Tizen::App::AppId, Tizen::Base::String, int) +IPC_SYNC_MESSAGE_CONTROL2_1(AppManager_TerminateApplication, Tizen::App::AppId, Tizen::Base::String, result) +IPC_SYNC_MESSAGE_CONTROL2_1(AppManager_IsRunning, Tizen::App::AppId, Tizen::Base::String, bool) +IPC_SYNC_MESSAGE_CONTROL0_2(AppManager_GetRunningAppList, Tizen::Base::Collection::ArrayList, result) +IPC_MESSAGE_CONTROL4(AppManager_RegisterApplication, Tizen::App::AppId, Tizen::Base::String, int, int) +IPC_MESSAGE_CONTROL1(AppManager_UnregisterApplication, int) +IPC_MESSAGE_CONTROL1(AppManager_OnEventReceived, Tizen::App::_AppManagerEventArg) +IPC_MESSAGE_CONTROL1(AppManager_AddEventListener, int) +IPC_MESSAGE_CONTROL1(AppManager_RemoveEventListener, int) +IPC_MESSAGE_CONTROL0(AppManager_OnTerminateApplicationRequested) diff --git a/src/app/inc/FApp_AppManagerProxy.h b/src/app/inc/FApp_AppManagerProxy.h new file mode 100644 index 0000000..72ffa22 --- /dev/null +++ b/src/app/inc/FApp_AppManagerProxy.h @@ -0,0 +1,97 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerProxy.h + * @brief This is the header file for the _AppManagerProxy class. + */ + +#ifndef _FAPP_INTERNAL_APP_MANAGER_PROXY_H_ +#define _FAPP_INTERNAL_APP_MANAGER_PROXY_H_ + +#include +#include +#include +#include +#include +#include "FApp_Types.h" +#include "FApp_IAppManager.h" +#include "FApp_AppManagerEvent.h" + +namespace Tizen { namespace Io { class _IpcClient; } } + +namespace Tizen { namespace App +{ + +class _IAppManagerEventListener; +class _IAppManagerServiceEventListener; +class _AppManagerEventArg; + +class _OSP_EXPORT_ _AppManagerProxy + : public _IAppManager + , public Tizen::Io::_IIpcClientEventListener + , public Tizen::Base::Object +{ +public: + virtual ~_AppManagerProxy(void); + + virtual result LaunchApplication(const AppId& appId, const Tizen::Base::String& executableName, int req); + + virtual result TerminateApplication(const AppId& appId, const Tizen::Base::String& executableName); + + virtual bool IsRunning(const AppId& appId, const Tizen::Base::String& executableName); + + virtual result GetRunningAppList(Tizen::Base::Collection::ArrayList* pList); + + // for platform + virtual result InitEventListener(_IAppManagerServiceEventListener* pListener); + + virtual result AddEventListener(int clientId );//, _IAppManagerServiceEventListener* pListener); + + virtual result RemoveEventListener(int clientId );//, _IAppManagerServiceEventListener* pListener); + + virtual result RegisterApplication(const AppId& appId, const Tizen::Base::String& executableName, _AppType appType, int pid); + + virtual result UnregisterApplication(int pid); + + static _IAppManager* GetService(void); + + static void SetService(_IAppManager* pAppManager); + +private: + _AppManagerProxy(void); + + _AppManagerProxy(const _AppManagerProxy& value); + + _AppManagerProxy& operator =(const _AppManagerProxy& source); + + result Construct(void); + + virtual void OnIpcResponseReceived(Tizen::Io::_IpcClient& client, const IPC::Message& message); + + bool OnEventReceived(const Tizen::App::_AppManagerEventArg& arg); + void OnTerminateApplicationRequested(void); + +private: + static _IAppManager* __pSelf; + Tizen::Io::_IpcClient* __pIpcClient; + static _IAppManagerServiceEventListener* __pServiceEventListener; +}; // _AppManagerProxy + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_MANAGER_PROXY_H_ diff --git a/src/app/inc/FApp_AppMessageImpl.h b/src/app/inc/FApp_AppMessageImpl.h new file mode 100644 index 0000000..7e94722 --- /dev/null +++ b/src/app/inc/FApp_AppMessageImpl.h @@ -0,0 +1,96 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppMessageImpl.h + * @brief This is the header file of the %_AppMessageImpl class. + * + * This header file contains the declarations of the %_AppMessageImpl class. + */ + +#ifndef _FAPP_INTERNAL_APP_MESSAGE_IMPL_H_ +#define _FAPP_INTERNAL_APP_MESSAGE_IMPL_H_ + +#include + +#include +#include + +namespace Tizen { namespace Base { namespace Collection { class IList; } } } + +namespace Tizen { namespace App +{ + +/** + * @class _AppMessageImpl + * @brief + * @since 2.1 + * + * + */ +class _OSP_EXPORT_ _AppMessageImpl +{ +public: + _AppMessageImpl(void); + + ~_AppMessageImpl(void); + + _AppMessageImpl(const _AppMessageImpl& rhs); + + _AppMessageImpl& operator=(const _AppMessageImpl& rhs); + + bundle* GetBundle(void) + { + return __pBundle; + } + + Tizen::Base::String GetValue(const wchar_t key[]) const; + + Tizen::Base::String GetValue(const Tizen::Base::String& key) const; + + result AddData(const Tizen::Base::String& key, const Tizen::Base::String& value); + + result AddData(const Tizen::Base::Collection::IList* pList); + + result AddData(const Tizen::Base::Collection::IMap* pMap); + + static result SetOperation(bundle* pBundle, const Tizen::Base::String& operation); + + static result SetUri(bundle* pBundle, const Tizen::Base::String& uri); + + static result SetMime(bundle* pBundle, const Tizen::Base::String& mime); + + static result SetCategory(bundle* pBundle, const Tizen::Base::String& category); + + static result AddData(bundle* pBundle, const Tizen::Base::String& key, const Tizen::Base::String& value); + + static result AddData(bundle* pBundle, const Tizen::Base::Collection::IList* pList); + + static result AddStringMap(bundle* pBundle, const Tizen::Base::Collection::IMap* pMap); + + static Tizen::Base::Collection::ArrayList* GetValueArray(bundle* pBundle, const char* pKey); + + static Tizen::Base::Collection::ArrayList* GetValueArray(bundle* pBundle, const Tizen::Base::String& key); + +private: + bundle* __pBundle; +}; + +} } // Tizen::App + +#endif //_FAPP_INTERNAL_APP_MESSAGE_IMPL_H_ + diff --git a/src/app/inc/FApp_AppUserEvent.h b/src/app/inc/FApp_AppUserEvent.h new file mode 100644 index 0000000..05cbb0f --- /dev/null +++ b/src/app/inc/FApp_AppUserEvent.h @@ -0,0 +1,68 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppUserEvent.h + * @brief This is the header file for the _AppUserEvent class. + * + * This file contains the declarations of _AppUserEvent. + */ + + +#ifndef _FAPP_INTERNAL_APP_USER_EVENT_H_ +#define _FAPP_INTERNAL_APP_USER_EVENT_H_ + +#include +#include +#include +#include + +#include + +#include "FApp_IAppUserEventListener.h" +#include "FApp_AppUserEventArg.h" + + +namespace Tizen { namespace App +{ + +class _AppUserEvent + : public Tizen::Base::Runtime::_Event +{ +// Lifecycle +public: + result Construct(void) + { + return _Event::Initialize(); + } + +protected: + virtual void FireImpl(Tizen::Base::Runtime::IEventListener& listener, const Tizen::Base::Runtime::IEventArg& arg) + { + _IAppUserEventListener* pAppUserEventListener = dynamic_cast<_IAppUserEventListener*>(&listener); + const _AppUserEventArg* pAppUserEventArg = dynamic_cast(&arg); + SysTryReturnVoidResult(NID_APP, pAppUserEventArg != null && pAppUserEventListener != null, E_INVALID_ARG, + "[E_INVALID_ARG] Listener or argument is null."); + + pAppUserEventListener->OnUserEventReceivedN(pAppUserEventArg->GetRequestId(), pAppUserEventArg->GetArgs()); + } +}; + + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_USER_EVENT_H_ diff --git a/src/app/inc/FApp_AppUserEventArg.h b/src/app/inc/FApp_AppUserEventArg.h new file mode 100644 index 0000000..e9d5b8b --- /dev/null +++ b/src/app/inc/FApp_AppUserEventArg.h @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppUserEventArg.h + * @brief This is the header file for the _AppUserEventArg class. + * + * This file contains the declarations of _AppUserEventArg. + */ + +#ifndef _FAPP_INTERNAL_APP_USER_EVENT_ARG_H_ +#define _FAPP_INTERNAL_APP_USER_EVENT_ARG_H_ + +#include +#include +#include + +namespace Tizen { namespace App +{ + +class _AppUserEventArg + : public Tizen::Base::Object + , public Tizen::Base::Runtime::IEventArg +{ +public: + _AppUserEventArg(RequestId reqId, const Tizen::Base::Collection::IList* pArgs) + : __reqId(reqId) + , __pArgs(pArgs) + { + } + + virtual ~_AppUserEventArg(void) {} + + RequestId GetRequestId(void) const + { + return __reqId; + } + Tizen::Base::Collection::IList* GetArgs(void) const + { + return const_cast( __pArgs ); + } + +private: + _AppUserEventArg(const _AppUserEventArg& value); + + _AppUserEventArg& operator =(const _AppUserEventArg& source); + +private: + RequestId __reqId; + const Tizen::Base::Collection::IList* __pArgs; +}; + + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_APP_USER_EVENT_ARG_H_ diff --git a/src/app/inc/FApp_Aul.h b/src/app/inc/FApp_Aul.h new file mode 100644 index 0000000..42f7a54 --- /dev/null +++ b/src/app/inc/FApp_Aul.h @@ -0,0 +1,118 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_Aul.h + * @brief This is the header file of the _Aul class. + */ + +#ifndef _FAPP_INTERNAL_AUL_H_ +#define _FAPP_INTERNAL_AUL_H_ + +#include +#include +#include +#include + +#define MAX_SLP_PACKAGE_ID 128 + +namespace Tizen { namespace App +{ + +/** +* @class _Aul +* @brief SysDep class for AppManager +* @since 2.1 +* @final This class it not intended for extension. +*/ +class _OSP_EXPORT_ _Aul +{ +public: + static result TerminateApplicationByPid(int pid); + + static result SendResult(bundle* b, appsvc_result_val res); + + static bool IsRunning(const AppId& appId, const Tizen::Base::String& exeName); + + static bool IsRunning(const Tizen::Base::String& packageName); + + static void SetOnAppTerminatedCb(int (* pf_app_dead_handler)(int pid, void* pData), void* pData); + + static result SetOomAdj(int pid, int adj); + + static result SetPowerOffNotiListener(void (*powerOffCb)(void *pData), void *pData); + + static int GetAppType(const Tizen::Base::String& category); + + static bool IsInstalled(const AppId& appId); + +public: + /** + * This is static helper class for desktop file. + */ + class _DesktopFile + { + public: + /** + * Updates the service value + * @param[in] appId The application's ID to be executed + * @param[in] value value to be added or updated. + * + * @remark If operations is new, it will be appended. + * but, if same operation is already exist, 'url' and 'mimeType' will be updated. + */ + static result UpdateService(const AppId& appId, const char* value); + + /** + * Removes the service value by operation + * @param[in] appId The application's ID to be executed + * @param[in] operationOnlyValue operationId of service to be removed + */ + static result RemoveService(const AppId& appId, const char* operationOnlyValue); + + private: + /** + * Updates value of specified field + */ + static result UpdateField(const char* path, const char* key, const char* value, bool isRemove = false); + + /** + * Makes desktop file path from appId (retrives appName using _PackageMamagerImpl) + */ + static result MakePath(const AppId& appId, const Tizen::Base::String* pExeName, char* path, int size); + + /** + * Update service value of input buffer with specified value + */ + static char* UpdateServiceValueN(char* buffer, const char* newValue, bool isRemove = false); + + /** + * Extracts each informations from one service string. + */ + static result ParseService(const Tizen::Base::String& service, Tizen::Base::String& operation, Tizen::Base::String& url, Tizen::Base::String& mimeType); + + static void AppendServiceValueToString(Tizen::Base::String& string, const Tizen::Base::String& newVaue); + + friend class UTs_Aul; + }; // _DesktopFile + + friend class UTs_Aul; +}; // _Aul + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_AUL_H_ diff --git a/src/app/inc/FApp_ConditionManagerIpcMessages.h b/src/app/inc/FApp_ConditionManagerIpcMessages.h new file mode 100644 index 0000000..7431c87 --- /dev/null +++ b/src/app/inc/FApp_ConditionManagerIpcMessages.h @@ -0,0 +1,33 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_ConditionManagerIpcMessages.h + * @brief This is the header file for the AppManagerService Ipc message types. + */ + +#include +#include "ipc/ipc_message_macros.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FIo_IpcMessageStart.h" + + +#define IPC_MESSAGE_START ConditionManagerServiceStart + +IPC_SYNC_MESSAGE_CONTROL5_1(ConditionManager_RegisterAppLaunch, Tizen::App::AppId, Tizen::Base::String, Tizen::Base::String, Tizen::Base::Collection::ArrayList, int, result) +IPC_SYNC_MESSAGE_CONTROL3_1(ConditionManager_UnregisterAppLaunch, Tizen::App::AppId, Tizen::Base::String, Tizen::Base::String, result) +IPC_SYNC_MESSAGE_CONTROL3_2(ConditionManager_IsAppLaunchRegistered, Tizen::App::AppId, Tizen::Base::String, Tizen::Base::String, bool, result) diff --git a/src/app/inc/FApp_IActiveWindowEventListener.h b/src/app/inc/FApp_IActiveWindowEventListener.h new file mode 100644 index 0000000..79f4df4 --- /dev/null +++ b/src/app/inc/FApp_IActiveWindowEventListener.h @@ -0,0 +1,41 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FApp_IActiveWindowEventListener.h + * @brief This is the header file for the _IActiveWindowEventListener class. + * + */ +#ifndef _FAPP_INTERNAL_IACTIVE_WINDOW_EVENT_LISTENER_H_ +#define _FAPP_INTERNAL_IACTIVE_WINDOW_EVENT_LISTENER_H_ + +#include + +namespace Tizen { namespace App +{ + +class _IActiveWindowEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + virtual ~_IActiveWindowEventListener(void) {} + + virtual void OnActiveWindowChanged(unsigned int xid, int pid, char* pAppName) = 0; +}; // _IActiveWindowEventListener + +}} // Tizen::App + +#endif // _FAPP_INTERNAL_IACTIVE_WINDOW_EVENT_LISTENER_H_ diff --git a/src/app/inc/FApp_IAppControlSysEventListener.h b/src/app/inc/FApp_IAppControlSysEventListener.h new file mode 100644 index 0000000..0426eef --- /dev/null +++ b/src/app/inc/FApp_IAppControlSysEventListener.h @@ -0,0 +1,57 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IAppControlSysEventListener.h + * @brief This is the header file of the _IAppControlSysEventListener class. + */ + +#ifndef _FAPP_INTERNAL_IAPP_CONTROL_SYS_EVENT_LISTENER_H_ +#define _FAPP_INTERNAL_IAPP_CONTROL_SYS_EVENT_LISTENER_H_ + +#include +#include +#include + +namespace Tizen { namespace Base { namespace Collection { class IMap; } } } + +namespace Tizen { namespace App +{ + +class _AppArg; + +/** + * @class _IAppControlSysEventListener + * @brief + * @since 2.1 + */ +class _IAppControlSysEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + virtual ~_IAppControlSysEventListener(void) {} + + virtual void OnAppControlEventReceivedN(int reqId, _AppArg* pArg, int res) = 0; + + virtual void OnAppControlEventReceivedN(int reqId, int res, const Tizen::Base::Collection::IMap* pArgs) = 0; + + virtual void OnAppControlEventReceivedN(int reqId, const AppId& appId, const Tizen::Base::String& operationId) = 0; +}; // _IAppControlSysEventListener + +} } // Tizen::App + +#endif //_FAPP_INTERNAL_IAPP_CONTROL_SYS_EVENT_LISTENER_H_ diff --git a/src/app/inc/FApp_IAppImpl.h b/src/app/inc/FApp_IAppImpl.h new file mode 100644 index 0000000..4e42011 --- /dev/null +++ b/src/app/inc/FApp_IAppImpl.h @@ -0,0 +1,124 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IAppImpl.h + * @brief This is the header file for the _IAppImpl class. + * + * This file contains the declarations of _IAppImpl. + */ + +#ifndef _FAPP_INTERNAL_IAPP_IMPL_H_ +#define _FAPP_INTERNAL_IAPP_IMPL_H_ + +#include + +namespace Tizen { namespace App +{ + +class _IAppImpl +{ +public: + virtual ~_IAppImpl(void) {} + + /** + * Called when the application is started + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual bool OnCreate(void) = 0; + + /** + * Called when the application's state changes to INITIALIZING + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + virtual bool OnAppInitializing(void) = 0; + + /** + * Called when the application's INITIALIZING state is finished + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + virtual bool OnAppInitialized(void) = 0; + + /** + * Called when other application send the launch request to the application + * + * @since 2.1 + * @param[in] service The handle to the service + * @param[in] initial initial launch + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnService(service_s* service, bool initial) = 0; + + /** + * Called when the application is completely obscured by another application and becomes invisible + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnPause(void) = 0; + + /** + * Called when the application becomes visible + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnResume(void) = 0; + + /** + * Called once after the main loop of application exits + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnTerminate(void) = 0; + + /** + * Called when an orintation event occurs. + * + * @since 2.1 + * @param[in] orientation The information about the orientation event + */ + virtual void OnDeviceOrientationChanged(app_device_orientation_e orientation) = 0; + + /** + * Called when the internal window handle is required. + * + * @since 2.1 + */ + virtual long OnWindowHandleRequest(void) = 0; +}; + + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_IAPP_IMPL_H_ diff --git a/src/app/inc/FApp_IAppLaunchConditionEventListener.h b/src/app/inc/FApp_IAppLaunchConditionEventListener.h new file mode 100644 index 0000000..c556181 --- /dev/null +++ b/src/app/inc/FApp_IAppLaunchConditionEventListener.h @@ -0,0 +1,60 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IAppLaunchConditionEventListener.h + * @brief This is the header file of the _IAppLaunchConditionEventListener interface. + * + * This header file contains the declarations of the _IAppLaunchConditionEventListener interface. + */ +#ifndef _FAPP_INTERNAL_IAPP_LAUNCH_CONDITION_EVENT_LISTENER_H_ +#define _FAPP_INTERNAL_IAPP_LAUNCH_CONDITION_EVENT_LISTENER_H_ + +#include +#include +#include +#include "FApp_AppLaunchCondition.h" + +namespace Tizen { namespace App { + +/** + * @interface _IAppLaunchConditionEventListener + * @brief This interface implements the listener for app launch condition met event. + * @since 2.1 + * + * The _IAppLaunchConditionEventListener interface is the listener interface for receiving condition occurred event, for example, OnAlarmExpired from AlarmConditonHandler. + */ +class _IAppLaunchConditionEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + virtual ~_IAppLaunchConditionEventListener(void) {} + + /** + * Called when an app launch condition meets. + * + * @since 2.1 + * @param[in] The operation related conditional operation, which contains current context. + * @see _AppLaunchConditionHandlerBase::Fire + */ + virtual void OnAppLaunchConditionMet(const _AppLaunchCondition& operation) = 0 ; +}; //_IAppLaunchConditionEventListener + + +}}//Tizen::App + +#endif // _FAPP_INTERNAL_IAPP_LAUNCH_CONDITION_EVENT_LISTENER_H_ diff --git a/src/app/inc/FApp_IAppManager.h b/src/app/inc/FApp_IAppManager.h new file mode 100644 index 0000000..5ada042 --- /dev/null +++ b/src/app/inc/FApp_IAppManager.h @@ -0,0 +1,57 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IAppManager.h + * @brief This is the header file for the %_IAppManager interface. + * + * This header file contains the declarations of the %_IAppManager interface. + */ + +#ifndef _FAPP_INTERNAL_IAPP_MANAGER_ +#define _FAPP_INTERNAL_IAPP_MANAGER_ + +#include +#include + +namespace Tizen { namespace Base { class String; } } +namespace Tizen { namespace Base { namespace Collection { class ArrayList; } } } + +namespace Tizen { namespace App +{ +class _IAppManagerServiceEventListener; + +class _IAppManager +{ +public: + virtual ~_IAppManager() {} + + virtual result LaunchApplication(const AppId& appId, const Tizen::Base::String& executableName, int req) = 0; + virtual result TerminateApplication(const AppId& appId, const Tizen::Base::String& executableName) = 0; + virtual bool IsRunning(const AppId& appId, const Tizen::Base::String& executableName) = 0; + virtual result GetRunningAppList(Tizen::Base::Collection::ArrayList* pArray) = 0; + virtual result RegisterApplication(const AppId& appId, const Tizen::Base::String& executableName, _AppType appType, int pid) = 0; + virtual result UnregisterApplication(int pid) = 0; + + virtual result InitEventListener(_IAppManagerServiceEventListener* pListener) = 0; + virtual result AddEventListener(int clientId) = 0;//, _IAppManagerServiceEventListener* pListener) = 0; + virtual result RemoveEventListener(int clientId) = 0;//, _IAppManagerServiceEventListener* pListener) = 0; +}; + +}} // Tizen::App + +#endif //_FAPP_INTERNAL_IAPP_MANAGER_ diff --git a/src/app/inc/FApp_IAppManagerEventListener.h b/src/app/inc/FApp_IAppManagerEventListener.h new file mode 100644 index 0000000..51e4c54 --- /dev/null +++ b/src/app/inc/FApp_IAppManagerEventListener.h @@ -0,0 +1,69 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IAppManagerEventListener.h + * @brief This is the header file for _IAppManagerEventListener class. + */ + +#ifndef _FAPP_INTERNAL_IAPP_MANAGER_EVENT_LISTENER_H_ +#define _FAPP_INTERNAL_IAPP_MANAGER_EVENT_LISTENER_H_ + +#include +#include +#include + +namespace Tizen { namespace App { + +/** +* @interface _IAppManagerEventListener +* @brief This is a tagging interface that all event listeners must implement. +* @since 2.1 +* +* The event listener can listen when the specific event is fired. The event listener +* has several methods, and each method will be called when the specific event is fired. +* +*/ +class _IAppManagerEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_IAppManagerEventListener(){} + + /** + * This method will be called when the application is launched. + * + * @since 2.1 + */ + virtual void OnApplicationLaunched(const AppId& appId, Tizen::App::_AppType type) = 0; + + /** + * This method will be called when the application is terminated. + * + * @since 2.1 + */ + virtual void OnApplicationTerminated(const AppId& appId, Tizen::App::_AppType type) = 0; +}; // _IAppManagerEventListener + +} } //Tizen::App + +#endif // _FAPP_INTERNAL_IAPP_MANAGER_EVENT_LISTENER_H_ diff --git a/src/app/inc/FApp_IAppManagerServiceEventListener.h b/src/app/inc/FApp_IAppManagerServiceEventListener.h new file mode 100644 index 0000000..a94bc44 --- /dev/null +++ b/src/app/inc/FApp_IAppManagerServiceEventListener.h @@ -0,0 +1,53 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IAppManagerServiceEventListener.h + * @brief This is the header file for the _IAppManagerServiceEventListener class. + */ + +#ifndef _FAPP_INTERNAL_IAPP_MANAGER_SERVICE_EVENT_LISTENER_H_ +#define _FAPP_INTERNAL_IAPP_MANAGER_SERVICE_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace App +{ + +class _AppManagerEventArg; + +/** + * @interface _IAppManagerServiceEventListener + * @brief This interface defines the listener for the event from _AppManangerService + * @since 2.1 + * + * Purpose of this interface is letting _AppManagerService and _AppManagerProxy implements this + * interface so they can notify to their paired client _AppManagerStub and _AppManagerImpl. + * Application should not implement this interface. + */ +class _IAppManagerServiceEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + virtual result OnServiceEventReceived(int clientId, const _AppManagerEventArg& arg) = 0; + virtual result OnTerminateApplicationRequested(int clientId) = 0; +}; // _IAppManagerServiceEventListener + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_IAPP_MANAGER_SERVICE_EVENT_LISTENER_H_ diff --git a/src/app/inc/FApp_IAppResourceBitmap.h b/src/app/inc/FApp_IAppResourceBitmap.h new file mode 100644 index 0000000..8a7d6c8 --- /dev/null +++ b/src/app/inc/FApp_IAppResourceBitmap.h @@ -0,0 +1,52 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IAppResourceBitmap.h + * @brief This is the header file of the _IAppResourceBitmap class. + */ + +#ifndef _FAPP_INTERNAL_IAPP_RESOURCE_BITMAP_H_ +#define _FAPP_INTERNAL_IAPP_RESOURCE_BITMAP_H_ + +#include + +namespace Tizen { namespace Graphics { class Bitmap; } } + +namespace Tizen { namespace Base +{ +class String; +}}//Tizen::Base + +namespace Tizen { namespace App +{ + +class _IAppResourceBitmap +{ +public: + /** + * This is the destructor for this class. + */ + virtual ~_IAppResourceBitmap(void) {}; + + virtual Tizen::Graphics::Bitmap* GetBitmapN(const Tizen::Base::String& imagePath, Tizen::Graphics::BitmapPixelFormat pixelFormat) const = 0; + +}; // _IAppResourceBitmap + +}} // Tizen::App + +#endif // _FAPP_INTERNAL_IAPP_RESOURCE_BITMAP_H_ diff --git a/src/app/inc/FApp_IAppUserEventListener.h b/src/app/inc/FApp_IAppUserEventListener.h new file mode 100644 index 0000000..ae21e8b --- /dev/null +++ b/src/app/inc/FApp_IAppUserEventListener.h @@ -0,0 +1,48 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_IAppUserEventListener.h + * @brief This is the header file for the _IAppUserEventListener class. + * + * This file contains the declarations of ClassName. + */ + + +#ifndef _FAPP_INTERNAL_IAPP_USER_EVENT_LISTENER_H_ +#define _FAPP_INTERNAL_IAPP_USER_EVENT_LISTENER_H_ + +#include +#include + + +namespace Tizen { namespace App +{ + +class _IAppUserEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + virtual ~_IAppUserEventListener(void) {} + + virtual void OnUserEventReceivedN(RequestId reqId, Tizen::Base::Collection::IList* pArgs) = 0; +}; + + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_IAPP_USER_EVENT_LISTENER_H_ diff --git a/src/app/inc/FApp_NotificationManagerEventParamTraits.h b/src/app/inc/FApp_NotificationManagerEventParamTraits.h new file mode 100644 index 0000000..557c465 --- /dev/null +++ b/src/app/inc/FApp_NotificationManagerEventParamTraits.h @@ -0,0 +1,119 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationManagerEventParamTraits.h + * @brief This is the header file for NotificationManagerEvent param traits. + */ + +#ifndef _FAPP_INTERNAL_NOTIFICATIONMANAGER_EVENT_ARG_PARAM_TRAITS_H_ +#define _FAPP_INTERNAL_NOTIFICATIONMANAGER_EVENT_ARG_PARAM_TRAITS_H_ + +#include "FBaseString.h" +#include "FBaseColIList.h" +#include "FBaseColArrayList.h" +#include "FIo_IpcCommonDataTypes.h" + +#include "base/tuple.h" +#include "ipc/ipc_param_traits.h" + +#include "FAppNotificationMessage.h" + + +namespace IPC +{ +template <> +struct ParamTraits +{ + typedef Tizen::App::NotificationMessage param_type; + + static void Write(Message* m, const param_type& p) + { + WriteParam(m, p.GetAlertText()); + WriteParam(m, p.GetAppMessage()); + WriteParam(m, p.GetTitleText()); + WriteParam(m, p.GetIconFilePath()); + WriteParam(m, p.GetSoundFilePath()); + + m->WriteInt(p.GetBadgeNumber()); + m->WriteInt(p.GetBadgeOffset()); + m->WriteInt((int)p.GetOngoingActivityType()); + m->WriteInt(p.GetOngoingActivityProgressValue()); + } + + static bool Read(const Message* m, void** iter, param_type* r) + { + Tizen::Base::String alertText; + Tizen::Base::String appMessage; + Tizen::Base::String titleText; + Tizen::Base::String iconFilePath; + Tizen::Base::String soundFilePath; + + int badgeNo = -1; + int badgeOffset = 0; + int progressValue = -1; + int activityType = Tizen::App::ONGOING_ACTIVITY_TYPE_TEXT; + + if (!ReadParam(m, iter, &alertText)) + { + return false; + } + if (!ReadParam(m, iter, &appMessage)) + { + return false; + } + if (!ReadParam(m, iter, &titleText)) + { + return false; + } + if (!ReadParam(m, iter, &iconFilePath)) + { + return false; + } + if (!ReadParam(m, iter, &soundFilePath)) + { + return false; + } + m->ReadInt(iter, &badgeNo); + m->ReadInt(iter, &badgeOffset); + m->ReadInt(iter, &progressValue); + m->ReadInt(iter, &activityType); + + Tizen::App::NotificationMessage notimessage; + notimessage.SetAlertText(alertText); + notimessage.SetAppMessage(appMessage); + notimessage.SetTitleText(titleText); + notimessage.SetIconFilePath(iconFilePath); + notimessage.SetSoundFilePath(soundFilePath); + + notimessage.SetBadgeNumber(badgeNo); + notimessage.SetBadgeOffset(badgeOffset); + notimessage.SetOngoingActivityProgressValue(progressValue); + notimessage.SetOngoingActivityType((Tizen::App::OngoingActivityType)activityType); + + *r = notimessage; + + return true; + } + static void Log(const param_type& p, std::string* l) + { + } + +}; +} + +#endif //_FAPP_INTERNAL_NOTIFICATIONMANAGER_EVENT_ARG_PARAM_TRAITS_H_ diff --git a/src/app/inc/FApp_NotificationManagerImpl.h b/src/app/inc/FApp_NotificationManagerImpl.h new file mode 100644 index 0000000..00c2312 --- /dev/null +++ b/src/app/inc/FApp_NotificationManagerImpl.h @@ -0,0 +1,449 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationManagerImpl.h + * @brief This is the header file for the %_NotificationManagerImpl class. + */ + +#ifndef _FAPP_INTERNAL_NOTIFICATION_MANAGER_IMPL_H_ +#define _FAPP_INTERNAL_NOTIFICATION_MANAGER_IMPL_H_ + +#include +#include +#include + +namespace Tizen { namespace App +{ + +class NotificationManager; +class _NotificationManagerProxy; + +class _OSP_EXPORT_ _NotificationManagerImpl + : public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 1.0 + */ + _NotificationManagerImpl(void); + + /** + * This is the destructor for this class. + * + * @since 1.0 + */ + virtual ~_NotificationManagerImpl(void); + + /** + * Initializes this instance of %_NotificationManagerImpl. + * + * @since 1.0 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result Construct(void); + + /** + * Gets the badge number of the application icon. + * + * @since 1.0 + * + * @return The current badge number + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OBJ_NOT_FOUND The application is not installed. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + * @remarks The specific error code can be accessed using the GetLastResult() method. @n + * In case of failure, this method returns @c -1. + */ + int GetBadgeNumber(void) const; + + /** + * Notifies the user using a badge number. + * + * @since 1.0 + * + * @return An error code + * @param[in] badgeNumber The badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the specified @c badgeNumber is less than @c 0. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the Tizen platform policy. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result Notify(int badgeNumber) const; + + /** + * Notifies the user using a message. + * + * @since 1.0 + * + * @return An error code + * @param[in] messageText The notification message + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the Tizen platform policy. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result Notify(const Tizen::Base::String& messageText) const; + + /** + * Notifies the user using a message and badge number. + * + * @since 1.0 + * + * @return An error code + * @param[in] messageText The notification message + * @param[in] badgeNumber The badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c badgeNumber is less than @c 0, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the Tizen platform policy. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result Notify(const Tizen::Base::String& messageText, int badgeNumber) const; + + /** + * Notifies the user using a message and badge number. @n + * If the user checks the message, @c launchArguments is delivered to the application. @n + * @c launchArguments is specified as input parameter for Application::OnUserEventReceivedN() or can be obtained by + * invoking Application::GetAppArgumentListN(), especially within Application::OnAppInitializing(). + * + * @since 1.0 + * + * @return An error code + * @param[in] messageText The notification message + * @param[in] badgeNumber The badge number + * @param[in] launchArguments The message for application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The specified @c badgeNumber is less than @c 0. @n + * - The length of the specified @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of the specified @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the Tizen platform policy. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + * @see Application::OnUserEventReceivedN(), Application::GetAppArgumentListN() + */ + result Notify(const Tizen::Base::String& messageText, int badgeNumber, const Tizen::Base::String& launchArguments) const; + + /** + * Removes the notification message. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM A system error occurred. + * @exception E_INVALID_STATE This instance is in an invalid state: @n + * - The Construct() method is not called. @n + * @remarks The method returns E_SUCCESS when there is no outstanding notification. + */ + result RemoveNotification(void); + + /** + * Notifies the user about the ongoing activity using a message. + * + * @since 2.0 + * + * @return An error code + * @param[in] messageText The notification message + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the Tizen platform policy. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result NotifyOngoingActivity(const Tizen::Base::String& messageText) const; + + /** + * Notifies the user about the ongoing activity using a message. @n + * @c launchArguments is specified as input parameter for Application::OnUserEventReceivedN() or can be obtained by + * invoking Application::GetAppArgumentListN(), especially within Application::OnAppInitializing(). + * + * @since 2.0 + * + * @return An error code + * @param[in] messageText The notification message + * @param[in] launchArguments The launch arguments for the application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The length of the specified @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of the specified @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the Tizen platform policy. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + * @see Application::OnUserEventReceivedN(), Application::GetAppArgumentListN() + */ + result NotifyOngoingActivity(const Tizen::Base::String& messageText, const Tizen::Base::String& launchArguments) const; + + /** + * Removes the notification message for the ongoing activity. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + * @remarks The method returns E_SUCCESS when there is no outstanding notification. + */ + result RemoveOngoingActivityNotification(void); + + /** + * Gets the badge number of the application icon. + * + * @since 1.0 + * + * @return The current badge number + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_OBJ_NOT_FOUND The application is not installed. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + * @remarks The specific error code can be accessed using the GetLastResult() method. @n + * In case of failure, this method returns @c -1. + */ + int GetBadgeNumber(const AppId& appId) const; + + /** + * Notifies the user using a badge number on behalf of the specified application. + * + * @since 1.0 + * + * @return An error code + * @param[in] appId The application ID + * @param[in] badgeNumber The badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the specified @c badgeNumber is less than @c 0. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to get any notification as per the Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result NotifyOnBehalf(const AppId& appId, int badgeNumber) const; + + /** + * Notifies the user using a message on behalf of the specified application. + * + * @since 1.0 + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to receive any notification as per the Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result NotifyOnBehalf(const AppId& appId, const Tizen::Base::String& messageText) const; + + /** + * Notifies the user using a message and badge number on behalf of the specified application. + * + * @since 1.0 + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @param[in] badgeNumber The badge number + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The specified @c badgeNumber is less than @c 0. @n + * - The length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to receive any notification as per the Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result NotifyOnBehalf(const AppId& appId, const Tizen::Base::String& messageText, int badgeNumber) const; + + /** + * Notifies the user using a message and badge number on behalf of the specified application. @n + * If the user checks the message, the @c launchArguments is delivered to the application. + * + * @since 2.0 + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @param[in] launchArguments The launch arguments for the application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The length of the specified @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of the specified @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to receive any notification as per the Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result NotifyOnBehalf(const AppId& appId, const Tizen::Base::String& messageText, const Tizen::Base::String& launchArguments) const; + + /** + * Notifies the user using a message and badge number on behalf of the specified application. @n + * If the user checks the message, the @c launchArguments is delivered to the application. + * + * @since 2.0 + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @param[in] badgeNumber The badge number + * @param[in] launchArguments The launch arguments for the application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The specified @c badgeNumber is less than 0. @n + * - The length of the specified @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of the specified @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_INVALID_OPERATION The target application with the specified application ID is not permitted to receive any notification as per the Tizen platform policy. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result NotifyOnBehalf(const AppId& appId, const Tizen::Base::String& messageText, int badgeNumber, const Tizen::Base::String& launchArguments) const; + + /** + * Notifies the user about the ongoing activity using a message on behalf of the specified application. + * + * @since 2.0 + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid, or + * the length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the Tizen platform policy. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result NotifyOngoingActivityOnBehalf(const AppId& appId, const Tizen::Base::String& messageText) const; + + /** + * Notifies the user about the ongoing activity using a message on behalf of the specified application. + * + * @since 2.0 + * + * @return An error code + * @param[in] appId The application ID + * @param[in] messageText The notification message + * @param[in] launchArguments The launch arguments for application + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - A specified input parameter is invalid. @n + * - The length of @c messageText is greater than App::MAX_NOTIFICATION_MESSAGE_LENGTH. @n + * - The length of @c launchArguments is greater than App::MAX_NOTIFICATION_LAUNCH_ARGUMENTS_LENGTH. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_OPERATION The type of application calling this method is invalid as per the Tizen platform policy. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + */ + result NotifyOngoingActivityOnBehalf(const AppId& appId, const Tizen::Base::String& messageText, const Tizen::Base::String& launchArguments) const; + + /** + * Removes the notification message for ongoing activity on behalf of the specified application. + * + * @since 2.0 + * + * @return An error code + * @param[in] appId The application ID + * @exception E_SUCCESS The method is successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_STATE This instance is in an invalid state. @n + * The Construct() method is not called. + * @remarks Although there is no outstanding notification for the calling application, this method returns E_SUCCESS. + */ + result RemoveOngoingActivityNotificationOnBehalf(const AppId& appId); + + /** + * Removes the notification message on behalf of the specified application. + * + * @since 2.0 + * + * @return An error code + * @param[in] appId The application ID + * @exception E_SUCCESS The method was successful. + * @exception E_APP_NOT_INSTALLED The application is not installed. + * @exception E_SYSTEM A system error occurred. + * @exception E_INVALID_STATE This instance is in an invalid state: @n + * - The Construct() method is not called. @n + * @remarks Although there is no outstanding notification for the calling application, this method returns E_SUCCESS. + */ + result RemoveNotificationOnBehalf(const AppId& appId); + + static const _NotificationManagerImpl* GetInstance(const NotificationManager& notiMgr); + + static _NotificationManagerImpl* GetInstance(NotificationManager& notiMgr); + +private: + result NotifyImpl(const Tizen::Base::String& messageText, int badgeNumber, const Tizen::Base::String& launchArguments, bool isOngoing = false) const; + + result NotifyImpl(const AppId& appId, const Tizen::Base::String& messageText, int badgeNumber, const Tizen::Base::String& launchArguments, bool isOngoing = false) const; + + inline result OngoingImpl(const Tizen::Base::String& messageText, const Tizen::Base::String& launchArguments) const; + + inline result OngoingImpl(const AppId& appId, const Tizen::Base::String& messageText, const Tizen::Base::String& launchArguments) const; + + _NotificationManagerImpl(const _NotificationManagerImpl& rhs); + + _NotificationManagerImpl& operator =(const _NotificationManagerImpl& rhs); + +private: + _NotificationManagerProxy* __pNotificationManager; +}; //_NotificationManagerImpl + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_NOTIFICATION_MANAGER_IMPL_H_ diff --git a/src/app/inc/FApp_NotificationManagerIpcMessages.h b/src/app/inc/FApp_NotificationManagerIpcMessages.h new file mode 100644 index 0000000..96cedef --- /dev/null +++ b/src/app/inc/FApp_NotificationManagerIpcMessages.h @@ -0,0 +1,35 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_NotificationManagerIpcMessages.h + * @brief This is the header file for the NotificationManager Ipc message types. + */ + +#include +#include + +#include "ipc/ipc_message_macros.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FIo_IpcMessageStart.h" +#include "FApp_NotificationManagerEventParamTraits.h" + +#define IPC_MESSAGE_START NotificationManagerServiceStart + +IPC_SYNC_MESSAGE_CONTROL3_1(NotificationManager_NotifyMessage, Tizen::App::AppId, Tizen::App::NotificationMessage, bool, result) +IPC_SYNC_MESSAGE_CONTROL2_1(NotificationManager_RemoveNotification, Tizen::App::AppId, bool, result) + diff --git a/src/app/inc/FApp_PackageManagerIpcMessages.h b/src/app/inc/FApp_PackageManagerIpcMessages.h new file mode 100755 index 0000000..d49f91d --- /dev/null +++ b/src/app/inc/FApp_PackageManagerIpcMessages.h @@ -0,0 +1,31 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_PackageManagerIpcMessages.h + * @brief This is the header file for the PackageManager Ipc message types. + */ + +#include +#include "ipc/ipc_message_macros.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FIo_IpcMessageStart.h" + +#define IPC_MESSAGE_START PackageManagerServiceStart + +IPC_SYNC_MESSAGE_CONTROL3_1(PackageManager_InstallPackage, Tizen::App::PackageId, Tizen::Base::String, int, result) +IPC_SYNC_MESSAGE_CONTROL2_1(PackageManager_UninstallPackage, Tizen::App::PackageId, int, result) diff --git a/src/app/inc/FApp_PackageManagerProxy.h b/src/app/inc/FApp_PackageManagerProxy.h new file mode 100755 index 0000000..c872ee2 --- /dev/null +++ b/src/app/inc/FApp_PackageManagerProxy.h @@ -0,0 +1,71 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_PackageManagerProxy.h + * @brief This is the header file of the _PackageManagerProxy class. + */ + +#ifndef _FAPP_INTERNAL_PACKAGE_MANAGER_PROXY_H_ +#define _FAPP_INTERNAL_PACKAGE_MANAGER_PROXY_H_ + +#include +#include +#include +#include + +#include "FApp_Types.h" + +namespace Tizen { namespace Io { class _IpcClient; } } + +namespace Tizen { namespace App { namespace Package { +class IPackageInstallationResponseListener; +class IPackageUninstallationResponseListener; +}}} + +namespace Tizen { namespace App +{ + +/** + * @class _PackageManagerProxy + * @brief + * @since 2.1 + */ +class _PackageManagerProxy + : public Tizen::Base::Object +{ +public: + _PackageManagerProxy(void); + virtual ~_PackageManagerProxy(void); + + result Construct(void); + + result InstallPackage(const PackageId& packageId, const Tizen::Base::String& packagePath, Tizen::App::Package::IPackageInstallationResponseListener* pListener); + result UninstallPackage(const PackageId& packageId, Tizen::App::Package::IPackageUninstallationResponseListener* pListener); + +private: + _PackageManagerProxy(const _PackageManagerProxy& rhs); + _PackageManagerProxy& operator =(const _PackageManagerProxy& rhs); + +private: + Tizen::Io::_IpcClient* __pIpcClient; + +}; // _PackageManagerProxy + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_PACKAGE_MANAGER_PROXY_H_ diff --git a/src/app/inc/FApp_RequestManagerT.h b/src/app/inc/FApp_RequestManagerT.h new file mode 100644 index 0000000..48952d2 --- /dev/null +++ b/src/app/inc/FApp_RequestManagerT.h @@ -0,0 +1,166 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_RequestManagerT.h + * @brief This is the header file for the _RequestManagerT class. + */ + +#ifndef _FAPP_INTERNAL_REQUEST_MANAGERT_H_ +#define _FAPP_INTERNAL_REQUEST_MANAGERT_H_ + +#include + +#include +#include + +#include + +namespace Tizen { namespace Base +{ +class String; +}} + +namespace Tizen { namespace App +{ + +template +class _RequestManagerT +{ +public: + typedef Tizen::Base::Collection::HashMapT RequestListType; + typedef Tizen::Base::Collection::IMapEnumeratorT RequestListEnumType; + + _RequestManagerT(void) + : __reqId(-1) + { + __requestList.Construct(); + } + + ~_RequestManagerT(void) + { + RequestListEnumType* pIter = __requestList.GetMapEnumeratorN(); + if (pIter == null) + { + return; + } + + while (pIter->MoveNext() == E_SUCCESS) + { + T* pInfo = null; + result r = pIter->GetValue(pInfo); + + if (IsFailed(r)) + { + continue; + } + + delete pInfo; + } + + delete pIter; + } + + int InsertItem(T* pItem) + { + SysTryReturn(NID_APP, pItem != null, -1, E_INVALID_ARG, "[E_INVALID_ARG] Empty argument."); + +#if 0 + // [INFO] temporary disable due to OBS build system + __sync_add_and_fetch(&__reqId, 1); + + // [TODO] awkward implementation after overflow + // overflow detection + __sync_bool_compare_and_swap(&__reqId, INT_MAX, 1); +#else + __reqId++; + if (__reqId >= INT_MAX) + { + __reqId = 1; + } +#endif + SysLog(NID_APP, "Current request ID : %d.", __reqId); + + pItem->reqId = __reqId; + __requestList.Add(__reqId, pItem); + + return __reqId; + } + + void RemoveItem(int reqId) + { + T* pItem = FindItem(reqId); + if (pItem) + { + __requestList.Remove(reqId); + delete pItem; + } + } + + void RemoveItem(T* pItem) + { + RequestListEnumType* pIter = __requestList.GetMapEnumeratorN(); + if (pItem == null || pIter == null) + { + return; + } + + while (pIter->MoveNext() == E_SUCCESS) + { + T* pInfo = null; + result r = pIter->GetValue(pInfo); + + if (pInfo == pItem) + { + int id = -1; + r = pIter->GetKey(id); + if (r == E_SUCCESS) + { + __requestList.Remove(id); + } + + delete pItem; + delete pIter; + + return; + } + } + + delete pIter; + } + + T* FindItem(int reqId) const + { + T* pItem = null; + result r = __requestList.GetValue(reqId, pItem); + + return (r == E_SUCCESS) ? pItem : null; + } + +private: + _RequestManagerT(const T& rhs); + + _RequestManagerT& operator =(const _RequestManagerT& rhs); + +private: + int __reqId; + RequestListType __requestList; +}; // _RequestManagerT + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_REQUEST_MANAGERT_H_ diff --git a/src/app/inc/FApp_ServiceAppImpl.h b/src/app/inc/FApp_ServiceAppImpl.h new file mode 100644 index 0000000..2f2f797 --- /dev/null +++ b/src/app/inc/FApp_ServiceAppImpl.h @@ -0,0 +1,219 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_ServiceAppImpl.h + * @brief This is the header file for the %_ServiceAppImpl class. + */ + +#ifndef _FAPP_INTERNAL_SERVICE_APP_IMPL_H_ +#define _FAPP_INTERNAL_SERVICE_APP_IMPL_H_ + +#include + +#include + +#include "FApp_IAppImpl.h" + +namespace Tizen { namespace Base { namespace Collection { class IList; } } } +namespace Tizen { namespace Base { namespace Runtime { class _EventDispatcher; } } } + +namespace Tizen { namespace App +{ + +/** + * @class _ServiceAppImpl + * @brief This class is the Impl class of a ServiceApp class. + * @since 2.1 + * + * This class is the Impl class of a ServiceApp class. + */ +class _OSP_EXPORT_ _ServiceAppImpl + : public Tizen::Base::Object + , public Tizen::App::_IAppImpl +{ +public: + /** + * Returns the _ServiceAppImpl's instance pointer. + * + * @since 2.1 + * @return A pointer to the %_ServiceAppImpl instance, @n + * else @c null if it fails + */ + static _ServiceAppImpl* GetInstance(); + + /** + * Returns the ServiceApp's instance pointer. + * + * @since 2.1 + * @return A pointer to the %ServiceApp instance, @n + * else @c null if it fails + */ + ServiceApp* GetServiceAppInstance(); + + + /** + * Called when the application is started + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual bool OnCreate(void); + + /** + * Called when other application send the launch request to the application + * + * @since 2.1 + * @param[in] service The handle to the service + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnService(service_s* service, bool initial); + + /** + * Called when the application is completely obscured by another application and becomes invisible + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnPause(void); + + /** + * Called when the application becomes visible + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnResume(void); + + /** + * Called once after the main loop of application exits + * + * @since 2.1 + * @param[in] user_data The user data passed from the callback registration function + * @remarks This is a system dependent callback function + */ + virtual void OnTerminate(void); + + /** + * Called when an orintation event occurs. + * + * @since 2.1 + * @param[in] orientation The information about the orientation event + */ + virtual void OnDeviceOrientationChanged(app_device_orientation_e orientation); + + /** + * Called when the application's state changes to Tizen::App::AppState::INITIALIZING. @n + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + virtual bool OnAppInitializing(void); + + /** + * Called when the application's INITIALIZING state is finished + * + * @since 2.1 + * @return @c true if the method is successful, @n + * else @c false + */ + virtual bool OnAppInitialized(void); + + /** + * Called when the internal window handle is required. + * + * @since 2.1 + */ + virtual long OnWindowHandleRequest(void); + + /** + * Called when the application's state change to Tizen::App::AppState::TERMINATING. @n + * + * @since 2.1 + * @param[in] forcedTermination @c true if the application terminate by system or other application, else @c false. + * @return @c true if the method is successful, @n + * else @c false + */ + bool OnServiceAppImplTerminating(bool forcedTermination); + + /** + * Executes an application implemented by inheriting App class. + * This method must be called from the UiApp or ServiceApp. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INIT_FAILED The initialization failure during OnAppInitializing(). + * @exception E_SYSTEM A system error has occurred. + */ + result Execute(void); + +private: + /** + * This is the default constructor for this class. + * + * @since 2.1 + */ + _ServiceAppImpl(void); + + /** + * This is the constructor for this class. + * + * @since 2.1 + */ + _ServiceAppImpl(ServiceApp* pServiceApp); + + /** + * This is the copy constructor for the this class. + */ + _ServiceAppImpl(const _ServiceAppImpl& source); + + /** + * This is the assignment operator for this class. + */ + _ServiceAppImpl& operator =(const _ServiceAppImpl& source); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_ServiceAppImpl(void); + +private: + static _ServiceAppImpl* __pServiceAppImpl; + + _AppImpl* __pAppImpl; + + ServiceApp* __pServiceApp; + + friend class ServiceApp; + +}; // _ServiceAppImpl + +} } //Tizen::App + +#endif // _FAPP_INTERNAL_SERVICE_APP_IMPL_H_ diff --git a/src/app/inc/FApp_TemplateUtil.h b/src/app/inc/FApp_TemplateUtil.h new file mode 100755 index 0000000..7f91010 --- /dev/null +++ b/src/app/inc/FApp_TemplateUtil.h @@ -0,0 +1,158 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_TemplateUtil.h + * @brief This is the header file for the internap Tizen::App utilities. + */ + +#ifndef _FAPP_INTERNAL_TEMPLATE_UTIL_H_ +#define _FAPP_INTERNAL_TEMPLATE_UTIL_H_ + +#include +#include +#include + +namespace Tizen { namespace App +{ + +template void +_DeleteCollection(Tizen::Base::Collection::ICollectionT& col) +{ + Tizen::Base::Collection::IEnumeratorT* pEnum = col.GetEnumeratorN(); + + if (pEnum) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + Type* pElem = null; + pEnum->GetCurrent(pElem); + + delete pElem; + } + + delete pEnum; + } +} + +template void +_DeleteCollectionMapValue(Tizen::Base::Collection::IMapT& col) +{ + Tizen::Base::Collection::IMapEnumeratorT* pEnum = col.GetMapEnumeratorN(); + + if (pEnum) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + ValueType* pValue = null; + pEnum->GetValue(pValue); + + delete pValue; + } + + delete pEnum; + } +} + +template void +_DeleteCollectionMapValue(Tizen::Base::Collection::IMultiMapT& col) +{ + Tizen::Base::Collection::IMapEnumeratorT* pEnum = col.GetMapEnumeratorN(); + + if (pEnum) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + ValueType* pValue = null; + pEnum->GetValue(pValue); + + delete pValue; + } + + delete pEnum; + } +} + +} } // Tizen::App + +namespace Tizen { namespace Base +{ + +template<> +class ComparerT +: public virtual Tizen::Base::Collection::IComparerT +, public Object +{ +public: + ComparerT(void) {} + + virtual ~ComparerT(void) {} + + virtual result Compare(const String& obj1, const String& obj2, int& cmp) const + { + cmp = String::Compare(obj1, obj2); + return E_SUCCESS; + } + +private: + ComparerT(const ComparerT& rhs); + + ComparerT& operator =(const ComparerT& rhs); +}; + +namespace Collection +{ + +template <> +class __HashMapDefaultProviderT +: public IHashCodeProviderT +, public Object +{ + public: + __HashMapDefaultProviderT(void) {} + + virtual ~__HashMapDefaultProviderT(void) {} + + virtual int GetHashCode(const String& obj) const + { + return obj.GetHashCode(); + } +}; + +template<> +class __MultiHashMapDefaultProviderT +: public IHashCodeProviderT +, public Object +{ + public: + __MultiHashMapDefaultProviderT(void) {} + + virtual ~__MultiHashMapDefaultProviderT(void) {} + + virtual int GetHashCode(const String& obj) const + { + return obj.GetHashCode(); + } +}; + + +} // Collection + +}} // Tizen::Base + +#endif //_FAPP_INTERNAL_TEMPLATE_UTIL_H_ + diff --git a/src/app/inc/FApp_Types.h b/src/app/inc/FApp_Types.h new file mode 100644 index 0000000..77c0579 --- /dev/null +++ b/src/app/inc/FApp_Types.h @@ -0,0 +1,114 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_Types.h + * @brief This is the header file for the internal Tizen::App types. + */ + +#ifndef _FAPP_INTERNAL_TYPES_H_ +#define _FAPP_INTERNAL_TYPES_H_ + + +namespace Tizen { namespace App +{ + +#define DRM_PARAM_MAX_LENGTH 4096 +#define WIDGET_APP_MAX_APPID_LENGTH 255 +#define NATIVE_APP_MAX_APPID_LENGTH 256 + +#define APP_APPID_SIZE_MAX 256 +#define APP_APPNAME_SIZE_MAX 256 +#define MAPP_CHANNELNAME_SIZE_MAX 256 +#define MAPP_PATH_SIZE_MAX 256 + +/** + * @enum _AppType + * Defines the type of an application. + * + * @since 2.1 + */ +enum _AppType +{ + _APP_TYPE_UI_APP = 0x01, /**< %UiApp type */ + _APP_TYPE_SERVICE_APP = 0x02, /**< %ServiceApp type */ + _APP_TYPE_IME_APP = 0x10, /**< %ImeApp type */ + _APP_TYPE_HOME_APP = 0x20, /**< %HomeApp type */ + _APP_TYPE_LOCK_APP = 0x40, /**< %LockApp type */ + _APP_TYPE_MENU_APP = 0x80, /**< %MenuApp type */ + _APP_TYPE_WEB_APP = 0x1000, /**< %WebApp type */ +}; + +enum _AppEvent +{ + AE_BATTERY = 0x01, + AE_LOW_MEMORY, + AE_LEGACY_APPCONTROL, + AE_LAUNCH_REQUEST, + AE_CHECKPOINT, + AE_DELETE_FRAME, + AE_CLEAR_LISTENER, +}; + +/** + * @enum _ApphandlerType + * Defines the application provider type + */ +enum _AppHandler +{ + _APP_HANDLER_NONE = 0x00, + _APP_HANDLER_APPCONTROL = 0x01, + _APP_HANDLER_DATACONTROL = 0x02, + _APP_HANDLER_LAUNCH_NORMAL = 0x04, + _APP_HANDLER_LAUNCH_COND = 0x08, +}; + +/** + * @enum _DataControlAccess + * Defines the DataControl accessibility + */ +enum _DataControlAccess +{ + _DATACONTROL_ACCESS_UNDEFINED = 0x00, + _DATACONTROL_ACCESS_READ = 0x01, + _DATACONTROL_ACCESS_WRITE = 0x10, + _DATACONTROL_ACCESS_READWRITE = 0x11, +}; + +// +// AppControl result mapping +// APP_CTRL_RESULT_SUCCEEDED <-> APPSVC_RES_OK (0) == SERVICE_RESULT_SUCCEEDED +// APP_CTRL_RESULT_FAILED <-> APPSVC_OSP_RES_FAIL +// APP_CTRL_RESULT_CANCELED <-> APPSVC_RES_NOT_OK (-1) == SERVICE_RESULT_FAILED +// APP_CTRL_RESULT_TERMINATED <-> APPSVC_OSP_RES_TERMINATE +// APP_CTRL_RESULT_ABORTED <-> APPSVC_RES_CANCEL (-2) == SERVICE_RESULT_CANCELED +// +const int APPSVC_OSP_RES_FAIL = -13; +const int APPSVC_OSP_RES_TERMINATE = -14; + +const int LAUNCH_ARG_META_COUNT = 3; + +_OSP_LOCAL_ extern const wchar_t LEGACY_LAUNCH_REASON_NORMAL[]; +_OSP_LOCAL_ extern const wchar_t LEGACY_LAUNCH_REASON_CONDITIONAL[]; +_OSP_LOCAL_ extern const wchar_t TIZEN_OPERATION_MAIN[]; +_OSP_EXPORT_ extern const wchar_t TIZEN_OPERATION_PICK[]; +_OSP_LOCAL_ extern const char TIZEN_APPCONTROL_DATA_LEGACY[]; +_OSP_LOCAL_ extern const char TIZEN_NOTIFICATION_DATA[]; + +} } // Tizen::App + +#endif // _FAPP_INTERNAL_TYPES_H_ diff --git a/src/app/package/FAppPkgPackageAppInfo.cpp b/src/app/package/FAppPkgPackageAppInfo.cpp new file mode 100755 index 0000000..a3114af --- /dev/null +++ b/src/app/package/FAppPkgPackageAppInfo.cpp @@ -0,0 +1,118 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppPkgPackageAppInfo.cpp + * @brief This is the implementation for the PackageAppInfo class. + */ + +#include + +#include + +#include +#include +#include "FAppPkg_PackageAppInfoImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Security; + +namespace Tizen { namespace App { namespace Package +{ + +PackageAppInfo::PackageAppInfo(void) + : __pPackageAppInfoImpl(null) +{ + __pPackageAppInfoImpl = new (std::nothrow) _PackageAppInfoImpl(); + SysTryReturnVoidResult(NID_APP, __pPackageAppInfoImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); +} + +PackageAppInfo::~PackageAppInfo(void) +{ + delete __pPackageAppInfoImpl; +} + +AppId +PackageAppInfo::GetAppId(void) const +{ + return __pPackageAppInfoImpl->GetAppId(); +} + +String +PackageAppInfo::GetAppName(void) const +{ + return __pPackageAppInfoImpl->GetAppName(); +} + +String +PackageAppInfo::GetAppDisplayName(void) const +{ + return __pPackageAppInfoImpl->GetAppDisplayName(); +} + +String +PackageAppInfo::GetAppMenuIconPath(void) const +{ + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGESETTING); + SysTryReturn(NID_APP, r == E_SUCCESS, L"", E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + return __pPackageAppInfoImpl->GetAppMenuIconPath(); +} + +String +PackageAppInfo::GetAppSettingIconPath(void) const +{ + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGESETTING); + SysTryReturn(NID_APP, r == E_SUCCESS, L"", E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + return __pPackageAppInfoImpl->GetAppSettingIconPath(); +} + +String +PackageAppInfo::GetAppNotificationIconPath(void) const +{ + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGESETTING); + SysTryReturn(NID_APP, r == E_SUCCESS, L"", E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + return __pPackageAppInfoImpl->GetAppNotificationIconPath(); +} + +IList* +PackageAppInfo::GetAppCategoryListN(void) const +{ + return __pPackageAppInfoImpl->GetAppCategoryListN(); +} + +bool +PackageAppInfo::IsMenuIconVisible(void) const +{ + return __pPackageAppInfoImpl->IsMenuIconVisible(); +} + +bool +PackageAppInfo::IsMainApp(void) const +{ + return __pPackageAppInfoImpl->IsMainApp(); +} + +}}} // Tizen::App::Package diff --git a/src/app/package/FAppPkgPackageInfo.cpp b/src/app/package/FAppPkgPackageInfo.cpp new file mode 100755 index 0000000..6cef015 --- /dev/null +++ b/src/app/package/FAppPkgPackageInfo.cpp @@ -0,0 +1,162 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppPkgPackageInfo.cpp + * @brief This is the implementation for the PackageInfo class. + */ + +#include + +#include + +#include +#include +#include "FAppPkg_PackageInfoImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Security; + +namespace Tizen { namespace App { namespace Package +{ + +PackageInfo::PackageInfo(void) + : __pPackageInfoImpl(null) +{ + __pPackageInfoImpl = new (std::nothrow) _PackageInfoImpl(); + SysTryReturnVoidResult(NID_APP, __pPackageInfoImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); +} + +PackageInfo::~PackageInfo(void) +{ + delete __pPackageInfoImpl; +} + +PackageId +PackageInfo::GetId(void) const +{ + return __pPackageInfoImpl->GetId(); +} + +String +PackageInfo::GetVersion(void) const +{ + return __pPackageInfoImpl->GetVersion(); +} + +String +PackageInfo::GetDisplayName(void) const +{ + return __pPackageInfoImpl->GetDisplayName(); +} + +String +PackageInfo::GetDescription(void) const +{ + return __pPackageInfoImpl->GetDescription(); +} + +String +PackageInfo::GetAuthor(void) const +{ + return __pPackageInfoImpl->GetAuthor(); +} + +String +PackageInfo::GetUrl(void) const +{ + return __pPackageInfoImpl->GetUrl(); +} + +DateTime +PackageInfo::GetInstallationTime(void) const +{ + return __pPackageInfoImpl->GetInstallationTime(); +} + +bool +PackageInfo::IsInstalledInExternalStorage(void) const +{ + return __pPackageInfoImpl->IsInstalledInExternalStorage(); +} + +bool +PackageInfo::IsUninstallable(void) const +{ + return __pPackageInfoImpl->IsUninstallable(); +} + +bool +PackageInfo::IsMovable(void) const +{ + return __pPackageInfoImpl->IsMovable(); +} + +bool +PackageInfo::IsDownloaded(void) const +{ + return __pPackageInfoImpl->IsDownloaded(); +} + +long long +PackageInfo::GetSize(void) const +{ + return __pPackageInfoImpl->GetSize(); +} + +long long +PackageInfo::GetDataSize(void) const +{ + return __pPackageInfoImpl->GetDataSize(); +} + +AppId +PackageInfo::GetMainAppId(void) const +{ + return __pPackageInfoImpl->GetMainAppId(); +} + +PackageId +PackageInfo::GetStoreClientId(void) const +{ + return __pPackageInfoImpl->GetStoreClientId(); +} + +IList* +PackageInfo::GetPackageAppInfoListN(void) const +{ + return __pPackageInfoImpl->GetPackageAppInfoListN(); +} + +PackageAppInfo* +PackageInfo::GetPackageAppInfoN(const AppId& appId) const +{ + return __pPackageInfoImpl->GetPackageAppInfoN(appId); +} + +PackageType +PackageInfo::GetType(void) const +{ + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGESETTING); + SysTryReturn(NID_APP, r == E_SUCCESS, PACKAGE_TYPE_TPK, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + return __pPackageInfoImpl->GetType(); +} + +}}} // Tizen::App::Package diff --git a/src/app/package/FAppPkgPackageManager.cpp b/src/app/package/FAppPkgPackageManager.cpp new file mode 100755 index 0000000..fb7e9db --- /dev/null +++ b/src/app/package/FAppPkgPackageManager.cpp @@ -0,0 +1,219 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppPkgPackageManager.cpp + * @brief This is the implementation for the PackageManager class. + */ + +#include + +#include +#include + +#include +#include +#include "FAppPkg_PackageManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Security; + +namespace Tizen { namespace App { namespace Package +{ + +PackageManager::PackageManager(void) + : __pPackageManagerImpl(null) +{ + +} + +PackageManager::~PackageManager(void) +{ + delete __pPackageManagerImpl; +} + +PackageId +PackageManager::GetPackageIdByAppId(const AppId& appId) +{ + return _PackageManagerImpl::GetPackageIdByAppId(appId); +} + +result +PackageManager::AddPackageInstallationEventListener(IPackageInstallationEventListener& listener) +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGEINFO); + SysTryReturnResult(NID_APP, r == E_SUCCESS, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + r = __pPackageManagerImpl->AddEventListener(&listener); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "AddEventListener is failed."); + + return r; +} + +result +PackageManager::RemovePackageInstallationEventListener(IPackageInstallationEventListener& listener) +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGEINFO); + SysTryReturnResult(NID_APP, r == E_SUCCESS, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + __pPackageManagerImpl->RemoveEventListener(&listener); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "RemoveEventListener is failed."); + + return r; +} + +PackageInfo* +PackageManager::GetPackageInfoN(const PackageId& packageId) const +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + result r = E_SUCCESS; + PackageInfo* pPackageInfo = null; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGEINFO); + SysTryReturn(NID_APP, r == E_SUCCESS, null, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + pPackageInfo = __pPackageManagerImpl->GetPackageInfoN(packageId); + + return pPackageInfo; +} + +PackageAppInfo* +PackageManager::GetPackageAppInfoN(const AppId& appId) const +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + result r = E_SUCCESS; + PackageAppInfo* pPackageAppInfo = null; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGEINFO); + SysTryReturn(NID_APP, r == E_SUCCESS, null, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + pPackageAppInfo = __pPackageManagerImpl->GetPackageAppInfoN(appId); + + return pPackageAppInfo; +} + +IList* +PackageManager::GetPackageInfoListN(void) const +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGEINFO); + SysTryReturn(NID_APP, r == E_SUCCESS, null, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + return __pPackageManagerImpl->GetPackageInfoListN(); +} + +bool +PackageManager::IsPackageInstalled(const PackageId& packageId) const +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGEINFO); + SysTryReturn(NID_APP, r == E_SUCCESS, false, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + return __pPackageManagerImpl->IsPackageInstalled(packageId); +} + +result +PackageManager::InstallPackage(const PackageId& packageId, const String& packagePath, IPackageInstallationResponseListener* pListener) +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + return __pPackageManagerImpl->InstallPackage(packageId, packagePath, pListener); +} + +result +PackageManager::UninstallPackage(const PackageId& packageId, IPackageUninstallationResponseListener* pListener) +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + return __pPackageManagerImpl->UninstallPackage(packageId, pListener); +} + +result +PackageManager::MoveToExternalStorage(const PackageId& packageId) +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGESETTING); + SysTryReturnResult(NID_APP, r == E_SUCCESS, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + return __pPackageManagerImpl->MoveToExternalStorage(packageId); +} + +result +PackageManager::MoveToInternalStorage(const PackageId& packageId) +{ + SysAssertf(__pPackageManagerImpl != null, "Not yet constructed. GetInstance() should be called before use."); + + result r = E_SUCCESS; + + r = _AccessController::CheckUserPrivilege(_PRV_PACKAGESETTING); + SysTryReturnResult(NID_APP, r == E_SUCCESS, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + return __pPackageManagerImpl->MoveToInternalStorage(packageId); +} + +PackageManager* +PackageManager::GetInstance(void) +{ + static PackageManager* pPackageManager = null; + _PackageManagerImpl* pImpl = null; + result r = E_SUCCESS; + + if (pPackageManager == null) + { + pPackageManager = new (std::nothrow) PackageManager(); + SysTryReturn(NID_APP, pPackageManager != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pPackageManager instance must not be null."); + + pImpl = new (std::nothrow) _PackageManagerImpl(); + SysTryCatch(NID_APP, pImpl != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pImpl instance must not be null."); + + r = pImpl->Construct(); + SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] pPackageManagerImpl construction failed.", GetErrorMessage(r)); + + pPackageManager->__pPackageManagerImpl = pImpl; + } + + return pPackageManager; + +CATCH: + delete pPackageManager; + pPackageManager = null; + + delete pImpl; + + return null; +} + +}}} // Tizen::App::Package diff --git a/src/app/package/FAppPkg_PackageAppInfoImpl.cpp b/src/app/package/FAppPkg_PackageAppInfoImpl.cpp new file mode 100755 index 0000000..9d77809 --- /dev/null +++ b/src/app/package/FAppPkg_PackageAppInfoImpl.cpp @@ -0,0 +1,1240 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppPkg_PackageAppInfoImpl.cpp + * @brief This is the implementation for the _PackageAppInfoImpl class. + */ +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "FAppPkg_PackageManagerImpl.h" +#include "FApp_TemplateUtil.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +namespace Tizen { namespace App { namespace Package +{ + +const AppId& +_PackageAppInfoImpl::GetAppId(void) const +{ + return __appId; +} + +result +_PackageAppInfoImpl::SetAppId(const AppId& appId) +{ + __appId = appId; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetAppName(void) const +{ + return __appName; +} + +result +_PackageAppInfoImpl::SetAppName(const String& appName) +{ + __appName = appName; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetAppDisplayName(void) const +{ + return __appDiplayName; +} + +result +_PackageAppInfoImpl::SetAppDisplayName(const String& appDiplayName) +{ + __appDiplayName = appDiplayName; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetAppMenuIconPath(void) const +{ + return __appIconPath; +} + +result +_PackageAppInfoImpl::SetAppMenuIconPath(const String& iconPath) +{ + __appIconPath = iconPath; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetAppSettingIconPath(void) const +{ + return __appSettingIconPath; +} + +result +_PackageAppInfoImpl::SetAppSettingIconPath(const Tizen::Base::String& appSettingIcon) +{ + __appSettingIconPath = appSettingIcon; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetAppNotificationIconPath(void) const +{ + return __appNotificationIconPath; +} + +result +_PackageAppInfoImpl::SetAppNotificationIconPath(const String& notificationIconPath) +{ + __appNotificationIconPath = notificationIconPath; + return E_SUCCESS; +} + +ArrayList* +_PackageAppInfoImpl::GetAppCategoryListN(void) const +{ + SysTryReturn(NID_APP, __pAppInfoHandle, null, E_SYSTEM, "[E_SYSTEM] __pAppInfoHandle is null."); + + result r = E_SUCCESS; + int res = PMINFO_R_OK; + ArrayList* pList = null; + + pList = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pList, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + pList->Construct(); + + res = pkgmgrinfo_appinfo_foreach_category(__pAppInfoHandle, CategoryHandler, pList); + if (res != PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_foreach_category() is failed. result = [%d]", res); + r = E_SYSTEM; + + pList->RemoveAll(true); + pList = null; + } + + SetLastResult(r); + return pList; +} + +bool +_PackageAppInfoImpl::IsMenuIconVisible(void) const +{ + return __launchingIconVisible; +} + +result +_PackageAppInfoImpl::SetMenuIconVisible(bool visible) +{ + __launchingIconVisible = visible; + return E_SUCCESS; +} + +bool +_PackageAppInfoImpl::IsMainApp(void) const +{ + return __mainApp; +} + +result +_PackageAppInfoImpl::SetMainApp(bool mainApp) +{ + __mainApp = mainApp; + return E_SUCCESS; +} + +_PackageAppInfoImpl* +_PackageAppInfoImpl::GetInstance(PackageAppInfo* pPackageAppInfo) +{ + if (pPackageAppInfo) + { + return pPackageAppInfo->__pPackageAppInfoImpl; + } + + return null; +} + +result +_PackageAppInfoImpl::Construct(const AppId& appId) +{ + int res = PMINFO_R_OK; + char* pExePath = null; + char* pDisplayName = null; + char* pMenuIcon = null; + char* pSettingIcon = null; + char* pNotificationIcon = null; + bool mainApp = false; + bool menuIconVisible = false; + + std::unique_ptr pAppId(_StringConverter::CopyToCharArrayN(appId)); + SysTryReturnResult(NID_APP, pAppId, E_OUT_OF_MEMORY, "pAppId is null"); + + res = pkgmgrinfo_appinfo_get_appinfo(pAppId.get(), &__pAppInfoHandle); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_appinfo_get_appinfo failed, res = [%d]", res); + + SetAppId(appId); + + res = pkgmgrinfo_appinfo_get_exec(__pAppInfoHandle, &pExePath); + if (res == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_exec(): exe = [%s]", pExePath); + + String exePath(pExePath); + int startIndex = exePath.GetLength() - 1; + int indexOf = 0; + result r = exePath.LastIndexOf(L'/', startIndex, indexOf); + if (r == E_SUCCESS) + { + String appName; + exePath.SubString(indexOf + 1, appName); + SetAppName(appName); + SysLog(NID_APP, "appName = [%ls]", appName.GetPointer()); + } + else + { + SysLog(NID_APP, "LastIndexOf is failed."); + } + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_exec() is failed. result = [%d]", res); + } + + res = pkgmgrinfo_appinfo_get_label(__pAppInfoHandle, &pDisplayName); + if (res == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_label(): displayName = [%s]", pDisplayName); + String displayName(pDisplayName); + SetAppDisplayName(displayName); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_label() is failed. result = [%d]", res); + } + + res = pkgmgrinfo_appinfo_get_icon(__pAppInfoHandle, &pMenuIcon); + if (res == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_icon(): MenuIcon = [%s]", pMenuIcon); + String menuIcon(pMenuIcon); + SetAppMenuIconPath(menuIcon); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_icon() is failed. result = [%d]", res); + } + + res = pkgmgrinfo_appinfo_get_setting_icon(__pAppInfoHandle, &pSettingIcon); + if (res == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_setting_icon(): SettingIcon = [%s]", pSettingIcon); + String settingIcon(pSettingIcon); + SetAppSettingIconPath(settingIcon); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_setting_icon() is failed. result = [%d]", res); + } + + res = pkgmgrinfo_appinfo_get_notification_icon(__pAppInfoHandle, &pNotificationIcon); + if (res == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_notification_icon(): NotificationIcon = [%s]", pNotificationIcon); + String notificationIcon(pNotificationIcon); + SetAppSettingIconPath(notificationIcon); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_notification_icon() is failed. result = [%d]", res); + } + + res = pkgmgrinfo_appinfo_is_mainapp(__pAppInfoHandle, &mainApp); + if (res == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_is_mainapp(): mainApp = [%d]", mainApp); + SetMainApp(mainApp); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_is_mainapp() is failed. result = [%d]", res); + } + + res = pkgmgrinfo_appinfo_is_nodisplay(__pAppInfoHandle, &menuIconVisible); + if (res == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_is_nodisplay(): displayName = [%d]", menuIconVisible); + SetMenuIconVisible(!menuIconVisible); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_is_nodisplay() is failed. result = [%d]", res); + } + + return E_SUCCESS; +} + +int +_PackageAppInfoImpl::CategoryHandler(const char* pCategoryName, void* pUserData) +{ + SysTryReturn(NID_APP, pCategoryName != null, 0, E_SYSTEM, "[E_SYSTEM] pCategoryName must not be null."); + + SysLog(NID_APP, "Category = [%s]", pCategoryName); + ArrayList* pList = (ArrayList*) pUserData; + + String* pCategory = new (std::nothrow) String (pCategoryName); + SysTryReturn(NID_APP, pCategory != null, 0, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pCategory instance must not be null."); + + pList->Add(*pCategory); + + return 0; +} + +// to be reviewed +_PackageAppInfoImpl::_PackageAppInfoImpl(void) + : __launchingIconVisible(true) + , __mainApp(false) + , __pLaunchConditionImplList(null) + , __pNotificationImplList(null) + , __pAppFeatureImplList(null) + , __pDataControlImplList(null) + , __pAppControlImplList(null) + , __uniqueId(0) + , __pkgId(0) + , __appFeature(0) + ,__pAppInfoHandle(null) +{ + __pLaunchConditionImplList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pLaunchConditionImplList != null, E_OUT_OF_MEMORY, "__pLaunchConditionImplList instance must not be null."); + __pLaunchConditionImplList->Construct(); + + __pNotificationImplList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pNotificationImplList != null, E_OUT_OF_MEMORY, "__pNotificationImplList instance must not be null."); + __pNotificationImplList->Construct(); + + __pAppFeatureImplList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pAppFeatureImplList != null, E_OUT_OF_MEMORY, "__pAppFeatureImplList instance must not be null."); + __pAppFeatureImplList->Construct(); + + __pDataControlImplList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pDataControlImplList != null, E_OUT_OF_MEMORY, "__pDataControlImplList instance must not be null."); + __pDataControlImplList->Construct(); + + __pAppControlImplList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pAppControlImplList != null, E_OUT_OF_MEMORY, "__pAppControlImplList instance must not be null."); + __pAppControlImplList->Construct(); + + __pNameList = new (std::nothrow) HashMap; + SysTryReturnVoidResult(NID_APP, __pNameList != null, E_OUT_OF_MEMORY, "__pNameList instance must not be null."); + __pNameList->Construct(); + +} + +_PackageAppInfoImpl::~_PackageAppInfoImpl(void) +{ + __pLaunchConditionImplList->RemoveAll(true); + delete __pLaunchConditionImplList; + + __pNotificationImplList->RemoveAll(true); + delete __pNotificationImplList; + + __pAppFeatureImplList->RemoveAll(true); + delete __pAppFeatureImplList; + + __pDataControlImplList->RemoveAll(true); + delete __pDataControlImplList; + + __pAppControlImplList->RemoveAll(true); + delete __pAppControlImplList; + + __pNameList->RemoveAll(true); + delete __pNameList; + + if (__pAppInfoHandle) + { + pkgmgrinfo_appinfo_destroy_appinfo(__pAppInfoHandle); + } +} + +const String& +_PackageAppInfoImpl::GetName(void) const +{ + return __name; +} + +result +_PackageAppInfoImpl::SetName(const String& name) +{ + __name = name; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetType(void) const +{ + return __type; +} + +result +_PackageAppInfoImpl::SetType(const String& type) +{ + __type = type; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetDefault(void) const +{ + return __default; +} + +result +_PackageAppInfoImpl::SetDefault(const String& defaultApp) +{ + __default = defaultApp; + return E_SUCCESS; +} + +ArrayList* +_PackageAppInfoImpl::GetLaunchConditionListN(void) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + //int id = 0; + ArrayList* pList = null; + + query.Format(1024, L"SELECT * FROM LaunchCondition WHERE ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = db.CreateStatementN(query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = db.ExecuteStatementN(*pStmt); + if (pEnum != null) + { + pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _LaunchConditionInfoImpl* pLaunchConditionImpl = new (std::nothrow) _LaunchConditionInfoImpl; + SysTryReturn(NID_APP, pLaunchConditionImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + String name; + String value; + + pEnum->GetStringAt(1, name); + pEnum->GetStringAt(2, value); + + pLaunchConditionImpl->SetName(name); + pLaunchConditionImpl->SetValue(value); + + pList->Add(*pLaunchConditionImpl); + } + delete pEnum; + } + +CATCH: + delete pStmt; + return pList; +} + +ArrayList* +_PackageAppInfoImpl::GetLaunchConditionList(void) const +{ + return __pLaunchConditionImplList; +} + +result +_PackageAppInfoImpl::AddLaunchCondition(const _LaunchConditionInfoImpl& launchConditionImpl) +{ + result r = E_SUCCESS; + r = __pLaunchConditionImplList->Add(launchConditionImpl); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "__pLaunchConditionImplList->Add() is failed."); + + return r; +} + +ArrayList* +_PackageAppInfoImpl::GetNotificationListN(void) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + //int id = 0; + ArrayList* pList = null; + + query.Format(1024, L"SELECT * FROM Notification WHERE ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = db.CreateStatementN(query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = db.ExecuteStatementN(*pStmt); + if (pEnum != null) + { + pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _NotificationInfoImpl* pNotificationImpl = new (std::nothrow) _NotificationInfoImpl; + SysTryReturn(NID_APP, pNotificationImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + String name; + String value; + + pEnum->GetStringAt(1, name); + pEnum->GetStringAt(2, value); + + pNotificationImpl->SetName(name); + pNotificationImpl->SetValue(value); + + pList->Add(*pNotificationImpl); + } + delete pEnum; + } + +CATCH: + delete pStmt; + return pList; +} + +ArrayList* +_PackageAppInfoImpl::GetNotificationList(void) const +{ + return __pNotificationImplList; +} + +result +_PackageAppInfoImpl::AddNotification(const _NotificationInfoImpl& notificationImpl) +{ + result r = E_SUCCESS; + r = __pNotificationImplList->Add(notificationImpl); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "__pNotificationImplList->Add() is failed."); + + return r; +} + +ArrayList* +_PackageAppInfoImpl::GetAppFeatureListN(void) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + //int id = 0; + ArrayList* pList = null; + + query.Format(1024, L"SELECT * FROM AppFeature WHERE ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = db.CreateStatementN(query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = db.ExecuteStatementN(*pStmt); + if (pEnum != null) + { + pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _AppFeatureInfoImpl* pAppFeatureImpl = new (std::nothrow) _AppFeatureInfoImpl; + SysTryReturn(NID_APP, pAppFeatureImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + String name; + String value; + + pEnum->GetStringAt(1, name); + pEnum->GetStringAt(2, value); + + pAppFeatureImpl->SetName(name); + pAppFeatureImpl->SetValue(value); + + pList->Add(*pAppFeatureImpl); + } + delete pEnum; + } + +CATCH: + delete pStmt; + return pList; +} + +ArrayList* +_PackageAppInfoImpl::GetAppFeatureList(void) const +{ + return __pAppFeatureImplList; +} + +HashMapT* +_PackageAppInfoImpl::GetAppFeatureMapN(void) const +{ + result r = E_SUCCESS; + Database db; + DbEnumerator* pEnum = null; + String query; + //int id = 0; + HashMapT* pMap = null; + + query.Format(1024, L"SELECT * FROM AppFeature WHERE ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryReturn(NID_APP, r == E_SUCCESS, null, r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + const DbStatement* pStmt = db.CreateStatementN(query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = db.ExecuteStatementN(*pStmt); + if (pEnum != null) + { + pMap = new (std::nothrow) HashMapT; + SysTryReturn(NID_APP, pMap != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + pMap->Construct(); + + String name; + String value; + + while (pEnum->MoveNext() == E_SUCCESS) + { + _AppFeatureInfoImpl* pAppFeatureImpl = new (std::nothrow) _AppFeatureInfoImpl; + SysTryReturn(NID_APP, pAppFeatureImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + pEnum->GetStringAt(1, name); + pEnum->GetStringAt(2, value); + + pAppFeatureImpl->SetName(name); + pAppFeatureImpl->SetValue(value); + + pMap->Add(name, pAppFeatureImpl); + } + delete pEnum; + } + +CATCH: + delete pStmt; + return pMap; +} + +result +_PackageAppInfoImpl::AddAppFeature(const _AppFeatureInfoImpl& appFeatureImpl) +{ + result r = E_SUCCESS; + r = __pAppFeatureImplList->Add(appFeatureImpl); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "__pAppFeatureImplList->Add() is failed."); + + return r; +} + +ArrayList* +_PackageAppInfoImpl::GetDataControlListN(void) const +{ + return null; +} + +ArrayList* +_PackageAppInfoImpl::GetDataControlList(void) const +{ + return __pDataControlImplList; +} + +result +_PackageAppInfoImpl::AddDataControl(_DataControlInfoImpl* pDataControl) +{ + result r = E_SUCCESS; + r = __pDataControlImplList->Add(*pDataControl); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "__pDataControlImplList->Add() is failed."); + + return r; +} + +ArrayList* +_PackageAppInfoImpl::GetAppControlListN(void) const +{ + return null; +} + +ArrayList* +_PackageAppInfoImpl::GetAppControlList(void) const +{ + return __pAppControlImplList; +} + +result +_PackageAppInfoImpl::AddAppControl(_AppControlInfoImpl* pAppControl) +{ + result r = E_SUCCESS; + r = __pAppControlImplList->Add(*pAppControl); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "__pAppControlImplList->Add() is failed."); + + return r; +} + +const String& +_PackageAppInfoImpl::GetPackageName(void) const +{ + return __packageName; +} + +result +_PackageAppInfoImpl::SetPackageName(const String& packageName) +{ + __packageName = packageName; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetMainmenuIcon(void) const +{ + return __mainmenuIcon; +} + +result +_PackageAppInfoImpl::SetMainmenuIcon(const String& mainmenuIcon) +{ + __mainmenuIcon = mainmenuIcon; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetSettingIcon(void) const +{ + return __settingIcon; +} + +result +_PackageAppInfoImpl::SetSettingIcon(const String& setting) +{ + __settingIcon = setting; + return E_SUCCESS; +} + +const String& +_PackageAppInfoImpl::GetQuickpanelIcon(void) const +{ + return __quickpanelIcon; +} + +result +_PackageAppInfoImpl::SetQuickpanelIcon(const String& quickpanelIcon) +{ + __quickpanelIcon = quickpanelIcon; + return E_SUCCESS; +} + +bool +_PackageAppInfoImpl::IsMainmenuVisible(void) const +{ + return __launchingIconVisible; +} + +result +_PackageAppInfoImpl::SetMainmenuVisible(bool visible) +{ + __launchingIconVisible = visible; + return E_SUCCESS; +} + +result +_PackageAppInfoImpl::AddName(const String& language, const String& name) +{ + result r = E_SUCCESS; + r = __pNameList->Add(language, name); + + return r; +} + +HashMap* +_PackageAppInfoImpl::GetNameList(void) const +{ + return __pNameList; +} + +int +_PackageAppInfoImpl::GetUniqueId(void) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + int uniqueId = 0; + + query.Format(1024, L"SELECT UNIQUE_ID FROM AppInfo WHERE APP_NAME = '%ls' and ID = %d", __name.GetPointer(), __pkgId); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = db.CreateStatementN(query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = db.ExecuteStatementN(*pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetIntAt(0, uniqueId); + } + + delete pEnum; + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + return uniqueId; +} + +int +_PackageAppInfoImpl::GetPkgId(void) const +{ + return __pkgId; +} + +result +_PackageAppInfoImpl::SetUniqueId(int id) +{ + __uniqueId = id; + return E_SUCCESS; +} + +result +_PackageAppInfoImpl::SetPkgId(int id) +{ + __pkgId = id; + return E_SUCCESS; +} + +int +_PackageAppInfoImpl::GetAppFeature(void) const +{ + return __appFeature; +} + +result +_PackageAppInfoImpl::SetAppFeature(int feature) +{ + __appFeature = feature; + return E_SUCCESS; +} + +_LaunchConditionInfoImpl::_LaunchConditionInfoImpl(void) +{ + +} + +_LaunchConditionInfoImpl::~_LaunchConditionInfoImpl(void) +{ + +} + +const String& +_LaunchConditionInfoImpl::GetName(void) const +{ + return __name; +} + +result +_LaunchConditionInfoImpl::SetName(const String& name) +{ + __name = name; + return E_SUCCESS; +} + +const String& +_LaunchConditionInfoImpl::GetValue(void) const +{ + return __value; +} + +result +_LaunchConditionInfoImpl::SetValue(const String& value) +{ + __value = value; + return E_SUCCESS; +} + +_NotificationInfoImpl::_NotificationInfoImpl(void) +{ + +} + +_NotificationInfoImpl::~_NotificationInfoImpl(void) +{ + +} + +const String& +_NotificationInfoImpl::GetName(void) const +{ + return __name; +} + +result +_NotificationInfoImpl::SetName(const String& name) +{ + __name = name; + return E_SUCCESS; +} + +const String& +_NotificationInfoImpl::GetValue(void) const +{ + return __value; +} + +result +_NotificationInfoImpl::SetValue(const String& value) +{ + __value = value; + return E_SUCCESS; +} + +_AppFeatureInfoImpl::_AppFeatureInfoImpl(void) +{ + +} + +_AppFeatureInfoImpl::~_AppFeatureInfoImpl(void) +{ + +} + +const String& +_AppFeatureInfoImpl::GetName(void) const +{ + return __name; +} + +result +_AppFeatureInfoImpl::SetName(const String& name) +{ + __name = name; + return E_SUCCESS; +} + +const String& +_AppFeatureInfoImpl::GetValue(void) const +{ + return __value; +} + +result +_AppFeatureInfoImpl::SetValue(const String& value) +{ + __value = value; + return E_SUCCESS; +} + +_DataControlTypeImpl::_DataControlTypeImpl(void) +{ + +} + +_DataControlTypeImpl::~_DataControlTypeImpl(void) +{ + +} + +const String& +_DataControlTypeImpl::GetType(void) const +{ + return __type; +} + +result +_DataControlTypeImpl::SetType(const String& type) +{ + __type = type; + return E_SUCCESS; +} + +const String& +_DataControlTypeImpl::GetAccess(void) const +{ + return __access; +} + +result +_DataControlTypeImpl::SetAccess(const String& access) +{ + __access = access; + return E_SUCCESS; +} + +_DataControlInfoImpl::_DataControlInfoImpl(void) + : __pControlTypeList(null) +{ + __pControlTypeList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pControlTypeList != null, E_OUT_OF_MEMORY, "__pControlTypeList instance must not be null."); + __pControlTypeList->Construct(); +} + +_DataControlInfoImpl::~_DataControlInfoImpl(void) +{ + __pControlTypeList->RemoveAll(true); + delete __pControlTypeList; +} + +const String& +_DataControlInfoImpl::GetProviderId(void) const +{ + return __providerId; +} + +result +_DataControlInfoImpl::SetProviderId(const String& providerId) +{ + __providerId = providerId; + return E_SUCCESS; +} + +ArrayList* +_DataControlInfoImpl::GetControlTypeList(void) const +{ + return __pControlTypeList; +} + +result +_DataControlInfoImpl::AddControlType(_DataControlTypeImpl* pControlType) +{ + __pControlTypeList->Add(*pControlType); + return E_SUCCESS; +} + +_AppControlResolutionInfoImpl::_AppControlResolutionInfoImpl(void) + : __pUriScheme(null) + , __pMimeType(null) +{ + +} + +_AppControlResolutionInfoImpl::~_AppControlResolutionInfoImpl(void) +{ + delete __pUriScheme; + delete __pMimeType; +} + +String* +_AppControlResolutionInfoImpl::GetUriScheme(void) const +{ + return __pUriScheme; +} + +result +_AppControlResolutionInfoImpl::SetUriScheme(String* pUriScheme) +{ + __pUriScheme = pUriScheme; + return E_SUCCESS; +} + +String* +_AppControlResolutionInfoImpl::GetMimeType(void) const +{ + return __pMimeType; +} + +result +_AppControlResolutionInfoImpl::SetMimeType(String* pMimeType) +{ + __pMimeType = pMimeType; + return E_SUCCESS; +} + +_AppControlCapabilityInfoImpl::_AppControlCapabilityInfoImpl(void) + : __uniqueId(0) + ,__appControlId(0) + ,__pResolutionList(null) +{ + __pResolutionList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pResolutionList != null, E_OUT_OF_MEMORY, "__pResolutionList instance must not be null."); + __pResolutionList->Construct(); +} + +_AppControlCapabilityInfoImpl::~_AppControlCapabilityInfoImpl(void) +{ + __pResolutionList->RemoveAll(true); + delete __pResolutionList; +} + +int +_AppControlCapabilityInfoImpl::GetUniqueId(void) const +{ + return __uniqueId; +} + +result +_AppControlCapabilityInfoImpl::SetUniqueId(int uniqueId) +{ + __uniqueId = uniqueId; + return E_SUCCESS; +} + +int +_AppControlCapabilityInfoImpl::GetAppControlId(void) const +{ + return __appControlId; +} + +result +_AppControlCapabilityInfoImpl::SetAppControlId(int appControlId) +{ + __appControlId = appControlId; + return E_SUCCESS; +} + +const String& +_AppControlCapabilityInfoImpl::GetOperationId(void) const +{ + return __operationId; +} + +result +_AppControlCapabilityInfoImpl::SetOperationId(const String& operationId) +{ + __operationId = operationId; + return E_SUCCESS; +} + +ArrayList* +_AppControlCapabilityInfoImpl::GetResolutionList(void) const +{ + return __pResolutionList; +} + +result +_AppControlCapabilityInfoImpl::AddResolution(_AppControlResolutionInfoImpl* pResolutionImpl) +{ + result r = E_SUCCESS; + r = __pResolutionList->Add(*pResolutionImpl); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "__pResolutionList->Add() is failed."); + + return r; +} + +_AppControlInfoImpl::_AppControlInfoImpl(void) + : __uniqueId(0) + ,__pCapabilityList(null) +{ + __pCapabilityList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pCapabilityList != null, E_OUT_OF_MEMORY, "__pCapabilityList instance must not be null."); + __pCapabilityList->Construct(); +} + +_AppControlInfoImpl::~_AppControlInfoImpl(void) +{ + __pCapabilityList->RemoveAll(true); + delete __pCapabilityList; +} + +int +_AppControlInfoImpl::GetUniqueId(void) const +{ + return __uniqueId; +} + +result +_AppControlInfoImpl::SetUniqueId(int uniqueId) +{ + __uniqueId = uniqueId; + return E_SUCCESS; +} + +const String& +_AppControlInfoImpl::GetProviderId(void) const +{ + return __providerId; +} + +result +_AppControlInfoImpl::SetProviderId(const String& providerId) +{ + __providerId = providerId; + return E_SUCCESS; +} + +const String& +_AppControlInfoImpl::GetCategory(void) const +{ + return __category; +} + +result +_AppControlInfoImpl::SetCategory(const String& category) +{ + __category = category; + return E_SUCCESS; +} + +ArrayList* +_AppControlInfoImpl::GetCapabilityList(void) const +{ + return __pCapabilityList; +} + +result +_AppControlInfoImpl::AddCapability(_AppControlCapabilityInfoImpl* pCapability) +{ + result r = E_SUCCESS; + r = __pCapabilityList->Add(*pCapability); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "__pCapabilityList->Add() is failed."); + + return r; +} + +} } } // Tizen::App::Package diff --git a/src/app/package/FAppPkg_PackageInfoImpl.cpp b/src/app/package/FAppPkg_PackageInfoImpl.cpp new file mode 100755 index 0000000..990323b --- /dev/null +++ b/src/app/package/FAppPkg_PackageInfoImpl.cpp @@ -0,0 +1,1193 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppPkg_PackageInfoImpl.cpp + * @brief This is the implementation for the _PackageInfoImpl class. + */ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "FAppPkg_PackageManagerImpl.h" +#include "FAppPkg_PackageInfoImpl.h" +#include "FAppPkg_PackageAppInfoImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +namespace Tizen { namespace App { namespace Package +{ + +const PackageId& +_PackageInfoImpl::GetId(void) const +{ + return __id; +} + +result +_PackageInfoImpl::SetId(const PackageId& id) +{ + __id = id; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetVersion(void) const +{ + return __version; +} + +result +_PackageInfoImpl::SetVersion(const String& version) +{ + __version = version; + return E_SUCCESS; +} + +PackageType +_PackageInfoImpl::GetType(void) const +{ + return __packageType; +} + +result +_PackageInfoImpl::SetType(PackageType packageType) +{ + __packageType = packageType; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetDisplayName(void) const +{ + return __displayName; +} + +result +_PackageInfoImpl::SetDisplayName(const String& displayName) +{ + __displayName = displayName; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetDescription(void) const +{ + return __description; +} + +result +_PackageInfoImpl::SetDescription(const String& description) +{ + __description = description; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAuthor(void) const +{ + return __author; +} + +result +_PackageInfoImpl::SetAuthor(const String& author) +{ + __author = author; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetUrl(void) const +{ + return __url; +} + +result +_PackageInfoImpl::SetUrl(const String& url) +{ + __url = url; + return E_SUCCESS; +} + +const DateTime& +_PackageInfoImpl::GetInstallationTime(void) const +{ + return __dateTime; +} + +result +_PackageInfoImpl::SetInstallationTime(const DateTime& installationTime) +{ + __dateTime = installationTime; + return E_SUCCESS; +} + +bool +_PackageInfoImpl::IsInstalledInExternalStorage(void) const +{ + return __externalStorage; +} + +result +_PackageInfoImpl::SetInstalledInExternalStorage(bool externalStorage) +{ + __externalStorage = externalStorage; + return E_SUCCESS; +} + +bool +_PackageInfoImpl::IsUninstallable(void) const +{ + return __uninstallable; +} + +result +_PackageInfoImpl::SetUninstallable(bool uninstallable) +{ + __uninstallable = uninstallable; + return E_SUCCESS; +} + +bool +_PackageInfoImpl::IsMovable(void) const +{ + return __movable; +} + +result +_PackageInfoImpl::SetMovable(bool movable) +{ + __movable = movable; + return E_SUCCESS; +} + +bool +_PackageInfoImpl::IsDownloaded(void) const +{ + return __downloaded; +} + +result +_PackageInfoImpl::SetDownloaded(bool downloaded) +{ + __downloaded = downloaded; + return E_SUCCESS; +} + +long long +_PackageInfoImpl::GetSize(void) const +{ + SysTryReturn(NID_APP, __packageInfoHandle, 0, E_SYSTEM, "[E_SYSTEM] __packageInfoHandle is null."); + + int result = PMINFO_R_OK; + int size = 0; + + result = pkgmgrinfo_pkginfo_get_total_size(__packageInfoHandle, &size); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_total_size(): size = [%d]", size); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_total_size() is failed. result = [%d]", result); + } + + return (long long) size; +} + +long long +_PackageInfoImpl::GetDataSize(void) const +{ + SysTryReturn(NID_APP, __packageInfoHandle, 0, E_SYSTEM, "[E_SYSTEM] __packageInfoHandle is null."); + + int result = PMINFO_R_OK; + int dataSize = 0; + + result = pkgmgrinfo_pkginfo_get_data_size(__packageInfoHandle, &dataSize); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_data_size(): dataSize = [%d]", dataSize); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_data_size() is failed. result = [%d]", result); + } + + return (long long) dataSize; +} + +const AppId& +_PackageInfoImpl::GetMainAppId(void) const +{ + return __mainAppId; +} + +result +_PackageInfoImpl::SetMainAppId(const AppId& appId) +{ + __mainAppId = appId; + return E_SUCCESS; +} + +const PackageId& +_PackageInfoImpl::GetStoreClientId(void) const +{ + return __storeClientId; +} + +result +_PackageInfoImpl::SetStoreClientId(const PackageId& packageId) +{ + __storeClientId = packageId; + return E_SUCCESS; +} + +ArrayList* +_PackageInfoImpl::GetPackageAppInfoListN(void) const +{ + SysTryReturn(NID_APP, __packageInfoHandle, null, E_SYSTEM, "[E_SYSTEM] __packageInfoHandle is null."); + + int res = 0; + ArrayList* pList = null; + + pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + pList->Construct(); + + res = pkgmgrinfo_appinfo_get_list(__packageInfoHandle, PMINFO_UI_APP, PackageAppInfoListHandler, (void *)pList); + res = pkgmgrinfo_appinfo_get_list(__packageInfoHandle, PMINFO_SVC_APP, PackageAppInfoListHandler, (void *)pList); + + return pList; +} + +PackageAppInfo* +_PackageInfoImpl::GetPackageAppInfoN(const AppId& appId) const +{ + SysTryReturn(NID_APP, __packageInfoHandle, null, E_SYSTEM, "[E_SYSTEM] __packageInfoHandle is null."); + + int res = 0; + pkgmgrinfo_appinfo_h appInfoHandle = null; + + std::unique_ptr pAppId(_StringConverter::CopyToCharArrayN(appId)); + SysTryReturn(NID_APP, pAppId, null, E_OUT_OF_MEMORY, "pAppId is null"); + + res = pkgmgrinfo_appinfo_get_appinfo(pAppId.get(), &appInfoHandle); + if (res == 0) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_appinfo(): appId = [%s]", pAppId.get()); + + PackageAppInfo* pPackageAppInfo = new (std::nothrow) PackageAppInfo; + SysTryReturn(NID_APP, pPackageAppInfo != null, 0, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + GetPackageAppInfo(appInfoHandle, pPackageAppInfo); + + return pPackageAppInfo; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_appinfo() is failed. result = [%d]", res); + } + + return null; +} + +int +_PackageInfoImpl::PackageAppInfoListHandler(const pkgmgrinfo_appinfo_h handle, void* pUser_data) +{ + ArrayList* pList = (ArrayList*) pUser_data; + + PackageAppInfo* pPackageAppInfo = new (std::nothrow) PackageAppInfo; + SysTryReturn(NID_APP, pPackageAppInfo != null, 0, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + GetPackageAppInfo(handle, pPackageAppInfo); + + pList->Add(*pPackageAppInfo); + + return 0; +} + +bool +_PackageInfoImpl::GetPackageAppInfo(const pkgmgrinfo_appinfo_h handle, PackageAppInfo* pPackageAppInfo) +{ + SysTryReturn(NID_APP, pPackageAppInfo, false, E_INVALID_ARG, "[E_INVALID_ARG] pPackageAppInfo is null."); + + int res = 0; + char* pAppId = null; + + _PackageAppInfoImpl* pPackageAppInfoImpl = _PackageAppInfoImpl::GetInstance(pPackageAppInfo); + + res = pkgmgrinfo_appinfo_get_appid(handle, &pAppId); + if (res == 0) + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_appid(): appId = [%s]", pAppId); + pPackageAppInfoImpl->Construct(pAppId); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_appinfo_get_appid() is failed. result = [%d]", res); + } + + return true; +} + +// to be reviewed +_PackageInfoImpl::_PackageInfoImpl(void) + : __appReadOnlySize(0) + , __appDataSize(0) + , __appStorageType(0) + , __appState(0) + , __certType(0) + , __pAppInfoImplList(null) + , __packageInfoHandle(null) + , __uninstallable(true) + , __movable(false) + , __downloaded(false) + , __iconAvailable(false) + , __externalStorage(false) + , __packageType(PACKAGE_TYPE_TPK) + , __pPackageInfo(null) +{ + __pAppInfoImplList = new (std::nothrow) ArrayList; + SysTryReturnVoidResult(NID_APP, __pAppInfoImplList != null, E_OUT_OF_MEMORY, "__pAppInfoImplList instance must not be null."); + __pAppInfoImplList->Construct(); +} + +_PackageInfoImpl::~_PackageInfoImpl(void) +{ + __pAppInfoImplList->RemoveAll(true); + delete __pAppInfoImplList; + + if (__packageInfoHandle) + { + pkgmgr_pkginfo_destroy_pkginfo(__packageInfoHandle); + } +} + +const String& +_PackageInfoImpl::GetAppId(void) const +{ + return __id; +} + +result +_PackageInfoImpl::SetAppId(const String& id) +{ + __id = id; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppVersion(void) const +{ + return __version; +} + +result +_PackageInfoImpl::SetAppVersion(const String& appVersion) +{ + __version = appVersion; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppType(void) const +{ + return __type; +} + +result +_PackageInfoImpl::SetAppType(const String& appType) +{ + __type = appType; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppMimeType(void) const +{ + return __appMimeType; +} + +result +_PackageInfoImpl::SetAppMimeType(const String& appMimeType) +{ + __appMimeType = appMimeType; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppApiVersion(void) const +{ + return __appApiVersion; +} + +result +_PackageInfoImpl::SetAppApiVersion(const String& appApiVersion) +{ + __appApiVersion = appApiVersion; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppName(void) const +{ + return __displayName; +} + +result +_PackageInfoImpl::SetAppName(const String& appName) +{ + __displayName = appName; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppDescription(void) const +{ + return __description; +} + +result +_PackageInfoImpl::SetAppDescription(const String& appDescription) +{ + __description = appDescription; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppVendor(void) const +{ + return __author; +} + +result +_PackageInfoImpl::SetAppVendor(const String& appVendor) +{ + __author = appVendor; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppUrl(void) const +{ + return __url; +} + +result +_PackageInfoImpl::SetAppUrl(const String& appUrl) +{ + __url = appUrl; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppCid(void) const +{ + return __appCid; +} + +result +_PackageInfoImpl::SetAppCid(const String& appCid) +{ + __appCid = appCid; + return E_SUCCESS; +} + +const String& +_PackageInfoImpl::GetAppRootPath(void) const +{ + return __appRootPath; +} + +result +_PackageInfoImpl::SetAppRootPath(const String& appRootPath) +{ + __appRootPath = appRootPath; + return E_SUCCESS; +} + +int +_PackageInfoImpl::GetAppStorageType(void) const +{ + return __appStorageType; +} + +result +_PackageInfoImpl::SetAppStorageType(int appStorageType) +{ + __appStorageType = appStorageType; + return E_SUCCESS; +} + +int +_PackageInfoImpl::GetCertType(void) const +{ + return __certType; +} + +result +_PackageInfoImpl::SetCertType(int certType) +{ + __certType = certType; + return E_SUCCESS; +} + +ArrayList* +_PackageInfoImpl::GetAppInfoListN(void) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + //int id = 0; + ArrayList* pList = null; + + query.Format(1024, L"SELECT * FROM AppInfo WHERE ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = _PackageManagerImpl::CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = _PackageManagerImpl::ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _PackageAppInfoImpl* pPackageAppInfoImpl = new (std::nothrow) _PackageAppInfoImpl; + SysTryReturn(NID_APP, pPackageAppInfoImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + int uniqueId = 0; + int pkgId = 0; + String name; + String type; + String defaultapp; + String mainmenuIcon; + String settingIcon; + //String tickerIcon; + String quickpanelIcon; + //String launchImageIcon; + int appFeature = 0; + String packageName; + + pEnum->GetIntAt(0, uniqueId); + pEnum->GetIntAt(1, pkgId); + pEnum->GetStringAt(2, name); + pEnum->GetStringAt(3, type); + pEnum->GetStringAt(4, defaultapp); + pEnum->GetStringAt(5, mainmenuIcon); + pEnum->GetStringAt(6, settingIcon); + //pEnum->GetStringAt(7, tickerIcon); + pEnum->GetStringAt(8, quickpanelIcon); + //pEnum->GetStringAt(9, launchImageIcon); + pEnum->GetIntAt(10, appFeature); + pEnum->GetStringAt(11, packageName); + + pPackageAppInfoImpl->SetUniqueId(uniqueId); + pPackageAppInfoImpl->SetPkgId(pkgId); + pPackageAppInfoImpl->SetName(name); + pPackageAppInfoImpl->SetType(type); + pPackageAppInfoImpl->SetDefault(defaultapp); + pPackageAppInfoImpl->SetMainmenuIcon(mainmenuIcon); + pPackageAppInfoImpl->SetSettingIcon(settingIcon); + //pPackageAppInfoImpl->SetTickerIcon(tickerIcon); + pPackageAppInfoImpl->SetQuickpanelIcon(quickpanelIcon); + //pPackageAppInfoImpl->SetLaunchImageIcon(launchImageIcon); + pPackageAppInfoImpl->SetAppFeature(appFeature); + pPackageAppInfoImpl->SetPackageName(packageName); + + pList->Add(*pPackageAppInfoImpl); + } + + delete pEnum; + } + +CATCH: + delete pStmt; + return pList; +} + +ArrayList* +_PackageInfoImpl::GetAppInfoList(void) +{ + if (__pAppInfoImplList == null) + { + __pAppInfoImplList = GetAppInfoListN(); + } + + return __pAppInfoImplList; +} + +result +_PackageInfoImpl::AddAppInfo(const _PackageAppInfoImpl& appInfoImpl) +{ + result r = E_SUCCESS; + r = __pAppInfoImplList->Add(appInfoImpl); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "__pAppInfoImplList->Add() is failed."); + + return r; +} + +result +_PackageInfoImpl::GetPrivileges(String& privileges, String& hmacPrivileges) +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + + query.Format(1024, L"SELECT * FROM PkgPrivileges WHERE ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = _PackageManagerImpl::CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = _PackageManagerImpl::ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetStringAt(1, privileges); + pEnum->GetStringAt(2, hmacPrivileges); + } + + delete pEnum; + pEnum = null; + } + +CATCH: + delete pStmt; + pStmt = null; + return r; +} + +result +_PackageInfoImpl::GetPrivilegesValue(String& privileges, String& hmacPrivileges) const +{ + privileges = __privileges; + hmacPrivileges = __hmacPrivileges; + + return E_SUCCESS; +} + +result +_PackageInfoImpl::SetPrivilegesValue(const String& privileges, const String& hmacPrivileges) +{ + __privileges = privileges; + __hmacPrivileges = hmacPrivileges; + + return E_SUCCESS; +} + +int +_PackageInfoImpl::GetApiVisibility() const +{ + result r = E_SUCCESS; + int apiVisibility = 0; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + + query.Format(1024, L"SELECT CERTIFICATE_TYPE FROM PkgPrivileges WHERE ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, "r"); + SysTryCatch(NID_APP, r == E_SUCCESS, apiVisibility = -1, r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = _PackageManagerImpl::CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, apiVisibility = -1, GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = _PackageManagerImpl::ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + if (pEnum->GetColumnType(0) != DB_COLUMNTYPE_NULL) + { + r = pEnum->GetIntAt(0, apiVisibility); + SysTryCatch(NID_APP, r == E_SUCCESS, apiVisibility = -1, r, "[%s] GetIntAt() is failed.", GetErrorMessage(r)); + } + } + + delete pEnum; + pEnum = null; + } + +CATCH: + delete pStmt; + pStmt = null; + return apiVisibility; +} + +const String& +_PackageInfoImpl::GetAppIconPath(void) const +{ + return __appIconPath; +} + +result +_PackageInfoImpl::SetAppIconPath(const Tizen::Base::String& appIconPath) +{ + __appIconPath = appIconPath; + + return E_SUCCESS; +} + +const DateTime& +_PackageInfoImpl::GetAppInstallationTime(void) const +{ + return __dateTime; +} + +result +_PackageInfoImpl::SetAppInstallationTime(const DateTime& installationTime) +{ + __dateTime = installationTime; + + return E_SUCCESS; +} + +result +_PackageInfoImpl::Construct(const PackageId& packageId) +{ + result r = E_SUCCESS; + int result = 0; + char* pPackage = null; + char* pVersion = null; + char* pName = null; + char* pIconPath = null; + char* pType = null; + char* pDescription = null; + char* pAuthor = null; + char* pUrl = null; + char* pMainAppId = null; + char* pStoreClientId = null; + int installedTime = 0; + pkgmgrinfo_installed_storage storage = PMINFO_INTERNAL_STORAGE; + bool removable = true; + + // temp + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + + std::unique_ptr pPackageId(_StringConverter::CopyToCharArrayN(packageId)); + SysTryReturnResult(NID_APP, pPackageId, E_OUT_OF_MEMORY, "pPackageId is null"); + + result = pkgmgrinfo_pkginfo_get_pkginfo(pPackageId.get(), &__packageInfoHandle); + SysTryReturnResult(NID_APP, result == PMINFO_R_OK, E_PKG_NOT_INSTALLED, "pkgmgrinfo_pkginfo_get_pkginfo() is failed. result=[%d], packageId=[%s]", result, pPackageId.get()); + + result = pkgmgrinfo_pkginfo_get_pkgname(__packageInfoHandle, &pPackage); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_pkgname(): package = [%s]", pPackage); + String package(pPackage); + __id = package; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_pkgname() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_version(__packageInfoHandle, &pVersion); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_version(): version = [%s]", pVersion); + String version(pVersion); + __version = version; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_version() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_type(__packageInfoHandle, &pType); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_type(): type = [%s]", pType); + String type(pType); + __type = type; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_type() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_label(__packageInfoHandle, &pName); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_label(): name = [%s]", pName); + String Name(pName); + __displayName = Name; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_label() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_icon(__packageInfoHandle, &pIconPath); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_icon(): iconpath = [%s]", pIconPath); + String path(pIconPath); + __appIconPath = path; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_icon() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_is_removable(__packageInfoHandle, &removable); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_is_removable(): removable = [%d]", removable); + + if (removable == false) + { + __uninstallable = false; + } + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_is_removable() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_description(__packageInfoHandle, &pDescription); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_description(): description = [%s]", pDescription); + String description(pDescription); + __description = description; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_description() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_author_name(__packageInfoHandle, &pAuthor); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_author_name(): author = [%s]", pAuthor); + String author(pAuthor); + __author = author; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_author_name() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_installed_time(__packageInfoHandle, &installedTime); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_installed_time(): installedTime = [%d]", installedTime); + + time_t dateTime = (time_t) installedTime; + struct tm* pGmTime = null; + + pGmTime = gmtime(&dateTime); + if (pGmTime) + { + DateTime tempTime; + tempTime.SetValue(pGmTime->tm_year + 1900, pGmTime->tm_mon + 1, pGmTime->tm_mday, pGmTime->tm_hour, pGmTime->tm_min, pGmTime->tm_sec); + __dateTime = tempTime; + SysLog(NID_APP, "Time %d %d/%d, %d:%d:%d", tempTime.GetYear(), tempTime.GetMonth(), tempTime.GetDay(), tempTime.GetHour(), tempTime.GetMinute(), tempTime.GetSecond()); + } + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_installed_time() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_installed_storage(__packageInfoHandle, &storage); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_installed_storage(): storage = [%d]", storage); + if (storage == PMINFO_EXTERNAL_STORAGE) + { + __externalStorage = true; + } + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_installed_storage() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_url(__packageInfoHandle, &pUrl); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_url(): url = [%s]", pUrl); + String url(pUrl); + __url = url; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_url() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_mainappid(__packageInfoHandle, &pMainAppId); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_mainappid(): mainAppId = [%s]", pMainAppId); + AppId mainAppId(pMainAppId); + __mainAppId = mainAppId; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_mainappid() is failed. result = [%d]", result); + } + + result = pkgmgrinfo_pkginfo_get_storeclientid(__packageInfoHandle, &pStoreClientId); + if (result == PMINFO_R_OK) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_storeclientid(): storeClientId = [%s]", pStoreClientId); + String storeClientId(pStoreClientId); + __storeClientId = storeClientId; + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_storeclientid() is failed. result = [%d]", result); + } + + // temp + query.Format(1024, L"SELECT PkgInfo.*, AppInfo.APP_MAINMENU_ICON FROM AppInfo, PkgInfo WHERE AppInfo.ID = PkgInfo.UNIQUE_ID and AppInfo.APP_DEFAULT = 'True' and PkgInfo.PKG_ID = '%ls'", packageId.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = _PackageManagerImpl::CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = _PackageManagerImpl::ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + String rootPath; + int storageType; + + pEnum->GetStringAt(16, rootPath); + pEnum->GetIntAt(17, storageType); + + SetAppRootPath(rootPath); + SetAppStorageType(storageType); + } + + delete pEnum; + } + +CATCH: + delete pStmt; + return r; +} + +int +_PackageInfoImpl::GetUniqueId(void) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + int uniqueId = 0; + + query.Format(1024, L"SELECT UNIQUE_ID FROM PkgInfo WHERE PKG_ID = '%ls'", __id.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = _PackageManagerImpl::CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = _PackageManagerImpl::ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetIntAt(0, uniqueId); + } + + delete pEnum; + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + + return uniqueId; +} + +result +_PackageInfoImpl::GetUiScalabilityInfo(String& baseScreenSize, String& coordinateSystem, String& logicalCoordinate) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + + query.Format(1024, + L"SELECT AppFeature.NAME, AppFeature.VALUE FROM AppFeature, AppInfo WHERE AppFeature.ID = AppInfo.UNIQUE_ID and AppInfo.APP_DEFAULT = 'True' and AppInfo.ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = _PackageManagerImpl::CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = _PackageManagerImpl::ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + String name; + String value; + + pEnum->GetStringAt(0, name); + pEnum->GetStringAt(1, value); + + if (name == L"CoordinateSystem") + { + coordinateSystem = value; + } + else if (name == L"BaseScreenSize") + { + baseScreenSize = value; + } + else if (name == L"LogicalCoordinate") + { + logicalCoordinate = value; + } + } + delete pEnum; + } + else + { + r = E_OBJ_NOT_FOUND; + SetLastResult(r); + } + +CATCH: + delete pStmt; + + return r; +} + +// to be removed +const String& +_PackageInfoImpl::GetAppPackageName(void) +{ + if (__appPackageName.IsEmpty() == false) + { + return __appPackageName; + } + + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + + query.Format(1024, L"SELECT AppInfo.PACKAGE_NAME FROM AppInfo WHERE AppInfo.APP_DEFAULT = 'True' and ID = %d", GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = _PackageManagerImpl::CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = _PackageManagerImpl::ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetStringAt(0, __appPackageName); + } + + delete pEnum; + pEnum = null; + } + +CATCH: + delete pStmt; + pStmt = null; + + return __appPackageName; +} + +const String& +_PackageInfoImpl::GetApiVersion(void) const +{ + return __appApiVersion; +} + +const String& +_PackageInfoImpl::GetName(void) const +{ + return __displayName; +} + +_PackageInfoImpl* +_PackageInfoImpl::GetInstance(PackageInfo* pPackageInfo) +{ + if (pPackageInfo) + { + return pPackageInfo->__pPackageInfoImpl; + } + + return null; +} + +const _PackageInfoImpl* +_PackageInfoImpl::GetInstance(const PackageInfo* pPackageInfo) +{ + if (pPackageInfo) + { + return pPackageInfo->__pPackageInfoImpl; + } + + return null; +} + +} } } // Tizen::App::Package diff --git a/src/app/package/FAppPkg_PackageManagerImpl.cpp b/src/app/package/FAppPkg_PackageManagerImpl.cpp new file mode 100755 index 0000000..91d5e0b --- /dev/null +++ b/src/app/package/FAppPkg_PackageManagerImpl.cpp @@ -0,0 +1,2553 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FAppPkg_PackageManagerImpl.cpp + * @brief This is the implementation for the _PackageManagerImpl class. + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "FAppPkg_PackageManagerImpl.h" +#include "FAppPkg_PackageInfoImpl.h" +#include "FAppPkg_PackageAppInfoImpl.h" +#include "FApp_AppInfo.h" +#include "FApp_PackageManagerProxy.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; +using namespace Tizen::System; + +namespace Tizen { namespace App { namespace Package +{ + +PackageManager* pPackageManagerInstance = null; + +Tizen::Base::Collection::HashMap _PackageManagerImpl::__installationList; + +const wchar_t PACKAGE_DATABASE_FILE_NAME[] = L"/opt/usr/dbspace/.app-package.db"; + +void +_PackageManagerEvent::FireImpl(IEventListener& listener, const IEventArg& arg) +{ + IPackageInstallationEventListener* pListener = dynamic_cast (&listener); + SysTryReturnVoidResult(NID_APP, pListener != null, E_OUT_OF_MEMORY, "pListener instance must not be null."); + + const _PackageManagerEventArg* pArg = dynamic_cast(&arg); + SysTryReturnVoidResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "pArg instance must not be null."); + + if (pArg->__eventKey == L"end") + { + if (pArg->__eventValue == L"ok") + { + if (pArg->__install) + { + SysLog(NID_APP, "Installation is Completed. [PackageId = %ls]", pArg->__packageId.GetPointer()); + pListener->OnPackageInstallationCompleted(pArg->__packageId, PACKAGE_INSTALLATION_RESULT_SUCCESS); + } + else + { + SysLog(NID_APP, "Uninstallation is Completed. [PackageId = %ls]", pArg->__packageId.GetPointer()); + pListener->OnPackageUninstallationCompleted(pArg->__packageId, true); + } + } + else + { + if (pArg->__install) + { + SysLog(NID_APP, "Installation is Completed(Error). [PackageId = %ls]", pArg->__packageId.GetPointer()); + pListener->OnPackageInstallationCompleted(pArg->__packageId, PACKAGE_INSTALLATION_RESULT_INVALID_PACKAGE); + } + else + { + SysLog(NID_APP, "Uninstallation is Completed(Error). [PackageId = %ls]", pArg->__packageId.GetPointer()); + pListener->OnPackageUninstallationCompleted(pArg->__packageId, false); + } + } + } + else if (pArg->__eventKey == L"install_percent") + { + std::unique_ptr pProgress(_StringConverter::CopyToCharArrayN(pArg->__eventValue)); + + int progress = 0; + sscanf(pProgress.get(), "%d", &progress); + + SysLog(NID_APP, "InstallationInProgress [%d]", progress); + pListener->OnPackageInstallationInProgress(pArg->__packageId, progress); + } +} + +PackageId +_PackageManagerImpl::GetPackageIdByAppId(const AppId& appId) +{ + SysTryReturn(NID_APP, appId.IsEmpty() == false, L"", E_INVALID_ARG, "appId is empty"); + + String packageId; + + if (appId.StartsWith(L".", 10) == true) + { + appId.SubString(0, 10, packageId); + } + else + { + int result = 0; + char* pPackageId = null; + pkgmgrinfo_appinfo_h pAppInfoHandle = null; + + std::unique_ptr pAppId(_StringConverter::CopyToCharArrayN(appId)); + SysTryReturn(NID_APP, pAppId, L"", E_OUT_OF_MEMORY, "pAppId is null"); + + result = pkgmgrinfo_appinfo_get_appinfo(pAppId.get(), &pAppInfoHandle); + SysTryReturn(NID_APP, result == 0, L"", E_PKG_NOT_INSTALLED, "pkgmgrinfo_appinfo_get_appinfo() failed. result=[%d], appId=[%s]", result, pAppId.get()); + + result = pkgmgrinfo_appinfo_get_pkgname(pAppInfoHandle, &pPackageId); + + packageId.Append(pPackageId); + + if(pAppInfoHandle) + { + pkgmgrinfo_appinfo_destroy_appinfo(pAppInfoHandle); + } + } + + SysLog(NID_APP, "appId = [%ls], packageId = [%ls]", appId.GetPointer(), packageId.GetPointer()); + + return packageId; +} + +result +_PackageManagerImpl::AddEventListener(IPackageInstallationEventListener* pListener, int priority) +{ + SysTryReturnResult(NID_APP, (priority < 3) && (priority >= 0), E_INVALID_ARG, "priority is invalid."); + + result r = E_SUCCESS; + int res = 0; + + std::unique_ptr< IEnumeratorT<_PackageManagerEvent*> > pEnum(__packageEventListenerList.GetEnumeratorN()); + SysTryReturnResult(NID_APP, pEnum, E_OUT_OF_MEMORY, "The memory is insufficient."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _PackageManagerEvent* pEvent = null; + pEnum->GetCurrent(pEvent); + if (pEvent) + { + if (pEvent->__pListener == pListener) + { + SysLog(NID_APP, "The event listener already exist. listener = [0x%x]", pListener); + return E_OBJ_ALREADY_EXIST; + } + } + } + + if (__pListeningClient == null) + { + __pListeningClient = pkgmgr_client_new(PC_LISTENING); + SysTryReturnResult(NID_APP, __pListeningClient != null, E_SYSTEM, "pkgmgr_client_new(PC_LISTENING) failed"); + + res = pkgmgr_client_listen_status(__pListeningClient, PackageEventHandler, this); + if (res < PKGMGR_R_OK) + { + pkgmgr_client_free(__pListeningClient); + __pListeningClient = null; + + if (res == PKGMGR_R_EINVAL) + { + SysLog(NID_APP, "pkgmgr_client_listen_status() returns ARGV error"); + return E_INVALID_ARG; + } + else if (res == PKGMGR_R_ECOMM) + { + SysLog(NID_APP, "pkgmgr_client_listen_status() returns COMM error"); + } + else if (res == PKGMGR_R_ETIMEOUT) + { + SysLog(NID_APP, "pkgmgr_client_listen_status() returns TIME_OUT error"); + } + else if (res == PKGMGR_R_ERROR) + { + SysLog(NID_APP, "pkgmgr_client_listen_status() returns Unknown error"); + } + else + { + SysLog(NID_APP, "pkgmgr_client_listen_status() returns Unknown error, res = %d", res); + } + + return E_SYSTEM; + } + } + + _PackageManagerEvent* pEvent = new (std::nothrow) _PackageManagerEvent(); + SysTryReturnResult(NID_APP, pEvent != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pEvent->Construct(); + SysTryReturnResult(NID_APP, r == E_SUCCESS, E_SYSTEM, "pEvent->Construct() failed."); + + pEvent->__pListener = pListener; + + r = pEvent->AddListener(*pListener, true); + SysTryReturnResult(NID_APP, r == E_SUCCESS, r, "pEvent->AddListener() failed. [%s]", GetErrorMessage(r)); + + r = __packageEventListenerList.Add(pEvent); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "[%s] Propagating.", GetErrorMessage(r)); + + SysLog(NID_APP, "Add PackageInstallationEventListener = [0x%x]", pListener); + return E_SUCCESS; +} + +result +_PackageManagerImpl::RemoveEventListener(IPackageInstallationEventListener* pListener) +{ + std::unique_ptr< IEnumeratorT<_PackageManagerEvent*> > pEnum(__packageEventListenerList.GetEnumeratorN()); + SysTryReturnResult(NID_APP, pEnum, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = E_SUCCESS; + + while (pEnum->MoveNext() == E_SUCCESS) + { + _PackageManagerEvent* pEvent = null; + pEnum->GetCurrent(pEvent); + if (pEvent) + { + if (pEvent->__pListener == pListener) + { + r = __packageEventListenerList.Remove(pEvent); + SysTryReturnResult(NID_APP, !IsFailed(r), r, "[%s] Propagating.", GetErrorMessage(r)); + + delete pEvent; + + SysLog(NID_APP, "Remove PackageInstallationEventListener = [0x%x]", pListener); + return E_SUCCESS; + } + } + } + + return E_OBJ_NOT_FOUND; +} + +PackageInfo* +_PackageManagerImpl::GetPackageInfoN(const PackageId& packageId) const +{ + SysTryReturn(NID_APP, packageId.IsEmpty() == false, null, E_INVALID_ARG, "[E_INVALID_ARG] packageId is empty."); + SysTryReturn(NID_APP, packageId.GetLength() < NATIVE_APP_MAX_APPID_LENGTH, null, E_INVALID_ARG, "packageId is invalid.(length)"); + + result r = E_SUCCESS; + PackageInfo* pPackageInfo = null; + + pPackageInfo = new (std::nothrow) PackageInfo; + SysTryReturn(NID_APP, pPackageInfo != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pPackageInfo instance must not be null."); + + _PackageInfoImpl* pPackageInfoImpl = _PackageInfoImpl::GetInstance(pPackageInfo); + r = pPackageInfoImpl->Construct(packageId); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[E_PKG_NOT_INSTALLED] packageId (%ls) is not found.", packageId.GetPointer()); + + return pPackageInfo; + +CATCH: + delete pPackageInfo; + return null; +} + +PackageAppInfo* +_PackageManagerImpl::GetPackageAppInfoN(const AppId& appId) const +{ + SysTryReturn(NID_APP, appId.IsEmpty() == false, null, E_INVALID_ARG, "[E_INVALID_ARG] appId is empty."); + + result r = E_SUCCESS; + PackageAppInfo* pPackageAppInfo = null; + + pPackageAppInfo = new (std::nothrow) PackageAppInfo; + SysTryReturn(NID_APP, pPackageAppInfo != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pPackageAppInfo instance must not be null."); + + _PackageAppInfoImpl* pPackageAppInfoImpl = _PackageAppInfoImpl::GetInstance(pPackageAppInfo); + r = pPackageAppInfoImpl->Construct(appId); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[E_PKG_NOT_INSTALLED] appId (%ls) is not found.", appId.GetPointer()); + + return pPackageAppInfo; + +CATCH: + delete pPackageAppInfo; + return null; +} + +IList* +_PackageManagerImpl::GetPackageInfoListN(void) const +{ + result r = E_SUCCESS; + int res = 0; + ArrayList* pList = null; + + pList = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + pList->Construct(); + + res = pkgmgrinfo_pkginfo_get_list(PackageInfoEventHandler, pList); + if (res != 0) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_list() is failed. result = [%d]", res); + + pList->RemoveAll(true); + pList = null; + } + + SetLastResult(r); + return pList; +} + +bool +_PackageManagerImpl::IsPackageInstalled(const PackageId& packageId) const +{ + SysTryReturn(NID_APP, packageId.IsEmpty() == false, false, E_INVALID_ARG, "packageId is empty"); + + int result = 0; + pkgmgrinfo_pkginfo_h pPackageInfoHandle = null; + + std::unique_ptr pPackageId(_StringConverter::CopyToCharArrayN(packageId)); + SysTryReturn(NID_APP, pPackageId, false, E_OUT_OF_MEMORY, "pPackageId is null"); + + result = pkgmgrinfo_pkginfo_get_pkginfo(pPackageId.get(), &pPackageInfoHandle); + if (result != 0) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_pkginfo() failed. result=[%d], packageId=[%s]", result, pPackageId.get()); + return false; + } + + if(pPackageInfoHandle) + { + pkgmgrinfo_pkginfo_destroy_pkginfo(pPackageInfoHandle); + } + + SysLog(NID_APP, "packageId = [%ls] is installed.", packageId.GetPointer()); + + return true; +} + +result +_PackageManagerImpl::InstallPackage(const PackageId& packageId, const String& packagePath, IPackageInstallationResponseListener* pListener) +{ + SysTryReturnResult(NID_APP, packageId.IsEmpty() == false, E_INVALID_ARG, "packageId is empty."); + SysTryReturnResult(NID_APP, packagePath.IsEmpty() == false, E_INVALID_ARG, "packagePath is empty."); + SysTryReturnResult(NID_APP, File::IsFileExist(packagePath) == true, E_FILE_NOT_FOUND, "packagePath is not existed."); + + String extension = File::GetFileExtension(packagePath); + SysTryReturnResult(NID_APP, extension.IsEmpty() == false, E_INVALID_ARG, "extension is empty."); + + std::unique_ptr pPackagePath(_StringConverter::CopyToCharArrayN(packagePath)); + SysTryReturnResult(NID_APP, pPackagePath, E_OUT_OF_MEMORY, "pPackagePath is null"); + + std::unique_ptr pExtension(_StringConverter::CopyToCharArrayN(extension)); + SysTryReturnResult(NID_APP, pExtension, E_OUT_OF_MEMORY, "pExtension is null"); + + if ((strcasecmp(pExtension.get(), "tpk") == 0) || (strcasecmp(pExtension.get(), "wgt") == 0)) + { + SysLog(NID_APP, "packageId = [%ls], packagePath = [%s], extension = [%s]", packageId.GetPointer(), pPackagePath.get(), pExtension.get()); + } + else + { + SysLog(NID_APP, "invalid extension! - packagePath = [%s], extension = [%s]", pPackagePath.get(), pExtension.get()); + return E_SYSTEM; + } + + result r = E_SUCCESS; + _PackageManagerProxy packageManagerProxy; + r = packageManagerProxy.Construct(); + SysTryReturnResult(NID_APP, r == E_SUCCESS, E_SYSTEM, "packageManagerProxy.Construct() failed."); + + r = packageManagerProxy.InstallPackage(packageId, packagePath, null); + SysTryReturnResult(NID_APP, r == E_SUCCESS, r, "packageManagerProxy.InstallPackage() failed."); + + if (__pRequestClient == null) + { + __pRequestClient = pkgmgr_client_new(PC_REQUEST); + SysTryReturnResult(NID_APP, __pRequestClient != null, E_SYSTEM, "pkgmgr_client_new(PC_REQUEST) failed"); + } + + int res = pkgmgr_client_install(__pRequestClient, pExtension.get(), null, pPackagePath.get(), null, PM_QUIET, InstallationEventHandler, pListener); + + if (res < PKGMGR_R_OK) + { + pkgmgr_client_free(__pRequestClient); + __pRequestClient = null; + + if (res == PKGMGR_R_EINVAL) + { + SysLog(NID_APP, "pkgmgr_client_install() returns ARGV error"); + return E_INVALID_ARG; + } + else if (res == PKGMGR_R_ECOMM) + { + SysLog(NID_APP, "pkgmgr_client_install() returns COMM error"); + } + else if (res == PKGMGR_R_ETIMEOUT) + { + SysLog(NID_APP, "pkgmgr_client_install() returns TIME_OUT error"); + } + else if (res == PKGMGR_R_ERROR) + { + SysLog(NID_APP, "pkgmgr_client_install() returns Unknown error"); + } + else + { + SysLog(NID_APP, "pkgmgr_client_install() returns Unknown error, res = %d", res); + } + + return E_SYSTEM; + } + + return E_SUCCESS; +} + +result +_PackageManagerImpl::UninstallPackage(const PackageId& packageId, IPackageUninstallationResponseListener* pListener) +{ + SysTryReturnResult(NID_APP, packageId.IsEmpty() == false, E_INVALID_ARG, "packageId is empty."); + SysTryReturnResult(NID_APP, packageId.GetLength() < NATIVE_APP_MAX_APPID_LENGTH, E_INVALID_ARG, "The packageId is invalid.(length)"); + SysTryReturnResult(NID_APP, IsPackageInstalled(packageId) == true, E_PKG_NOT_INSTALLED, "package is not installed."); + + result r = E_SUCCESS; + int res = 0; + char* pType = null; + pkgmgrinfo_pkginfo_h pPackageInfoHandle = null; + + _PackageManagerProxy packageManagerProxy; + r = packageManagerProxy.Construct(); + SysTryReturnResult(NID_APP, r == E_SUCCESS, E_SYSTEM, "packageManagerProxy.Construct() failed."); + + r = packageManagerProxy.UninstallPackage(packageId, pListener); + SysTryReturnResult(NID_APP, r == E_SUCCESS, r, "packageManagerProxy.UninstallPackage() failed."); + + std::unique_ptr pPackageId(_StringConverter::CopyToCharArrayN(packageId)); + SysTryReturnResult(NID_APP, pPackageId != null, E_OUT_OF_MEMORY, "pPackageId is null"); + + res = pkgmgrinfo_pkginfo_get_pkginfo(pPackageId.get(), &pPackageInfoHandle); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_pkginfo_get_pkginfo() failed. result=[%d], packageId=[%s]", res, pPackageId.get()); + + res = pkgmgrinfo_pkginfo_get_type(pPackageInfoHandle, &pType); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_pkginfo_get_type() failed. result=[%d], packageId=[%s]", res, pPackageId.get()); + + if (__pRequestClient == null) + { + __pRequestClient = pkgmgr_client_new(PC_REQUEST); + SysTryReturnResult(NID_APP, __pRequestClient != null, E_SYSTEM, "pkgmgr_client_new(PC_REQUEST) failed"); + } + + res = pkgmgr_client_uninstall(__pRequestClient, pType, pPackageId.get(), PM_QUIET, UninstallationEventHandler, pListener); + SysLog(NID_APP, "pkgmgr_client_uninstall - req_id=[%d], packageId=[%s], type=[%s]", res, pPackageId.get(), pType); + + if(pPackageInfoHandle) + { + pkgmgrinfo_pkginfo_destroy_pkginfo(pPackageInfoHandle); + } + + if (res < PKGMGR_R_OK) + { + pkgmgr_client_free(__pRequestClient); + __pRequestClient = null; + + if (res == PKGMGR_R_EINVAL) + { + SysLog(NID_APP, "pkgmgr_client_uninstall() returns ARGV error"); + return E_INVALID_ARG; + } + else if (res == PKGMGR_R_ECOMM) + { + SysLog(NID_APP, "pkgmgr_client_uninstall() returns COMM error"); + } + else if (res == PKGMGR_R_ETIMEOUT) + { + SysLog(NID_APP, "pkgmgr_client_uninstall() returns TIME_OUT error"); + } + else if (res == PKGMGR_R_ERROR) + { + SysLog(NID_APP, "pkgmgr_client_uninstall() returns Unknown error"); + } + else + { + SysLog(NID_APP, "pkgmgr_client_uninstall() returns Unknown error, res = %d", res); + } + + return E_SYSTEM; + } + + return E_SUCCESS; +} + +result +_PackageManagerImpl::MoveToExternalStorage(const PackageId& packageId) +{ + SysTryReturnResult(NID_APP, packageId.IsEmpty() == false, E_INVALID_ARG, "packageId is empty"); + SysTryReturnResult(NID_APP, IsPackageInstalled(packageId) == true, E_PKG_NOT_INSTALLED, "package is not installed."); + +#if defined(_OSP_EMUL_) + SysLog(NID_APP, "MoveToExternalStorage() is unavailable on the emulator."); + return E_SYSTEM; +#else + int res = 0; + char* pType = null; + pkgmgrinfo_installed_storage storage = PMINFO_INTERNAL_STORAGE; + pkgmgrinfo_pkginfo_h packageInfoHandle = null; + + std::unique_ptr pPackageId(_StringConverter::CopyToCharArrayN(packageId)); + SysTryReturnResult(NID_APP, pPackageId != null, E_OUT_OF_MEMORY, "pPackageId is null"); + + res = pkgmgrinfo_pkginfo_get_pkginfo(pPackageId.get(), &packageInfoHandle); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_pkginfo_get_pkginfo() failed. result=[%d], packageId=[%s]", res, pPackageId.get()); + + res = pkgmgrinfo_pkginfo_get_type(packageInfoHandle, &pType); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_pkginfo_get_type() failed. result=[%d], packageId=[%s]", res, pPackageId.get()); + + res = pkgmgrinfo_pkginfo_get_installed_storage(packageInfoHandle, &storage); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_pkginfo_get_installed_storage() failed. result=[%d], packageId=[%s]", res, pPackageId.get()); + + if (storage == PMINFO_EXTERNAL_STORAGE) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_installed_storage(): storage = [%d][E_INVALID_OPERATION]", storage); + return E_INVALID_OPERATION; + } + + if (__pRequestClient == null) + { + __pRequestClient = pkgmgr_client_new(PC_REQUEST); + SysTryReturnResult(NID_APP, __pRequestClient != null, E_SYSTEM, "pkgmgr_client_new(PC_REQUEST) failed"); + } + + res = pkgmgr_client_move(__pRequestClient, pType, pPackageId.get(), PM_MOVE_TO_SDCARD, PM_QUIET); + + if(packageInfoHandle) + { + pkgmgrinfo_pkginfo_destroy_pkginfo(packageInfoHandle); + } + + if (res < PKGMGR_R_OK) + { + pkgmgr_client_free(__pRequestClient); + __pRequestClient = null; + + if (res == PKGMGR_R_EINVAL) + { + SysLog(NID_APP, "pkgmgr_client_move() returns ARGV error"); + return E_INVALID_ARG; + } + else if (res == PKGMGR_R_ERROR) + { + SysLog(NID_APP, "pkgmgr_client_move() returns Unknown error"); + } + else + { + SysLog(NID_APP, "pkgmgr_client_move() returns Unknown error, res = %d", res); + } + + return E_SYSTEM; + } + + return E_SUCCESS; +#endif +} + +result +_PackageManagerImpl::MoveToInternalStorage(const PackageId& packageId) +{ + SysTryReturnResult(NID_APP, packageId.IsEmpty() == false, E_INVALID_ARG, "packageId is empty"); + SysTryReturnResult(NID_APP, IsPackageInstalled(packageId) == true, E_PKG_NOT_INSTALLED, "package is not installed."); + +#if defined(_OSP_EMUL_) + SysLog(NID_APP, "MoveToInternalStorage() is unavailable on the emulator."); + return E_SYSTEM; +#else + int res = 0; + char* pType = null; + pkgmgrinfo_installed_storage storage = PMINFO_INTERNAL_STORAGE; + pkgmgrinfo_pkginfo_h packageInfoHandle = null; + + std::unique_ptr pPackageId(_StringConverter::CopyToCharArrayN(packageId)); + SysTryReturnResult(NID_APP, pPackageId != null, E_OUT_OF_MEMORY, "pPackageId is null"); + + res = pkgmgrinfo_pkginfo_get_pkginfo(pPackageId.get(), &packageInfoHandle); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_pkginfo_get_pkginfo() failed. result=[%d], packageId=[%s]", res, pPackageId.get()); + + res = pkgmgrinfo_pkginfo_get_type(packageInfoHandle, &pType); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_pkginfo_get_type() failed. result=[%d], packageId=[%s]", res, pPackageId.get()); + + res = pkgmgrinfo_pkginfo_get_installed_storage(packageInfoHandle, &storage); + SysTryReturnResult(NID_APP, res == 0, E_SYSTEM, "pkgmgrinfo_pkginfo_get_installed_storage() failed. result=[%d], packageId=[%s]", res, pPackageId.get()); + + if (storage == PMINFO_INTERNAL_STORAGE) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_installed_storage(): storage = [%d][E_INVALID_OPERATION]", storage); + return E_INVALID_OPERATION; + } + + if (__pRequestClient == null) + { + __pRequestClient = pkgmgr_client_new(PC_REQUEST); + SysTryReturnResult(NID_APP, __pRequestClient != null, E_SYSTEM, "pkgmgr_client_new(PC_REQUEST) failed"); + } + + res = pkgmgr_client_move(__pRequestClient, pType, pPackageId.get(), PM_MOVE_TO_INTERNAL, PM_QUIET); + + if(packageInfoHandle) + { + pkgmgrinfo_pkginfo_destroy_pkginfo(packageInfoHandle); + } + + if (res < PKGMGR_R_OK) + { + pkgmgr_client_free(__pRequestClient); + __pRequestClient = null; + + if (res == PKGMGR_R_EINVAL) + { + SysLog(NID_APP, "pkgmgr_client_move() returns ARGV error"); + return E_INVALID_ARG; + } + else if (res == PKGMGR_R_ERROR) + { + SysLog(NID_APP, "pkgmgr_client_move() returns Unknown error"); + } + else + { + SysLog(NID_APP, "pkgmgr_client_move() returns Unknown error, res = %d", res); + } + + return E_SYSTEM; + } + + return E_SUCCESS; +#endif +} + +int +_PackageManagerImpl::InstallationEventHandler(int reqId, const char* pType, const char* pPackageId, const char* pKey, const char* pVal, const void* pMsg, void* pData) +{ + SysLog(NID_APP, "reqId[%d], Type[%s], PackageId[%s], Key[%s], Val[%s]", reqId, pType, pPackageId, pKey, pVal); + + if (pData) + { + if (strcmp(pKey, "end") == 0) + { + IPackageInstallationResponseListener* pListener = (IPackageInstallationResponseListener*) pData; + + if (strcmp(pVal, "ok") == 0) + { + pListener->OnPackageInstallationResponseReceived(pPackageId, PACKAGE_INSTALLATION_RESULT_SUCCESS); + SysLog(NID_APP, "OnPackageInstallationResponseReceived(PACKAGE_INSTALLATION_RESULT_SUCCESS)"); + } + else + { + pListener->OnPackageInstallationResponseReceived(pPackageId, PACKAGE_INSTALLATION_RESULT_INVALID_PACKAGE); + SysLog(NID_APP, "OnPackageInstallationResponseReceived(PACKAGE_INSTALLATION_RESULT_INVALID_PACKAGE)"); + } + + delete pListener; + } + } + + return 0; +} + +int +_PackageManagerImpl::UninstallationEventHandler(int reqId, const char* pType, const char* pPackageId, const char* pKey, const char* pVal, const void* pMsg, void* pData) +{ + SysLog(NID_APP, "reqId[%d], Type[%s], PackageId[%s], Key[%s], Val[%s]", reqId, pType, pPackageId, pKey, pVal); + + if (pData) + { + if (strcmp(pKey, "end") == 0) + { + IPackageUninstallationResponseListener* pListener = (IPackageUninstallationResponseListener*) pData; + + if (strcmp(pVal, "ok") == 0) + { + SysLog(NID_APP, "OnPackageUninstallationResponseReceived(true)"); + pListener->OnPackageUninstallationResponseReceived(pPackageId, true); + } + else + { + SysLog(NID_APP, "OnPackageUninstallationResponseReceived(false)"); + pListener->OnPackageUninstallationResponseReceived(pPackageId, false); + } + + delete pListener; + } + } + + return 0; +} + +_PackageManagerImpl* +_PackageManagerImpl::GetInstance(void) +{ + return PackageManager::GetInstance()->__pPackageManagerImpl; +} + +result +_PackageManagerImpl::Construct(void) +{ + ClearLastResult(); + + result r = __installationList.Construct(); + SysTryReturnResult(NID_APP, r == E_SUCCESS, r, "The memory is insufficient."); + + return E_SUCCESS; +} + +_PackageManagerImpl::_PackageManagerImpl(void) +:__pRequestClient(null), +__pListeningClient(null), +__pDb(null) +{ + CreatePackageTables(); +} + +_PackageManagerImpl::~_PackageManagerImpl(void) +{ +} + +void +_PackageManagerImpl::SendPackageEvent(PackageType type, const PackageId& packageId, const char* pEventKey, const char* pEventValue) +{ + result r = E_SUCCESS; + bool install = true; + + if (strcmp(pEventKey, "start") == 0) + { + if ((strcmp(pEventValue, "install") == 0) || (strcmp(pEventValue, "uninstall") == 0)) + { + String* pAppId = new (std::nothrow) String(packageId); + SysTryReturnVoidResult(NID_APP, pAppId != null, E_OUT_OF_MEMORY, "pAppId instance must not be null."); + + String* pOperation = new (std::nothrow) String(pEventValue); + SysTryReturnVoidResult(NID_APP, pOperation != null, E_OUT_OF_MEMORY, "pOperation instance must not be null."); + + r = __installationList.Add(*pAppId, *pOperation); + if (IsFailed(r)) + { + delete pAppId; + delete pOperation; + SysLog(NID_APP, "Failed to add installation condition."); + SetLastResult(E_SYSTEM); + return; + } + } + } + else if (strcmp(pEventKey, "end") == 0) + { + String* pOperation = static_cast (__installationList.GetValue(packageId)); + if (pOperation) + { + if (pOperation->Equals("uninstall", true) == true) + { + install = false; + } + + r = __installationList.Remove(packageId, true); + if (IsFailed(r)) + { + SysLogException(NID_APP, r, "[%s] Remove Element [%ls] is failed from installing list.", GetErrorMessage(r), packageId.GetPointer()); + } + } + } + + std::unique_ptr< IEnumeratorT<_PackageManagerEvent*> > pEnum(__packageEventListenerList.GetEnumeratorN()); + SysTryReturnVoidResult(NID_APP, pEnum, E_OUT_OF_MEMORY, "The memory is insufficient."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _PackageManagerEvent* pEvent = null; + pEnum->GetCurrent(pEvent); + if (pEvent) + { + _PackageManagerEventArg* pEventArg= new (std::nothrow) _PackageManagerEventArg(); + SysTryReturnVoidResult(NID_APP, pEventArg, E_OUT_OF_MEMORY, "The memory is insufficient."); + + String eventKey(pEventKey); + String eventValue(pEventValue); + + pEventArg->__packageId = packageId; + pEventArg->__eventKey = eventKey; + pEventArg->__eventValue = eventValue; + pEventArg->__install = install; + + r = pEvent->Fire(*pEventArg); + if (r != E_SUCCESS) + { + SysLog(NID_APP, "pEvent->Fire(*pEventArg) failed. [%s]", GetErrorMessage(r)); + } + + SysLog(NID_APP, "PackageId = [%ls], Key = [%ls], Value = [%ls], install = [%d]", pEventArg->__packageId.GetPointer(), pEventArg->__eventKey.GetPointer(), pEventArg->__eventValue.GetPointer(), pEventArg->__install); + } + else + { + SysLog(NID_APP, "pEvent is null."); + } + } +} + +PackageInfo* +_PackageManagerImpl::GetPackageInfoN(PackageType packageType, const String& packageName) const +{ + SysTryReturn(NID_APP, packageName.IsEmpty() == false, null, E_INVALID_ARG, "[E_INVALID_ARG] packageName is empty."); + + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + PackageInfo *pPackageInfo = null; + + query.Format( 1024, L"SELECT PkgInfo.*, AppInfo.APP_MAINMENU_ICON FROM AppInfo, PkgInfo WHERE AppInfo.ID = PkgInfo.UNIQUE_ID and AppInfo.PACKAGE_NAME = '%ls'", packageName.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pPackageInfo = new (std::nothrow) PackageInfo; + SysTryReturn(NID_APP, pPackageInfo != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pPackageInfo instance must not be null."); + + _PackageInfoImpl* pPackageInfoImpl = _PackageInfoImpl::GetInstance(pPackageInfo); + + String id; + String appVersion; + String appType; + String appMimeType; + String appApiVersion; + String appName; + String appVendor; + String appDescription; + String appUrl; + String appCid; + String appRootPath; + int appStorageType = 0; + DateTime appInstallationTime; + String appIconPath; + + pEnum->GetStringAt(1, id); + pEnum->GetStringAt(3, appVersion); + pEnum->GetStringAt(4, appType); + pEnum->GetStringAt(5, appMimeType); + pEnum->GetStringAt(6, appApiVersion); + pEnum->GetStringAt(7, appName); + pEnum->GetStringAt(8, appVendor); + pEnum->GetStringAt(9, appDescription); + pEnum->GetStringAt(10, appUrl); + pEnum->GetStringAt(11, appCid); + pEnum->GetStringAt(16, appRootPath); + pEnum->GetIntAt(17, appStorageType); + pEnum->GetDateTimeAt(18, appInstallationTime); + pEnum->GetStringAt(21, appIconPath); + + pPackageInfoImpl->SetAppId(id); + pPackageInfoImpl->SetAppVersion(appVersion); + pPackageInfoImpl->SetAppMimeType(appMimeType); + pPackageInfoImpl->SetAppApiVersion(appApiVersion); + pPackageInfoImpl->SetAppName(appName); + pPackageInfoImpl->SetAppVendor(appVendor); + pPackageInfoImpl->SetAppDescription(appDescription); + pPackageInfoImpl->SetAppUrl(appUrl); + pPackageInfoImpl->SetAppCid(appCid); + pPackageInfoImpl->SetAppRootPath(appRootPath); + pPackageInfoImpl->SetAppStorageType(appStorageType); + pPackageInfoImpl->SetAppInstallationTime(appInstallationTime); + pPackageInfoImpl->SetAppIconPath(appIconPath); + } + + delete pEnum; + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + return pPackageInfo; +} + +int +_PackageManagerImpl::PackageInfoEventHandler(const pkgmgrinfo_pkginfo_h handle, void* pUserData) +{ + SysTryReturn(NID_APP, handle != null, 0, E_SYSTEM, "[E_SYSTEM] handle must not be null."); + + int result = 0; + char* pPackage = null; + ArrayList* pList = (ArrayList*)pUserData; + + PackageInfo *pPackageInfo = new (std::nothrow) PackageInfo; + SysTryReturn(NID_APP, pPackageInfo != null, 0, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pPackageInfo instance must not be null."); + + _PackageInfoImpl* pPackageInfoImpl = _PackageInfoImpl::GetInstance(pPackageInfo); + + result = pkgmgrinfo_pkginfo_get_pkgname(handle, &pPackage); + if (result == 0) + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_pkgname(): package = [%s]", pPackage); + } + else + { + SysLog(NID_APP, "pkgmgrinfo_pkginfo_get_pkgname() is failed. result = [%d]", result); + } + + pPackageInfoImpl->Construct(pPackage); + pList->Add(*pPackageInfo); + + return result; +} + +IList* +_PackageManagerImpl::GetFilteredAppIdListN(const String& feature, const String& value) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + ArrayList* pList = null; + + query.Format(1024, L"SELECT AppInfo.PACKAGE_NAME FROM AppInfo, AppFeature WHERE AppFeature.ID = AppInfo.UNIQUE_ID and AppFeature.NAME = '%ls' and AppFeature.VALUE = '%ls' COLLATE NOCASE", feature.GetPointer(), value.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + + if (pEnum != null) + { + pList = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + String* pPackageName = new (std::nothrow) String; + SysTryReturn(NID_APP, pPackageName != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pPackageName instance must not be null."); + + pEnum->GetStringAt(0, *pPackageName); + + pList->Add(*pPackageName); + } + + delete pEnum; + + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + return pList; +} + +IList* +_PackageManagerImpl::GetDataControlInfoN(const String& providerId, const String& type) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + ArrayList* pList = null; + + query.Format(1024, L"SELECT AppInfo.PACKAGE_NAME, DataControl.ACCESS FROM AppInfo, DataControl WHERE DataControl.ID = AppInfo.UNIQUE_ID and DataControl.PROVIDER_ID = '%ls' and DataControl.TYPE = '%ls' COLLATE NOCASE", providerId.GetPointer(), type.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + + if (pEnum != null) + { + pList = new (std::nothrow) ArrayList(); + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "ArrayList creation failure."); + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + String* pPackageName = new (std::nothrow) String; + SysTryReturn(NID_APP, pPackageName != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pPackageName instance must not be null."); + + String* pAccess = new (std::nothrow) String; + SysTryReturn(NID_APP, pAccess != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pAccess instance must not be null."); + + pEnum->GetStringAt(0, *pPackageName); + pList->Add(*pPackageName); + + pEnum->GetStringAt(1, *pAccess); + pList->Add(*pAccess); + } + + delete pEnum; + + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + return pList; +} + +IMap* +_PackageManagerImpl::GetUiThemeListN(const PackageId& packageId) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + HashMap* pList = null; + + query.Format(1024, L"SELECT AppFeature.NAME, AppFeature.VALUE FROM PkgInfo, AppInfo, AppFeature WHERE (AppFeature.ID = AppInfo.UNIQUE_ID and AppInfo.ID = PkgInfo.UNIQUE_ID and PkgInfo.PKG_ID = '%ls') and (AppFeature.NAME = 'SystemTheme' or AppFeature.NAME = 'UserDefinedTheme')" + , packageId.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + + if (pEnum != null) + { + pList = new (std::nothrow) HashMap(); + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "HashMap creation failure."); + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + String* pName = new (std::nothrow) String; + SysTryCatch(NID_APP, pName != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pName instance must not be null."); + + String* pValue = new (std::nothrow) String; + SysTryCatch(NID_APP, pValue != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] pValue instance must not be null."); + + pEnum->GetStringAt(0, *pName); + pEnum->GetStringAt(1, *pValue); + + pList->Add(*pName, *pValue); + } + + delete pEnum; + + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + return pList; +} + +bool +_PackageManagerImpl::IsAppInstalled(const AppId& appId) +{ + if (appId == _AppInfo::GetPackageId()) + { + return true; + } + + int result = 0; + pkgmgrinfo_pkginfo_h pPackageInfoHandle = null; + + std::unique_ptr pPackageId(_StringConverter::CopyToCharArrayN(appId)); + SysTryReturn(NID_APP, pPackageId, false, E_OUT_OF_MEMORY, "pPackageId is null"); + + result = pkgmgrinfo_pkginfo_get_pkginfo(pPackageId.get(), &pPackageInfoHandle); + SysTryReturn(NID_APP, result == 0, false, E_APP_NOT_INSTALLED, "pkgmgrinfo_pkginfo_get_pkginfo() failed. result=[%d], packageId=[%s]", result, pPackageId.get()); + + if(pPackageInfoHandle) + { + pkgmgrinfo_pkginfo_destroy_pkginfo(pPackageInfoHandle); + } + + return true; +} + +int +_PackageManagerImpl::PackageEventHandler(int req_id, const char* pkg_type, const char* pkg_name, + const char* key, const char* val, const void* pmsg, void* data) +{ + SysLog(NID_APP, "PackageEventHandler - req_id: %d, pkg_type: %s, pkg_name: %s, key: %s, val: %s", req_id, pkg_type, + pkg_name, key, val); + + PackageType type = PACKAGE_TYPE_TPK; + PackageId packageId(pkg_name); + + if (strcmp(pkg_type, "tpk") == 0) + { + type = PACKAGE_TYPE_TPK; + } + else if (strcmp(pkg_type, "wgt") == 0) + { + type = PACKAGE_TYPE_WGT; + } + else + { + SysLog(NID_APP, "Invalid type - pkg_type: %s", pkg_type); + return 0; + } + + _PackageManagerImpl* pThis = _PackageManagerImpl::GetInstance(); + pThis->SendPackageEvent(type, packageId, key, val); + + return 0; +} + +String* +_PackageManagerImpl::GetAppIdOfDataControlN(const String& providerId) +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + String* pAppId = null; + + query.Format(1024, L"SELECT PkgInfo.PKG_ID FROM PkgInfo, AppInfo, DataControl WHERE DataControl.PROVIDER_ID = '%ls' and DataControl.ID = AppInfo.UNIQUE_ID and AppInfo.ID = PkgInfo.UNIQUE_ID", + providerId.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pAppId = new (std::nothrow) String; + SysTryReturn(NID_APP, pAppId != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Insufficient memory"); + + pEnum->GetStringAt(0, *pAppId); + } + + delete pEnum; + } + +CATCH: + delete pStmt; + return pAppId; +} + +result +_PackageManagerImpl::CreatePackageTables(void) +{ + result r = E_SUCCESS; + Database db; + String createQuery; + + if (File::IsFileExist(PACKAGE_DATABASE_FILE_NAME) == true) + { + SysLog(NID_APP, ".app-package.db is already existed!"); + return r; + } + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.Construct is failed. [%s]", GetErrorMessage(r)); + + // PkgInfo + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS PkgInfo" + "( UNIQUE_ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "PKG_ID TEXT," + "PKG_SECRET TEXT," + "PKG_VERSION TEXT," + "PKG_TYPE TEXT," + "PKG_MIMETYPE TEXT," + "PKG_APIVERSION TEXT," + "PKG_NAME TEXT," + "PKG_VENDOR TEXT," + "PKG_DESCRIPTION TEXT," + "PKG_URL TEXT," + "PKG_CID TEXT," + "PKG_READONLY_SIZE INTEGER," + "PKG_DATA_SIZE INTEGER," + "PKG_PARENT_ID TEXT," + "PKG_ATTRIBUTE INTEGER," + "PKG_ROOTPATH TEXT," + "PKG_STORAGE_TYPE INTEGER," + "PKG_INSTALLATION_DATE TEXT," + "PKG_STATE INTEGER," + "PKG_INITIATOR INTEGER )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // PkgPrivileges + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS PkgPrivileges" + "( ID INTEGER," + "PRIVILEGES TEXT," + "HMAC_PPRIVILEGES TEXT," + "CERTIFICATE_TYPE INTEGER )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // PkgIntegrity + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS PkgIntegrity" + "( ID INTEGER," + "HMAC_APPID TEXT," + "HMAC_APPSECRET TEXT," + "HMAC_HTB TEXT," + "SLOT_NUM INTEGER )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // AppInfo + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS AppInfo" + "( UNIQUE_ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "ID INTEGER," + "APP_NAME TEXT," + "APP_TYPE TEXT," + "APP_DEFAULT TEXT," + "APP_MAINMENU_ICON TEXT," + "APP_SETTING_ICON TEXT," + "APP_TICKER_ICON TEXT," + "APP_QUICKPANEL_ICON TEXT," + "APP_LAUNCHIMAGE_ICON TEXT," + "APP_FEATURE INTEGER," + "PACKAGE_NAME TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // Notification + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS Notification" + "( ID INTEGER," + "NAME TEXT," + "VALUE TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // AppFeature + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS AppFeature" + "( ID INTEGER," + "NAME TEXT," + "VALUE TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // LaunchCondition + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS LaunchCondition" + "( ID INTEGER," + "NAME TEXT," + "VALUE TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // DataControl + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS DataControl" + "( ID INTEGER," + "PROVIDER_ID TEXT," + "TYPE TEXT," + "ACCESS TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // Capability + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS Capability" + "( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "OPERATION_ID TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // ResolutionUriScheme + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS ResolutionUriScheme" + "( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "URI_SCHEME TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // ResolutionMimeType + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS ResolutionMimeType" + "( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "MIME_TYPE TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // AppControl + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS AppControl" + "( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "PROVIDER_ID TEXT," + "CATEGORY TEXT )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + // AppInfoLookup + createQuery.Format(1024, L"CREATE TABLE IF NOT EXISTS AppInfoLookup" + "( AppInfoID INTEGER," + "CapabilityID INTEGER," + "ResolutionUriSchemeID INTEGER," + "ResolutionMimeTypeID INTEGER," + "AppControlID INTEGER )"); + r = db.ExecuteSql(createQuery, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "MakePackageDb: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + createQuery.Clear(); + + return r; +} + +result +_PackageManagerImpl::RegisterPackageInfo(_PackageInfoImpl& pkgInfoImpl) +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + String privileges; + String hmacPrivileges; + PackageInfo packageInfo; + int uniqueId = 0; + + SysLog(NID_APP, "_PackageManagerImpl::RegisterPackageInfo()"); + + query.Format( + 1024, L"INSERT INTO PkgInfo " + "(PKG_ID, PKG_SECRET, PKG_VERSION, PKG_TYPE, PKG_MIMETYPE, PKG_APIVERSION, PKG_NAME, PKG_VENDOR, PKG_DESCRIPTION, PKG_URL, PKG_CID, PKG_READONLY_SIZE, PKG_DATA_SIZE, PKG_PARENT_ID," + " PKG_ATTRIBUTE, PKG_ROOTPATH, PKG_STORAGE_TYPE, PKG_INSTALLATION_DATE, PKG_STATE, PKG_INITIATOR) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + //SysTryCatch(NID_APP, r == E_SUCCESS, r, r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + //SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + PackageId packageId = pkgInfoImpl.GetAppId(); + String appVersion = pkgInfoImpl.GetAppVersion(); + String type = pkgInfoImpl.GetAppType(); + String appMimeType = pkgInfoImpl.GetAppMimeType(); + String appApiVersion = pkgInfoImpl.GetAppApiVersion(); + String appName = pkgInfoImpl.GetAppName(); + String appVendor = pkgInfoImpl.GetAppVendor(); + String appDescription = pkgInfoImpl.GetAppDescription(); + String appUrl = pkgInfoImpl.GetAppUrl(); + String appCid = pkgInfoImpl.GetAppCid(); + + pkgInfoImpl.GetPrivilegesValue(privileges, hmacPrivileges); + String appRootPath = pkgInfoImpl.GetAppRootPath(); + int appStorageType = pkgInfoImpl.GetAppStorageType(); + int certType = pkgInfoImpl.GetCertType(); + ArrayList* pAppInfoImplList = pkgInfoImpl.GetAppInfoList(); + + DateTime time; + r = SystemTime::GetCurrentTime(time); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "An error occurs while getting a current time."); + + if (!packageId.IsEmpty()) + { + r = pStmt->BindString(0, packageId); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appVersion.IsEmpty()) + { + r = pStmt->BindString(2, appVersion); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!type.IsEmpty()) + { + r = pStmt->BindString(3, type); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appMimeType.IsEmpty()) + { + r = pStmt->BindString(4, appMimeType); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appApiVersion.IsEmpty()) + { + r = pStmt->BindString(5, appApiVersion); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appName.IsEmpty()) + { + r = pStmt->BindString(6, appName); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appVendor.IsEmpty()) + { + r = pStmt->BindString(7, appVendor); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appDescription.IsEmpty()) + { + r = pStmt->BindString(8, appDescription); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appUrl.IsEmpty()) + { + r = pStmt->BindString(9, appUrl); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appCid.IsEmpty()) + { + r = pStmt->BindString(10, appCid); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!appRootPath.IsEmpty()) + { + r = pStmt->BindString(15, appRootPath); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (appStorageType != 0) + { + r = pStmt->BindInt(16, appStorageType); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + r = pStmt->BindDateTime(17, time); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + + pEnum = ExecuteStatementN(db, pStmt); + + r = GetLastResult(); + + uniqueId = pkgInfoImpl.GetUniqueId(); + + SysLog(NID_APP, "_PackageManagerImpl::RegisterPackageInfo()-GetUniqueId(%d)", uniqueId); + + __pDb = &db; + + // AppInfo + RegisterAppInfoList(uniqueId, pAppInfoImplList); + + // PkgPrivileges + RegisterPrivileges(uniqueId, privileges, hmacPrivileges, certType); + +CATCH: + __pDb = null; + delete pEnum; + delete pStmt; + return r; +} + +result +_PackageManagerImpl::UnregisterPackageInfo(const PackageId& packageId) +{ + SysLog(NID_APP, "packageId = [%ls]", packageId.GetPointer()); + + result r = E_SUCCESS; + Database db; + String query; + int id = 0; + PackageInfo* pPkgInfo; + _PackageInfoImpl* pPackageInfoImpl = null; + ArrayList* pList = null; + + pPkgInfo = GetPackageInfoN(packageId); + SysTryReturn(NID_APP, pPkgInfo != null, r, r, "UnregisterPackageInfo: GetUniqueId() is invalid. [%d]", id); + + pPackageInfoImpl = _PackageInfoImpl::GetInstance(pPkgInfo); + pPackageInfoImpl->SetAppId(packageId); + id = pPackageInfoImpl->GetUniqueId(); + SysTryReturn(NID_APP, id > 0, r, r, "UnregisterPackageInfo: GetUniqueId() is invalid. [%d]", id); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "UnregisterPackageInfo: db.Construct is failed. [%s]", GetErrorMessage(r)); + + // AppInfoLookup + pList = pPackageInfoImpl->GetAppInfoListN(); + if (pList != null) + { + for (int i = 0; i < pList->GetCount(); i++) + { + _PackageAppInfoImpl* pAppInfoImpl = dynamic_cast <_PackageAppInfoImpl*>(pList->GetAt(i)); + + if (pAppInfoImpl != null) + { + int uniqueId = 0; + uniqueId = pAppInfoImpl->GetUniqueId(); + + query.Format(1024, L"DELETE FROM AppInfoLookup WHERE AppInfoID = %d", uniqueId); + r = db.ExecuteSql(query, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "UnregisterPackageInfo: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + query.Clear(); + } + } + delete pList; + } + + // PkgInfo + query.Format(1024, L"DELETE FROM PkgInfo WHERE PKG_ID = '%ls'", packageId.GetPointer()); + r = db.ExecuteSql(query, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "UnregisterPackageInfo: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + query.Clear(); + + // AppInfo + query.Format(1024, L"DELETE FROM AppInfo WHERE ID = %d", id); + r = db.ExecuteSql(query, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "UnregisterPackageInfo: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + query.Clear(); + + // PkgPrivileges + query.Format(1024, L"DELETE FROM PkgPrivileges WHERE ID = %d", id); + r = db.ExecuteSql(query, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "UnregisterPackageInfo: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + query.Clear(); + + // DataControl + query.Format(1024, L"DELETE FROM DataControl WHERE ID = %d", id); + r = db.ExecuteSql(query, true); + SysTryReturn(NID_APP, r == E_SUCCESS, r, r, "UnregisterPackageInfo: db.ExecuteSql is failed. [%s]", GetErrorMessage(r)); + query.Clear(); + + delete pPkgInfo; + return r; +} + +PackageInfo* +_PackageManagerImpl::GetPackageInfoN(const String& providerId, const String& operationId) const +{ + result r = E_SUCCESS; + PackageInfo* pPkgInfo = null; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + + query.Format(1024, L"SELECT PkgInfo.PKG_ID FROM PkgInfo, AppInfo, AppInfoLookup, AppControl, Capability " + "WHERE AppControl.PROVIDER_ID ='%ls' and Capability.OPERATION_ID ='%ls' and AppControl.ID = AppInfoLookup.AppControlID " + "and Capability.ID = AppInfoLookup.CapabilityID and AppInfoLookup.AppInfoID = AppInfo.UNIQUE_ID and AppInfo.ID = PkgInfo.UNIQUE_ID " + "GROUP BY AppInfoID" + , providerId.GetPointer(), operationId.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + PackageId packageId; + pEnum->GetStringAt(0, packageId); + + pPkgInfo = GetPackageInfoN(packageId); + } + + delete pEnum; + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + return pPkgInfo; +} + +result +_PackageManagerImpl::GetAppInfo(int uniqueId, _PackageAppInfoImpl& appInfo) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + + query.Format(1024, L"SELECT * FROM AppInfo WHERE UNIQUE_ID = %d", uniqueId); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + int uniqueId = 0; + int pkgId = 0; + String name; + String defaultapp; + String mainmenuIcon; + String settingIcon; + String tickerIcon; + String quickpanelIcon; + String launchImageIcon; + int appFeature = 0; + String packageName; + + pEnum->GetIntAt(0, uniqueId); + pEnum->GetIntAt(1, pkgId); + pEnum->GetStringAt(2, name); + pEnum->GetStringAt(3, defaultapp); + pEnum->GetStringAt(4, mainmenuIcon); + pEnum->GetStringAt(5, settingIcon); + pEnum->GetStringAt(7, quickpanelIcon); + pEnum->GetIntAt(9, appFeature); + pEnum->GetStringAt(10, packageName); + + appInfo.SetUniqueId(uniqueId); + appInfo.SetPkgId(pkgId); + appInfo.SetName(name); + appInfo.SetDefault(defaultapp); + appInfo.SetMainmenuIcon(mainmenuIcon); + appInfo.SetSettingIcon(settingIcon); + appInfo.SetQuickpanelIcon(quickpanelIcon); + appInfo.SetAppFeature(appFeature); + appInfo.SetPackageName(packageName); + } + + delete pEnum; + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + return r; +} + +ArrayList* +_PackageManagerImpl::GetPackageAppInfoImplListN(const String& packageId) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + //int id = 0; + PackageInfo* pPkgInfo = null; + _PackageInfoImpl* pPackageInfoImpl = null; + ArrayList* pList = null; + + pPkgInfo = GetPackageInfoN(packageId); + SysTryCatch(NID_APP, pPkgInfo != null, , r, "[%s] GetPackageInfoN() is failed", GetErrorMessage(r)); + + pPackageInfoImpl = _PackageInfoImpl::GetInstance(pPkgInfo); + query.Format(1024, L"SELECT * FROM AppInfo WHERE ID = %d", pPackageInfoImpl->GetUniqueId()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + + if (pEnum != null) + { + pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Container allocation failure."); + + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _PackageAppInfoImpl* pPackageAppInfoImpl = new (std::nothrow) _PackageAppInfoImpl; + SysTryReturn(NID_APP, pPackageAppInfoImpl != null, null, E_OUT_OF_MEMORY, "pPackageAppInfoImpl instance must not be null."); + + int uniqueId = 0; + int pkgId = 0; + String name; + String defaultapp; + String mainmenuIcon; + String settingIcon; + String quickpanelIcon; + int appFeature = 0; + String packageName; + + pEnum->GetIntAt(0, uniqueId); + pEnum->GetIntAt(1, pkgId); + pEnum->GetStringAt(2, name); + pEnum->GetStringAt(3, defaultapp); + pEnum->GetStringAt(4, mainmenuIcon); + pEnum->GetStringAt(5, settingIcon); + pEnum->GetStringAt(7, quickpanelIcon); + pEnum->GetIntAt(9, appFeature); + pEnum->GetStringAt(10, packageName); + + pPackageAppInfoImpl->SetUniqueId(uniqueId); + pPackageAppInfoImpl->SetPkgId(pkgId); + pPackageAppInfoImpl->SetName(name); + pPackageAppInfoImpl->SetDefault(defaultapp); + pPackageAppInfoImpl->SetMainmenuIcon(mainmenuIcon); + pPackageAppInfoImpl->SetSettingIcon(settingIcon); + pPackageAppInfoImpl->SetQuickpanelIcon(quickpanelIcon); + pPackageAppInfoImpl->SetAppFeature(appFeature); + pPackageAppInfoImpl->SetPackageName(packageName); + + pList->Add(*pPackageAppInfoImpl); + } + + delete pEnum; + } + +CATCH: + delete pPkgInfo; + delete pStmt; + return pList; +} + +ArrayList* +_PackageManagerImpl::GetPackageAppFeatureListN(const PackageId& packageId, const Tizen::Base::String& appExecutableName) const +{ + ArrayList* pAppInfoList = GetPackageAppInfoImplListN(packageId); + SysTryReturn(NID_APP, pAppInfoList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] AppInfo list instance must not be null."); + + ArrayList* pResult = null; + + for (int i = 0; i < pAppInfoList->GetCount(); i++) + { + const _PackageAppInfoImpl* pAppInfoImpl = static_cast(pAppInfoList->GetAt(i)); + if (pAppInfoImpl == null) + { + continue; + } + + if (pAppInfoImpl->GetName() == appExecutableName) + { + pResult = pAppInfoImpl->GetAppFeatureListN(); + goto OUT; + } + } + +OUT: + pAppInfoList->RemoveAll(true); + delete pAppInfoList; + + return pResult; +} + +HashMapT* +_PackageManagerImpl::GetPackageAppFeatureMapN(const PackageId& packageId, const Tizen::Base::String& appExecutableName) const +{ + ArrayList* pAppInfoList = GetPackageAppInfoImplListN(packageId); + SysTryReturn(NID_APP, pAppInfoList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] AppInfo list instance must not be null."); + + HashMapT* pResult = null; + + std::auto_ptr pEnum(pAppInfoList->GetEnumeratorN()); + + while (pEnum->MoveNext() == E_SUCCESS) + { + const _PackageAppInfoImpl* pAppInfoImpl = static_cast(pEnum->GetCurrent()); + if (pAppInfoImpl == null) + { + continue; + } + + if (pAppInfoImpl->GetName() == appExecutableName) + { + pResult = pAppInfoImpl->GetAppFeatureMapN(); + goto OUT; + } + } + +OUT: + pAppInfoList->RemoveAll(true); + delete pAppInfoList; + + return pResult; +} + +ArrayList* +_PackageManagerImpl::GetAppLaunchConditionListN(const String& packageName) const +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + ArrayList* pList = null; + + query.Format(1024, L"SELECT LaunchCondition.* FROM LaunchCondition, AppInfo WHERE AppInfo.UNIQUE_ID = LaunchCondition.ID and AppInfo.PACKAGE_NAME = '%ls'", packageName.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + pList = new (std::nothrow) ArrayList; + SysTryReturn(NID_APP, pList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Container allocation failure."); + + pList->Construct(); + + while (pEnum->MoveNext() == E_SUCCESS) + { + _LaunchConditionInfoImpl* pLaunchCondtion = new (std::nothrow) _LaunchConditionInfoImpl; + SysTryReturn(NID_APP, pLaunchCondtion != null, null, E_OUT_OF_MEMORY, "pLaunchCondtion instance must not be null."); + + String name; + String value; + + pEnum->GetStringAt(1, name); + pEnum->GetStringAt(2, value); + + pLaunchCondtion->SetName(name); + pLaunchCondtion->SetValue(value); + + pList->Add(*pLaunchCondtion); + + SysLog(NID_APP, "Name[%ls], Value[%ls]", name.GetPointer(), value.GetPointer()); + } + + delete pEnum; + } + +CATCH: + delete pStmt; + return pList; +} + +result +_PackageManagerImpl::RegisterAppInfoList(int id, ArrayList* pList) +{ + SysTryReturnResult(NID_APP, __pDb != null, E_SYSTEM, "__pDb is null"); + + result r = E_SUCCESS; + String query; + DbStatement* pStmt = null; + + if (pList != null) + { + for (int i = 0; i < pList->GetCount(); i++) + { + _PackageAppInfoImpl* pAppInfoImpl = dynamic_cast <_PackageAppInfoImpl*>(pList->GetAt(i)); + + if (pAppInfoImpl != null) + { + DbEnumerator* pEnum = null; + int uniqueId = 0; + + String name = pAppInfoImpl->GetName(); + String defaultapp = pAppInfoImpl->GetDefault(); + String mainmenuIcon = pAppInfoImpl->GetMainmenuIcon(); + String settingIcon = pAppInfoImpl->GetSettingIcon(); + String quickpanelIcon = pAppInfoImpl->GetQuickpanelIcon(); + int appFeature = pAppInfoImpl->GetAppFeature(); + String packageName = pAppInfoImpl->GetPackageName(); + String type = pAppInfoImpl->GetType(); + + ArrayList* pLaunchConditionImplList = pAppInfoImpl->GetLaunchConditionList(); + ArrayList* pNotificationImplList = pAppInfoImpl->GetNotificationList(); + ArrayList* pAppFeatureImplList = pAppInfoImpl->GetAppFeatureList(); + ArrayList* pDataControlImplList = pAppInfoImpl->GetDataControlList(); + + query.Format( + 1024, L"INSERT INTO AppInfo " + "(ID, APP_NAME, APP_DEFAULT, APP_MAINMENU_ICON, APP_SETTING_ICON, APP_TICKER_ICON, APP_QUICKPANEL_ICON, APP_LAUNCHIMAGE_ICON, APP_FEATURE, PACKAGE_NAME, APP_TYPE) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?)"); + + pStmt = CreateStatementN(*__pDb, query); + //SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + if (id != 0) + { + r = pStmt->BindInt(0, id); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!name.IsEmpty()) + { + r = pStmt->BindString(1, name); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!defaultapp.IsEmpty()) + { + r = pStmt->BindString(2, defaultapp); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!mainmenuIcon.IsEmpty()) + { + r = pStmt->BindString(3, mainmenuIcon); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!settingIcon.IsEmpty()) + { + r = pStmt->BindString(4, settingIcon); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!quickpanelIcon.IsEmpty()) + { + r = pStmt->BindString(6, quickpanelIcon); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (appFeature != 0) + { + r = pStmt->BindInt(8, appFeature); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!packageName.IsEmpty()) + { + r = pStmt->BindString(9, packageName); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!type.IsEmpty()) + { + r = pStmt->BindString(10, type); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + pEnum = ExecuteStatementN(*__pDb, pStmt); + + query.Clear(); + delete pStmt; + pStmt = null; + delete pEnum; + + pAppInfoImpl->SetPkgId(id); + uniqueId = pAppInfoImpl->GetUniqueId(); + RegisterLaunchConditionList(uniqueId, pLaunchConditionImplList); + RegisterNotificationList(uniqueId, pNotificationImplList); + RegisterAppFeatureList(uniqueId, pAppFeatureImplList); + RegisterDataControlList(uniqueId, pDataControlImplList); + //RegisterAppControlList(uniqueId, pAppControlImplList); + } + } + } + + r = GetLastResult(); + +CATCH: + delete pStmt; + + return r; +} + +result +_PackageManagerImpl::RegisterLaunchConditionList(int id, ArrayList* pList) +{ + SysTryReturnResult(NID_APP, __pDb != null, E_SYSTEM, "__pDb is null"); + + result r = E_SUCCESS; + String query; + DbStatement* pStmt = null; + + if (pList != null) + { + for (int i = 0; i < pList->GetCount(); i++) + { + _LaunchConditionInfoImpl* pLaunchCondition = dynamic_cast<_LaunchConditionInfoImpl*>(pList->GetAt(i)); + + if (pLaunchCondition != null) + { + DbEnumerator* pEnum = null; + + String name = pLaunchCondition->GetName(); + String value = pLaunchCondition->GetValue(); + + query.Format(1024, L"INSERT INTO LaunchCondition (ID, NAME, VALUE) VALUES (?,?,?)"); + + pStmt = CreateStatementN(*__pDb, query); + //SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + if (id != 0) + { + r = pStmt->BindInt(0, id); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!name.IsEmpty()) + { + r = pStmt->BindString(1, name); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!value.IsEmpty()) + { + r = pStmt->BindString(2, value); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + pEnum = ExecuteStatementN(*__pDb, pStmt); + + query.Clear(); + delete pStmt; + pStmt = null; + delete pEnum; + } + } + } + + r = GetLastResult(); + +CATCH: + delete pStmt; + + return r; +} + +result +_PackageManagerImpl::RegisterNotificationList(int id, ArrayList* pList) +{ + SysTryReturnResult(NID_APP, __pDb != null, E_SYSTEM, "__pDb is null"); + + result r = E_SUCCESS; + String query; + DbStatement* pStmt = null; + + if (pList != null) + { + for (int i = 0; i < pList->GetCount(); i++) + { + _NotificationInfoImpl* pNotification = dynamic_cast<_NotificationInfoImpl*>(pList->GetAt(i)); + + if (pNotification != null) + { + DbEnumerator* pEnum = null; + + String name = pNotification->GetName(); + String value = pNotification->GetValue(); + + query.Format(1024, L"INSERT INTO Notification (ID, NAME, VALUE) VALUES (?,?,?)"); + + pStmt = CreateStatementN(*__pDb, query); + //SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + if (id != 0) + { + r = pStmt->BindInt(0, id); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!name.IsEmpty()) + { + r = pStmt->BindString(1, name); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!value.IsEmpty()) + { + r = pStmt->BindString(2, value); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + pEnum = ExecuteStatementN(*__pDb, pStmt); + + query.Clear(); + delete pStmt; + pStmt = null; + delete pEnum; + } + } + } + + r = GetLastResult(); + +CATCH: + delete pStmt; + + return r; +} + +result +_PackageManagerImpl::RegisterAppFeatureList(int id, ArrayList* pList) +{ + SysTryReturnResult(NID_APP, __pDb != null, E_SYSTEM, "__pDb is null"); + + result r = E_SUCCESS; + String query; + DbStatement* pStmt = null; + + if (pList != null) + { + for (int i = 0; i < pList->GetCount(); i++) + { + _AppFeatureInfoImpl* pAppFeature = dynamic_cast<_AppFeatureInfoImpl*>(pList->GetAt(i)); + + if (pAppFeature != null) + { + DbEnumerator* pEnum = null; + + String name = pAppFeature->GetName(); + String value = pAppFeature->GetValue(); + + query.Format(1024, L"INSERT INTO AppFeature (ID, NAME, VALUE) VALUES (?,?,?)"); + + pStmt = CreateStatementN(*__pDb, query); + //SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + if (id != 0) + { + r = pStmt->BindInt(0, id); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!name.IsEmpty()) + { + r = pStmt->BindString(1, name); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!value.IsEmpty()) + { + r = pStmt->BindString(2, value); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + pEnum = ExecuteStatementN(*__pDb, pStmt); + + query.Clear(); + delete pStmt; + pStmt = null; + delete pEnum; + } + } + } + + r = GetLastResult(); + +CATCH: + delete pStmt; + + return r; +} + +result +_PackageManagerImpl::RegisterDataControlList(int id, ArrayList* pList) +{ + SysTryReturnResult(NID_APP, __pDb != null, E_SYSTEM, "__pDb is null"); + + result r = E_SUCCESS; + String query; + DbStatement* pStmt = null; + + if (pList != null) + { + for (int i = 0; i < pList->GetCount(); i++) + { + _DataControlInfoImpl* pDataControl = dynamic_cast<_DataControlInfoImpl*>(pList->GetAt(i)); + + if (pDataControl != null) + { + DbEnumerator* pEnum = null; + + String providerId = pDataControl->GetProviderId(); + ArrayList* pTypeList = pDataControl->GetControlTypeList(); + + if (pTypeList != null) + { + for (int j = 0; j < pTypeList->GetCount(); j++) + { + _DataControlTypeImpl* pControlType = dynamic_cast<_DataControlTypeImpl*>(pTypeList->GetAt(j)); + + if (pControlType != null) + { + String access = pControlType->GetAccess(); + String type = pControlType->GetType(); + + query.Format(1024, L"INSERT INTO DataControl (ID, PROVIDER_ID, TYPE, ACCESS) VALUES (?,?,?,?)"); + + pStmt = CreateStatementN(*__pDb, query); + //SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + if (id != 0) + { + r = pStmt->BindInt(0, id); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!providerId.IsEmpty()) + { + r = pStmt->BindString(1, providerId); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!type.IsEmpty()) + { + r = pStmt->BindString(2, type); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!access.IsEmpty()) + { + r = pStmt->BindString(3, access); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + pEnum = ExecuteStatementN(*__pDb, pStmt); + + query.Clear(); + delete pStmt; + pStmt = null; + delete pEnum; + } + } + } + } + } + } + + r = GetLastResult(); + +CATCH: + delete pStmt; + + return r; +} + +int +_PackageManagerImpl::FindRecord(const String& tableName, const String& columnName, const String& value) const +{ + + result r = E_SUCCESS; + Database db; + String query; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + int uniqueId = 0; + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + //SysTryCatch(NID_APP, r == E_SUCCESS, r, r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + query.Format(1024, L"SELECT * FROM %ls WHERE %ls = '%ls'", tableName.GetPointer(), columnName.GetPointer(), value.GetPointer()); + + pStmt = CreateStatementN(db, query); + //SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetIntAt(0, uniqueId); + } + + delete pEnum; + } + +//CATCH: + delete pStmt; + + return uniqueId; +} + +result +_PackageManagerImpl::GetRecord(const String& tableName, int uniqueId, const String& columnName, String& value) const +{ + result r = E_SUCCESS; + Database db; + String query; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + //SysTryCatch(NID_APP, r == E_SUCCESS, r, r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + query.Format(1024, L"SELECT %ls FROM %ls WHERE UNIQUE_ID = %d", columnName.GetPointer(), tableName.GetPointer(), uniqueId); + + pStmt = CreateStatementN(db, query); + //SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetStringAt(0, value); + } + + delete pEnum; + } + +//CATCH: + delete pStmt; + + return r; +} + +result +_PackageManagerImpl::RegisterPrivileges(int id, const String& privileges, const String& hmacPrivileges, int certType) +{ + SysTryReturnResult(NID_APP, __pDb != null, E_SYSTEM, "__pDb is null"); + + result r = E_SUCCESS; + String query; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + + query.Format(1024, L"INSERT INTO PkgPrivileges (ID, PRIVILEGES, HMAC_PPRIVILEGES, CERTIFICATE_TYPE) VALUES (?,?,?,?)"); + + pStmt = CreateStatementN(*__pDb, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + if (id != 0) + { + r = pStmt->BindInt(0, id); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!privileges.IsEmpty()) + { + r = pStmt->BindString(1, privileges); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (!hmacPrivileges.IsEmpty()) + { + r = pStmt->BindString(2, hmacPrivileges); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + if (certType != 0) + { + r = pStmt->BindInt(3, certType); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while constructing a database.", GetErrorMessage(r)); + } + + pEnum = ExecuteStatementN(*__pDb, pStmt); + + delete pStmt; + pStmt = null; + delete pEnum; + pEnum = null; + + r = GetLastResult(); + +CATCH: + delete pStmt; + return r; +} + +result +_PackageManagerImpl::GetPackageName(const PackageId& packageId, const String* pName, char* pPackageName, int bufferSize) +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + Tizen::Base::String packageName; + + if (pName == null) + { + query.Format( + 1024, + L"SELECT AppInfo.PACKAGE_NAME FROM AppInfo, PkgInfo WHERE AppInfo.ID = PkgInfo.UNIQUE_ID and AppInfo.APP_DEFAULT = '%s' and PkgInfo.PKG_ID = '%ls'", + "True", packageId.GetPointer()); + } + else + { + query.Format( + 1024, + L"SELECT AppInfo.PACKAGE_NAME FROM AppInfo, PkgInfo WHERE AppInfo.ID = PkgInfo.UNIQUE_ID and APP_NAME = '%ls' and PkgInfo.PKG_ID = '%ls'", + pName->GetPointer(), packageId.GetPointer()); + } + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetStringAt(0, packageName); + snprintf(pPackageName, bufferSize, "%ls", packageName.GetPointer()); + } + delete pEnum; + } + else + { + r = E_OBJ_NOT_FOUND; + } + +CATCH: + delete pStmt; + + return r; +} + +String +_PackageManagerImpl::GetDefaultAppExecutableName(const PackageId& packageId) +{ + result r = E_SUCCESS; + Database db; + DbStatement* pStmt = null; + DbEnumerator* pEnum = null; + String query; + String executableName; + + query.Format( + 1024, + L"SELECT AppInfo.APP_NAME FROM AppInfo, PkgInfo WHERE AppInfo.ID = PkgInfo.UNIQUE_ID and AppInfo.APP_DEFAULT = '%s' and PkgInfo.PKG_ID = '%ls'", + "True", packageId.GetPointer()); + + r = db.Construct(PACKAGE_DATABASE_FILE_NAME, false); + SysTryCatch(NID_APP, r == E_SUCCESS, , r, "[%s] An error occurs while opening a database.", GetErrorMessage(r)); + + pStmt = CreateStatementN(db, query); + SysTryCatch(NID_APP, pStmt != null, GetLastResult(), + GetLastResult(), "[%s] An error occurs while creating a database statement.", GetErrorMessage(GetLastResult())); + + pEnum = ExecuteStatementN(db, pStmt); + if (pEnum != null) + { + if (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetStringAt(0, executableName); + } + delete pEnum; + } + else + { + r = E_OBJ_NOT_FOUND; + SetLastResult(r); + } + +CATCH: + delete pStmt; + + return executableName; +} + +DbStatement* +_PackageManagerImpl::CreateStatementN(Database& db, const String& query) +{ + result r = E_SUCCESS; + DbStatement* pStmt = null; + + for (int i = 0; i < MAX_DATABASE_RETRY_COUNT; i++) + { + pStmt = db.CreateStatementN(query); + r = GetLastResult(); + + if (r != E_OBJECT_LOCKED) + { + break; + } + else + { + SysLog(NID_APP, "RetryCount[%d] CreateStatementN - E_OBJECT_LOCKED", i); + delete pStmt; + pStmt = null; + usleep(50000); + } + } + + return pStmt; +} + +DbEnumerator* +_PackageManagerImpl::ExecuteStatementN(Database& db, const DbStatement* pStmt) +{ + result r = E_SUCCESS; + DbEnumerator* pEnum = null; + + for (int i = 0; i < MAX_DATABASE_RETRY_COUNT; i++) + { + pEnum = db.ExecuteStatementN(*pStmt); + r = GetLastResult(); + + if (r != E_OBJECT_LOCKED) + { + break; + } + else + { + SysLog(NID_APP, "RetryCount[%d] ExecuteStatementN - E_OBJECT_LOCKED", i); + delete pEnum; + pEnum = null; + usleep(50000); + } + } + + return pEnum; +} + +} } } // Tizen::App::Package diff --git a/src/appfw/CMakeLists.txt b/src/appfw/CMakeLists.txt new file mode 100755 index 0000000..58ced5e --- /dev/null +++ b/src/appfw/CMakeLists.txt @@ -0,0 +1,116 @@ +SET (this_target osp-appfw) + +INCLUDE_DIRECTORIES( + ${SLP_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/inc + ${CMAKE_SOURCE_DIR}/src/base/inc + ${CMAKE_SOURCE_DIR}/src/app/inc + ${CMAKE_SOURCE_DIR}/src/security/inc + ${CMAKE_SOURCE_DIR}/src/io/inc + ) + +SET (${this_target}_SOURCE_FILES + ${CMAKE_SOURCE_DIR}/src/osp-init/Osp.cpp +) + +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -Wall" ) + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} SHARED ${${this_target}_SOURCE_FILES}) + +SET(STATIC_LIBS app base io locales security system text newlib-compat) + +SET_TARGET_PROPERTIES(${this_target} PROPERTIES LINK_INTERFACE_LIBRARIES "") + +ADD_DEPENDENCIES(${this_target} ${STATIC_LIBS}) + +MACRO(OSP_ADD_OBJS_IN_ARCHIVE archives) + SET(LINK_OBJECTS_IN_ARCHIVE) + FOREACH(archive ${ARGV}) + SET(LINK_OBJECTS_IN_ARCHIVE "${LINK_OBJECTS_IN_ARCHIVE} -l${archive}") + ENDFOREACH(archive) + SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--whole-archive ${LINK_OBJECTS_IN_ARCHIVE} -Wl,-no-whole-archive") +ENDMACRO(OSP_ADD_OBJS_IN_ARCHIVE) + +OSP_ADD_OBJS_IN_ARCHIVE(${STATIC_LIBS}) + +SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--no-undefined -Wl,--as-needed") + +TARGET_LINK_LIBRARIES( ${this_target} ${STATIC_LIBS}) +TARGET_LINK_LIBRARIES(${this_target} "-lchromium" ) +TARGET_LINK_LIBRARIES(${this_target} "-lminizip" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-appfw-application" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-appfw-app-manager" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-appfw-package-manager" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-content-mime-type" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-location-manager") +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-media-sound-manager" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-network-serial" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-system-power" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-system-device" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-system-sensor" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-system-info" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-system-system-settings") +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-system-runtime-info") +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-telephony-sim" ) +TARGET_LINK_LIBRARIES(${this_target} "-lappsvc" ) +TARGET_LINK_LIBRARIES(${this_target} "-laul" ) +TARGET_LINK_LIBRARIES(${this_target} "-lbundle" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcrypto" ) +TARGET_LINK_LIBRARIES(${this_target} "-ldevman" ) +TARGET_LINK_LIBRARIES(${this_target} "-ldbus-1" ) +TARGET_LINK_LIBRARIES(${this_target} "-ldbus-glib-1" ) +TARGET_LINK_LIBRARIES(${this_target} "-ldl" ) +TARGET_LINK_LIBRARIES(${this_target} "-ldlog" ) +TARGET_LINK_LIBRARIES(${this_target} "-lglib-2.0" ) +TARGET_LINK_LIBRARIES(${this_target} "-lheynoti" ) +TARGET_LINK_LIBRARIES(${this_target} "-licui18n" ) +TARGET_LINK_LIBRARIES(${this_target} "-licuuc" ) +TARGET_LINK_LIBRARIES(${this_target} "-lnotification" ) +TARGET_LINK_LIBRARIES(${this_target} "-lpcre" ) +TARGET_LINK_LIBRARIES(${this_target} "-lpkgmgr-client" ) +TARGET_LINK_LIBRARIES(${this_target} "-lpkgmgr-info" ) +TARGET_LINK_LIBRARIES(${this_target} "-lpmapi" ) +TARGET_LINK_LIBRARIES(${this_target} "-lpthread" ) +TARGET_LINK_LIBRARIES(${this_target} "-lrt" ) +TARGET_LINK_LIBRARIES(${this_target} "-lsensor") +TARGET_LINK_LIBRARIES(${this_target} "-lsqlite3" ) +TARGET_LINK_LIBRARIES(${this_target} "-lsoup-2.4" ) +TARGET_LINK_LIBRARIES(${this_target} "-luuid" ) +TARGET_LINK_LIBRARIES(${this_target} "-lvconf" ) +TARGET_LINK_LIBRARIES(${this_target} "-lxml2" ) +TARGET_LINK_LIBRARIES(${this_target} "-lz" ) +TARGET_LINK_LIBRARIES(${this_target} "-ldukgenerator" ) +TARGET_LINK_LIBRARIES(${this_target} "-lcryptsvc" ) +TARGET_LINK_LIBRARIES(${this_target} "-L/usr/lib -ldrm-service-core-intel") +TARGET_LINK_LIBRARIES(${this_target} "-lecore" ) + + +SET_TARGET_PROPERTIES(${this_target} + PROPERTIES + VERSION ${FULLVER} + SOVERSION ${MAJORVER} + CLEAN_DIRECT_OUTPUT 1 +) +ADD_CUSTOM_COMMAND(TARGET ${this_target} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy ${LIBRARY_OUTPUT_PATH}/${CMAKE_SHARED_LIBRARY_PREFIX}${this_target}${CMAKE_SHARED_LIBRARY_SUFFIX} ${LIBRARY_OUTPUT_PATH}/debug/${CMAKE_SHARED_LIBRARY_PREFIX}${this_target}${CMAKE_SHARED_LIBRARY_SUFFIX}.${FULLVER} + COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_SHARED_LIBRARY_PREFIX}${this_target}${CMAKE_SHARED_LIBRARY_SUFFIX}.${FULLVER} ${LIBRARY_OUTPUT_PATH}/debug/${CMAKE_SHARED_LIBRARY_PREFIX}${this_target}${CMAKE_SHARED_LIBRARY_SUFFIX}.${MAJORVER} + COMMAND ${CMAKE_STRIP} --strip-unneeded ${LIBRARY_OUTPUT_PATH}/${CMAKE_SHARED_LIBRARY_PREFIX}${this_target}${CMAKE_SHARED_LIBRARY_SUFFIX} + COMMENT "strip ${this_target}" +) + + +SET(PC_NAME ${this_target}) +SET(PC_REQUIRED ${pc_requires}) +SET(PC_LDFLAGS -l${this_target}) + +# pkgconfig file +CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/${this_target}.pc.in ${CMAKE_SOURCE_DIR}/${this_target}.pc @ONLY) diff --git a/src/base/CMakeLists.txt b/src/base/CMakeLists.txt new file mode 100755 index 0000000..63f2bb0 --- /dev/null +++ b/src/base/CMakeLists.txt @@ -0,0 +1,127 @@ +SET (this_target base) + +INCLUDE_DIRECTORIES( + ${SLP_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/inc + ${CMAKE_SOURCE_DIR}/src/app/inc + ${CMAKE_SOURCE_DIR}/src/io/inc + inc + collection + runtime + utility + ext/minizip +) + +SET (${this_target}_SOURCE_FILES + FBaseBoolean.cpp + FBaseBufferBase.cpp + FBaseByteBuffer.cpp + FBaseCharacter.cpp + FBase_CharacterImpl.cpp + FBaseDateTime.cpp + FBaseDouble.cpp + FBaseDoubleComparer.cpp + FBaseErrors.cpp + FBaseFloat.cpp + FBaseFloatComparer.cpp + FBaseInt8.cpp + FBaseInt8Comparer.cpp + FBaseInteger.cpp + FBaseIntegerComparer.cpp + FBaseLong.cpp + FBaseLongComparer.cpp + FBaseLongLong.cpp + FBaseLongLongComparer.cpp + FBaseObject.cpp + FBaseResult.cpp + FBaseShort.cpp + FBaseShortComparer.cpp + FBaseString.cpp + FBaseStringComparer.cpp + FBase_StringConverter.cpp + FBaseSys.cpp + FBaseTimeSpan.cpp + FBaseTypes.cpp + FBaseUuId.cpp + FBase_NativeError.cpp + FBaseInit.cpp + FBase_Exception.cpp + FBaseFloatMatrix.cpp + FBaseFloatMatrix3.cpp + FBaseFloatMatrix4.cpp + FBaseDoubleMatrix.cpp + FBaseDoubleMatrix3.cpp + FBaseDoubleMatrix4.cpp + FBaseIntMatrix.cpp + collection/FBaseColMapEntry.cpp + collection/FBaseColQueue.cpp + collection/FBaseColLinkedList.cpp + collection/FBaseColStack.cpp + collection/FBaseColArrayList.cpp + collection/FBaseColMultiHashMap.cpp + collection/FBaseColHashMap.cpp + collection/FBaseColTypes.cpp + runtime/FBaseRt_Event.cpp + runtime/FBaseRt_EventImpl.cpp + runtime/FBaseRtEvent.cpp + runtime/FBaseRt_Process.cpp + runtime/FBaseRt_EventManager.cpp + runtime/FBaseRt_ITask.cpp + runtime/FBaseRt_EventDispatcher.cpp + runtime/FBaseRt_EventPendingOperationManager.cpp + runtime/FBaseRtIEventListener.cpp + runtime/FBaseRtLibrary.cpp + runtime/FBaseRt_LibraryImpl.cpp + runtime/FBaseRtTimer.cpp + runtime/FBaseRtMemoryManager.cpp + runtime/FBaseRt_TimerImpl.cpp + runtime/FBaseRt_ThreadImpl.cpp + runtime/FBaseRt_EventDrivenThreadImpl.cpp + runtime/FBaseRt_EventDrivenThreadEventArg.cpp + runtime/FBaseRt_EventDrivenThreadEvent.cpp + runtime/FBaseRt_MainThreadImpl.cpp + runtime/FBaseRtMonitor.cpp + runtime/FBaseRt_MonitorImpl.cpp + runtime/FBaseRtMutex.cpp + runtime/FBaseRt_MutexImpl.cpp + runtime/FBaseRtIRunnable.cpp + runtime/FBaseRtSemaphore.cpp + runtime/FBaseRt_SemaphoreImpl.cpp + runtime/FBaseRtEventDrivenThread.cpp + runtime/FBaseRtThread.cpp + runtime/FBaseRt_ThreadManager.cpp + runtime/FBaseRt_WorkerThreadImpl.cpp + runtime/FBaseRt_WaitingLoopImpl.cpp + runtime/FBaseRtWaitingLoop.cpp + utility/FBaseUtilDeflator.cpp + utility/FBaseUtilStringTokenizer.cpp + utility/FBaseUtilInflator.cpp + utility/FBaseUtilMath.cpp + utility/FBaseUtilLinkInfo.cpp + utility/FBaseUtilZipEntry.cpp + utility/FBaseUtilStringUtil.cpp + utility/FBaseUtilUri.cpp + utility/FBaseUtilFileZipper.cpp + utility/FBaseUtilUrlEncoder.cpp + utility/FBaseUtilFileUnzipper.cpp + utility/FBaseUtil_FileUnzipperImpl.cpp + utility/FBaseUtilUrlDecoder.cpp + utility/FBaseUtilRegularExpression.cpp + utility/FBaseUtil_RegularExpressionImpl.cpp + utility/FBaseUtil_FileZipperImpl.cpp + utility/FBaseUtil_IcuConverter.cpp +) + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") + +## SET EXTRA COMPILER FLAGS +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fPIC" ) + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} STATIC ${${this_target}_SOURCE_FILES}) diff --git a/src/base/FBaseBoolean.cpp b/src/base/FBaseBoolean.cpp new file mode 100644 index 0000000..5166f06 --- /dev/null +++ b/src/base/FBaseBoolean.cpp @@ -0,0 +1,205 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseBool.cpp + * @brief This is the implementation file for Boolean class. + */ + +#include +#include + + +namespace Tizen { namespace Base +{ + +Boolean::Boolean(bool value) + : value(value) + , __pBooleanImpl(null) +{ +} + +Boolean::Boolean(const Boolean& value) + : value(value.value) + , __pBooleanImpl(null) +{ +} + +Boolean::Boolean(const String& value) +{ + const String trueString = L"true"; + String lowString; + + value.ToLower(lowString); + + if (lowString.Equals(trueString)) + { + this->value = true; + } + else + { + this->value = false; + } + + __pBooleanImpl = null; +} + +Boolean::~Boolean(void) +{ +} + +bool +Boolean::operator ==(const Boolean& rhs) const +{ + return(value == rhs.value); +} + +bool +Boolean::operator !=(const Boolean& rhs) const +{ + return(value != rhs.value); +} + +Boolean& +Boolean::operator =(const Boolean& rhs) +{ + if (&rhs != this) + { + value = rhs.value; + } + + return(*this); +} + +bool +Boolean::Equals(const Object& obj) const +{ + const Boolean* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + return *this == *pOther; +} + +int +Boolean::GetHashCode(void) const +{ + return static_cast (value); +} + +bool +Boolean::Equals(bool value) const +{ + return this->value == value; +} + +bool +Boolean::ToBool(void) const +{ + return value; +} + +bool +Boolean::Parse(const String& s) +{ + const String trueString = L"true"; + if (s.Equals(trueString)) + { + return true; + } + + return false; +} + +bool +Boolean::Parse(const String& s, bool caseSensitive) +{ + const String trueString = L"true"; + + if (caseSensitive) + { + if (s.Equals(trueString)) + { + return true; + } + } + else + { + int len = s.GetLength(); + int trueLen = trueString.GetLength(); + + result r = E_SUCCESS; + + if (len != trueLen) + { + return false; + } + + String lowString; + + r = s.ToLower(lowString); + if (!lowString.Equals(trueString)) + { + return false; + } + + return true; + } + + return false; +} + +String +Boolean::ToString(void) const +{ + return(Boolean::ToString(value)); +} + +String +Boolean::ToString(bool value) +{ + String str; + + if (value == true) + { + str = L"true"; + } + else + { + str = L"false"; + } + + return str; +} + +const Boolean +Boolean::GetTrue(void) +{ + static const Boolean True(true); + return True; +} + +const Boolean +Boolean::GetFalse(void) +{ + static const Boolean False(false); + return False; +} + +}} // Tizen::Base diff --git a/src/base/FBaseBufferBase.cpp b/src/base/FBaseBufferBase.cpp new file mode 100644 index 0000000..0662b53 --- /dev/null +++ b/src/base/FBaseBufferBase.cpp @@ -0,0 +1,323 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseBufferBase.cpp + * @brief This is the implementation for BufferBase class. + */ + +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base +{ + +BufferBase::BufferBase(void) + : _capacity(0) + , _position(0) + , _limit(0) + , _mark(-1) + , _pData(null) + , __pArrayStart(null) + , __pBufferBaseImpl(null) +{ +} + +BufferBase::~BufferBase(void) +{ + if ((_pData != null) && (Release() == 0)) + { + free(_pData); + _pData = null; + } +} + +result +BufferBase::Construct(int capacity) +{ + SysTryReturn(NID_BASE, capacity >= 0, E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used. The capacity is negative", GetErrorMessage(E_INVALID_ARG)); + + result r = E_SUCCESS; + void* pTemp = null; + + // check whether the size of memory is larger than the maximum of unsigned int + unsigned long long size = static_cast (sizeof(_BufferData)) + + static_cast (capacity) * static_cast (GetTypeSize()); + SysTryReturnResult(NID_BASE, size <= static_cast ((unsigned int) -1), E_OUT_OF_MEMORY, + "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + pTemp = malloc(static_cast (size)); + SysTryReturnResult(NID_BASE, 0 != pTemp, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(pTemp, 0, static_cast (size)); + + _pData = static_cast <_BufferData*>(pTemp); + + _pData->refCount = 1; + _pData->capacityInByte = capacity * GetTypeSize(); + + _capacity = capacity; + _limit = capacity; + + if (capacity > 0) + { + __pArrayStart = _pData->GetArray(); + } + + return r; +} + +void +BufferBase::Clear(void) +{ + _position = 0; + _limit = _capacity; + _mark = -1; +} + +void +BufferBase::Compact(void) +{ + int remaining = GetRemaining(); + if (HasRemaining() && (0 != _position)) + { + int offset = _position * GetTypeSize(); + int byteNum = remaining * GetTypeSize(); + for (int i = 0; i < byteNum; i++) + { + __pArrayStart[i] = __pArrayStart[offset + i]; + } + } + _position = remaining; + _mark = -1; + _limit = _capacity; +} + +void +BufferBase::Flip(PositionTo to) +{ + _limit = _position; + if ((to == POSITION_TO_MARK) && (_mark > -1)) + { + _position = _mark; + } + else + { + _position = 0; + _mark = -1; + } +} + +int +BufferBase::GetHashCode(void) const +{ + int len = (GetRemaining() * GetTypeSize()) / sizeof(len); + + // s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] + int hash = 0; + int offset = _position * GetTypeSize(); + for (int i = 0; i < len; ++i) + { + hash += (int) __pArrayStart[offset + (i * sizeof(hash))] * (int) pow((double) 31, len - (i + 1)); + } + + return hash; +} + +void +BufferBase::InvalidateMark(void) +{ + _mark = -1; +} + +result +BufferBase::Reset(void) +{ + SysTryReturnResult(NID_BASE, _mark >= 0, E_INVALID_OPERATION, "[%s] The mark has not been set.", + GetErrorMessage(E_INVALID_OPERATION)); + + _position = _mark; + return E_SUCCESS; +} + +void +BufferBase::Rewind(void) +{ + _position = 0; + _mark = -1; +} + +result +BufferBase::ShiftLimit(int amount) +{ + SysTryReturnResult(NID_BASE, (((_limit + amount) <= _capacity) && ((_limit + amount) >= 0)), E_OUT_OF_RANGE, + "The amount(%d) is larger than the capacity(%d), or smaller than zero starting from the current limit(%d).", + amount, _capacity, _limit); + + return SetLimit(_limit + amount); +} + +int +BufferBase::GetCapacity(void) const +{ + return _capacity; +} + +int +BufferBase::GetLimit(void) const +{ + return _limit; +} + +int +BufferBase::GetMark(void) const +{ + return _mark; +} + +int +BufferBase::GetPosition(void) const +{ + return _position; +} + +int +BufferBase::GetRemaining(void) const +{ + return _limit - _position; +} + +result +BufferBase::SetLimit(int limit) +{ + SysTryReturnResult(NID_BASE, limit <= _capacity && limit >= 0, E_OUT_OF_RANGE, + "The limit(%d) MUST be greater than or equal to 0 and less than the current capacity(%d).", limit, _capacity); + + if (limit != _limit) + { + _limit = limit; + if (_position > limit) + { + _position = limit; + if (_mark > limit) + { + _mark = -1; + } + } + } + return E_SUCCESS; +} + +void +BufferBase::SetMark(void) +{ + _mark = _position; +} + +result +BufferBase::SetPosition(int position) +{ + SysTryReturnResult(NID_BASE, position <= _limit && position >= 0, E_OUT_OF_RANGE, + "The position(%d) MUST be greater than or equal to 0 and less than the current limit(%d).", position, _limit); + + _position = position; + if (_mark > _position) + { + _mark = -1; + } + + return E_SUCCESS; +} + +bool +BufferBase::HasRemaining(void) const +{ + return _limit > _position; +} + +result +BufferBase::ExpandCapacity(int newCapacity) +{ + SysTryReturnResult(NID_BASE, newCapacity > _capacity, E_INVALID_ARG, + "The capacity is less than the current capacity."); + + // check whether the size of memory is larger than the maximum of unsigned int + unsigned long long size = static_cast (sizeof(_BufferData)) + + static_cast (newCapacity) * static_cast (GetTypeSize()); + + SysTryReturnResult(NID_BASE, size <= static_cast ((unsigned int) -1), E_OUT_OF_MEMORY, + "Memory allocation failed."); + + _pData = static_cast<_BufferData*>(realloc(_pData, static_cast(size))); + SysTryReturnResult(NID_BASE, 0 != _pData, E_OUT_OF_MEMORY, "Memory allocation failed."); + + _capacity = newCapacity; + _limit = newCapacity; + + __pArrayStart = _pData->GetArray(); + + return E_SUCCESS; +} + +long +BufferBase::AddRef(void) const +{ + SysAssertf(_pData->refCount > 0, "refCount(%d) is not greater than zero.", _pData->refCount); + + _pData->refCount++; + + return _pData->refCount; +} + +long +BufferBase::Release(void) const +{ + SysAssertf(_pData->refCount > 0, "refCount is not greater than zero(impossible!)."); + + _pData->refCount--; + + return _pData->refCount; +} + +void +BufferBase::Dispose(void) +{ +} + +BufferBase::_BufferData::_BufferData() + :capacityInByte(0) + ,refCount(0) +{ +} + +BufferBase::_BufferData::~_BufferData() +{ +} + +byte* +BufferBase::_BufferData::GetArray(void) +{ + return reinterpret_cast (this + 1); +} + +}} // Tizen::Base diff --git a/src/base/FBaseByteBuffer.cpp b/src/base/FBaseByteBuffer.cpp new file mode 100644 index 0000000..90eab78 --- /dev/null +++ b/src/base/FBaseByteBuffer.cpp @@ -0,0 +1,871 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseByteBuffer.cpp + * @brief This is the implementation for ByteBuffer class. + */ + +#include +#include +#include +#include + + +static const byte DOUBLE_SIZE = sizeof(double); +static const byte FLOAT_SIZE = sizeof(float); +static const byte INT_SIZE = sizeof(int); +static const byte LONG_SIZE = sizeof(long); +static const byte LONGLONG_SIZE = sizeof(long long); +static const byte MCHAR_SIZE = sizeof(wchar_t); +static const byte SHORT_SIZE = sizeof(short); + +namespace Tizen { namespace Base +{ + +ByteBuffer::ByteBuffer(void) + : __pByteBufferImpl(null) +{ +} + +ByteBuffer::~ByteBuffer(void) +{ +} + +result +ByteBuffer::Construct(const ByteBuffer& buffer) +{ + SysTryReturn(NID_BASE, null != buffer._pData, E_INVALID_ARG, E_INVALID_ARG, + "[%s] The source buffer is not constructed.", GetErrorMessage(E_INVALID_ARG)); + + _capacity = buffer._capacity; + _position = buffer._position; + _limit = buffer._limit; + _mark = buffer._mark; + _pData = buffer._pData; + + AddRef(); + __pArrayStart = buffer.__pArrayStart; + + return E_SUCCESS; +} + +result +ByteBuffer::Construct(int capacity) +{ + result r = BufferBase::Construct(capacity); + if (r != E_SUCCESS) + { + SysLogException(NID_BASE, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + return r; +} + +result +ByteBuffer::Construct(const byte *pBuffer, int index, int length, int capacity) +{ + SysTryReturn(NID_BASE, pBuffer != null, E_INVALID_ARG, E_INVALID_ARG, "[%s] The pBuffer is null.", + GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_BASE, index >= 0 && length >= 0 && capacity >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] index(%d), length(%d) and capacity(%d) MUST be greater than or equal to 0.", + GetErrorMessage(E_OUT_OF_RANGE), index, length, capacity); + SysTryReturn(NID_BASE, index < capacity && length <= capacity && index + length <= capacity, + E_OUT_OF_RANGE, E_OUT_OF_RANGE, "[%s] index(%d), length(%d) and capacity(%d) MUST be greater than or equal to 0.", + GetErrorMessage(E_OUT_OF_RANGE), index, length, capacity); + + void* pTemp = null; + int sizeofBufferData = sizeof(_BufferData); + + __pArrayStart = const_cast (pBuffer + index); + + pTemp = malloc(sizeofBufferData); + SysTryReturn(NID_BASE, pTemp != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s]", GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(pTemp, 0, sizeofBufferData); + _pData = static_cast <_BufferData*>(pTemp); + + _pData->refCount = 1; + _pData->capacityInByte = capacity; + + _capacity = capacity; + _limit = length; + + return E_SUCCESS; +} + +byte& +ByteBuffer::operator [](int index) +{ + SysAssertf(index < _limit, "index out of range.\n"); + SysAssertf(index >= 0, "index out of range.\n"); + + return __pArrayStart[index]; +} + +byte +ByteBuffer::operator [](int index) const +{ + return const_cast(*this)[index]; +} + +bool +ByteBuffer::operator ==(const ByteBuffer& buffer) const +{ + bool r = true; + + if (this == &buffer) + { + r = true; + } + else if (GetRemaining() != buffer.GetRemaining()) + { + r = false; + } + else + { + for (int i = 0; i < GetRemaining(); ++i) + { + if (__pArrayStart[_position + i] != buffer.__pArrayStart[buffer._position + i]) + { + r = false; + break; + } + } + } + + return r; +} + +bool +ByteBuffer::operator !=(const ByteBuffer& buffer) const +{ + return !(*this == buffer); +} + +DoubleBuffer* +ByteBuffer::AsDoubleBufferN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) DoubleBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining() / DOUBLE_SIZE; + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +FloatBuffer* +ByteBuffer::AsFloatBufferN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) FloatBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining() / FLOAT_SIZE; + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +IntBuffer* +ByteBuffer::AsIntBufferN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) IntBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining() / INT_SIZE; + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +LongBuffer* +ByteBuffer::AsLongBufferN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) LongBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining() / LONG_SIZE; + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +LongLongBuffer* +ByteBuffer::AsLongLongBufferN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) LongLongBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining() / LONGLONG_SIZE; + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +McharBuffer* +ByteBuffer::AsMcharBufferN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) McharBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining() / MCHAR_SIZE; + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +WcharBuffer* +ByteBuffer::AsWcharBufferN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) WcharBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining() / MCHAR_SIZE; + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +ShortBuffer* +ByteBuffer::AsShortBufferN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) ShortBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining() / SHORT_SIZE; + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +result +ByteBuffer::CopyFrom(ByteBuffer& buffer) +{ + SysTryReturn(NID_BASE, this != static_cast (&buffer), E_INVALID_ARG, E_INVALID_ARG, + "[%s] The source and target buffers are identical.", GetErrorMessage(E_INVALID_ARG)); + int copyLength = buffer.GetRemaining(); + SysTryReturn(NID_BASE, + GetRemaining() >= copyLength, E_OVERFLOW, E_OVERFLOW, + "[%s] The current buffer is smaller than the input buffer.", GetErrorMessage(E_OVERFLOW)); + + memcpy(__pArrayStart + _position, buffer.__pArrayStart + buffer._position, copyLength); + _position += copyLength; + buffer._position += copyLength; + + return E_SUCCESS; +} + +result +ByteBuffer::GetArray(byte* pArray, int index, int length) +{ + SysTryReturn(NID_BASE, null != pArray, E_INVALID_ARG, E_INVALID_ARG, "[%s] The pArray is null.", + GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_BASE, index >= 0 && length >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] Both of index(%d) and length(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), + index, length); + SysTryReturn(NID_BASE, GetRemaining() >= length, E_UNDERFLOW, E_UNDERFLOW, "[%s]", GetErrorMessage(E_UNDERFLOW)); + + memcpy(pArray + index, __pArrayStart + _position, length); + _position += length; + + return E_SUCCESS; +} + +result +ByteBuffer::GetByte(byte& value) +{ + SysTryReturn(NID_BASE, _position < _limit, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The current position is not smaller than the limit.", GetErrorMessage(E_UNDERFLOW)); + + value = __pArrayStart[_position++]; + + return E_SUCCESS; +} + +result +ByteBuffer::GetByte(int index, byte& value) const +{ + SysTryReturn(NID_BASE, index < _limit && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the current limit(%d).", GetErrorMessage(E_OUT_OF_RANGE), + index, _limit); + + value = __pArrayStart[index]; + + return E_SUCCESS; +} + +result +ByteBuffer::GetDouble(double& value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= DOUBLE_SIZE, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The remaining bytes of this buffer are smaller than the size of double", GetErrorMessage(E_UNDERFLOW)); + + value = *reinterpret_cast (&__pArrayStart[_position]); + _position += DOUBLE_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::GetDouble(int index, double& value) const +{ + SysTryReturn(NID_BASE, + index <= (_limit - DOUBLE_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of double(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, DOUBLE_SIZE); + + value = *reinterpret_cast (&__pArrayStart[index]); + + return E_SUCCESS; +} + +result +ByteBuffer::GetFloat(float& value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= FLOAT_SIZE, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The remaining bytes of this buffer are smaller than the size of float.", GetErrorMessage(E_UNDERFLOW)); + + value = *reinterpret_cast (&__pArrayStart[_position]); + _position += FLOAT_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::GetFloat(int index, float& value) const +{ + SysTryReturn(NID_BASE, + index <= (_limit - FLOAT_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of float(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, FLOAT_SIZE); + + value = *reinterpret_cast (&__pArrayStart[index]); + + return E_SUCCESS; +} + +result +ByteBuffer::GetInt(int& value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= INT_SIZE, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The remaining bytes of this buffer are smaller than the size of int.", GetErrorMessage(E_UNDERFLOW)); + + value = *reinterpret_cast (&__pArrayStart[_position]); + _position += INT_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::GetInt(int index, int& value) const +{ + SysTryReturn(NID_BASE, + index <= (_limit - INT_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of int(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, INT_SIZE); + + value = *reinterpret_cast (&__pArrayStart[index]); + + return E_SUCCESS; +} + +result +ByteBuffer::GetLong(long& value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= LONG_SIZE, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The remaining bytes of this buffer are smaller than the size of long.", GetErrorMessage(E_UNDERFLOW)); + + value = *reinterpret_cast (&__pArrayStart[_position]); + _position += LONG_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::GetLong(int index, long& value) const +{ + SysTryReturn(NID_BASE, + index <= (_limit - LONG_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of long(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, LONG_SIZE); + + value = *reinterpret_cast (&__pArrayStart[index]); + + return E_SUCCESS; +} + +result +ByteBuffer::GetLongLong(long long& value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= LONGLONG_SIZE, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The remaining bytes of this buffer are smaller than the size of long long.", GetErrorMessage(E_UNDERFLOW)); + + value = *reinterpret_cast (&__pArrayStart[_position]); + _position += LONGLONG_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::GetLongLong(int index, long long& value) const +{ + SysTryReturn(NID_BASE, + index <= (_limit - LONGLONG_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of long long(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, LONGLONG_SIZE); + + value = *reinterpret_cast (&__pArrayStart[index]); + + return E_SUCCESS; +} + +result +ByteBuffer::GetMchar(wchar_t& value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= MCHAR_SIZE, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The remaining bytes of this buffer are smaller than the size of wchar_t.", GetErrorMessage(E_UNDERFLOW)); + + value = *reinterpret_cast (&__pArrayStart[_position]); + _position += MCHAR_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::GetWchar(wchar_t& value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= MCHAR_SIZE, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The remaining bytes of this buffer are smaller than the size of wchar_t.", GetErrorMessage(E_UNDERFLOW)); + + value = *reinterpret_cast (&__pArrayStart[_position]); + _position += MCHAR_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::GetMchar(int index, wchar_t& value) const +{ + SysTryReturn(NID_BASE, + index <= (_limit - MCHAR_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of wchar_t(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, MCHAR_SIZE); + + value = *reinterpret_cast (&__pArrayStart[index]); + + return E_SUCCESS; +} + +result +ByteBuffer::GetWchar(int index, wchar_t& value) const +{ + SysTryReturn(NID_BASE, + index <= (_limit - MCHAR_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of wchar_t(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, MCHAR_SIZE); + + value = *reinterpret_cast (&__pArrayStart[index]); + + return E_SUCCESS; +} + +result +ByteBuffer::GetShort(short& value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= SHORT_SIZE, E_UNDERFLOW, E_UNDERFLOW, + "[%s] The remaining bytes of this buffer are smaller than the size of short.", GetErrorMessage(E_UNDERFLOW)); + + value = *reinterpret_cast (&__pArrayStart[_position]); + _position += SHORT_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::GetShort(int index, short& value) const +{ + SysTryReturn(NID_BASE, + index <= (_limit - SHORT_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of short(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, SHORT_SIZE); + + value = *reinterpret_cast (&__pArrayStart[index]); + + return E_SUCCESS; +} + +result +ByteBuffer::ReadFrom(ByteBuffer& buffer) +{ + SysTryReturn(NID_BASE, this != static_cast (&buffer), E_INVALID_ARG, E_INVALID_ARG, + "[%s] The source and target buffers are identical.", GetErrorMessage(E_INVALID_ARG)); + + int copyLength = (GetRemaining() < buffer.GetRemaining()) ? GetRemaining() : buffer.GetRemaining(); + memcpy(__pArrayStart + _position, buffer.__pArrayStart + buffer._position, copyLength); + _position += copyLength; + buffer._position += copyLength; + + return E_SUCCESS; +} + +result +ByteBuffer::SetArray(const byte* pArray, int index, int length) +{ + SysTryReturn(NID_BASE, null != pArray, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The pArray is null."); + SysTryReturn(NID_BASE, index >= 0 && length >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] Both of index(%d) and length(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), + index, length); + SysTryReturn(NID_BASE, GetRemaining() >= length, E_OVERFLOW, E_OVERFLOW, "[%s] The remaining bytes are smaller than length.", + GetErrorMessage(E_OVERFLOW)); + + memcpy(__pArrayStart + _position, pArray + index, length); + _position += length; + + return E_SUCCESS; +} + +result +ByteBuffer::SetByte(byte value) +{ + SysTryReturn(NID_BASE, _position < _limit, E_OVERFLOW, E_OVERFLOW, + "[%s] The current position is not smaller than the limit.", GetErrorMessage(E_OVERFLOW)); + + __pArrayStart[_position++] = value; + return E_SUCCESS; +} + +result +ByteBuffer::SetByte(int index, byte value) +{ + SysTryReturn(NID_BASE, index < _limit && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the current limit(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit); + + __pArrayStart[index] = value; + return E_SUCCESS; +} + +result +ByteBuffer::SetDouble(double value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= DOUBLE_SIZE, E_OVERFLOW, E_OVERFLOW, + "[%s] The remaining bytes of this buffer are smaller than size of double.", GetErrorMessage(E_OVERFLOW)); + + *reinterpret_cast (&__pArrayStart[_position]) = value; + _position += DOUBLE_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::SetDouble(int index, double value) +{ + SysTryReturn(NID_BASE, + index <= (_limit - DOUBLE_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of double(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, DOUBLE_SIZE); + + *reinterpret_cast (&__pArrayStart[index]) = value; + + return E_SUCCESS; +} + +result +ByteBuffer::SetFloat(float value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= FLOAT_SIZE, E_OVERFLOW, E_OVERFLOW, + "[%s] The remaining bytes of this buffer are smaller than size of float.", GetErrorMessage(E_OVERFLOW)); + + *reinterpret_cast (&__pArrayStart[_position]) = value; + _position += FLOAT_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::SetFloat(int index, float value) +{ + SysTryReturn(NID_BASE, + index <= (_limit - FLOAT_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of float(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, FLOAT_SIZE); + + *reinterpret_cast (&__pArrayStart[index]) = value; + + return E_SUCCESS; +} + +result +ByteBuffer::SetInt(int value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= INT_SIZE, E_OVERFLOW, E_OVERFLOW, + "[%s] The remaining bytes of this buffer are smaller than size of int.", GetErrorMessage(E_OVERFLOW)); + + *reinterpret_cast (&__pArrayStart[_position]) = value; + _position += INT_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::SetInt(int index, int value) +{ + SysTryReturn(NID_BASE, + index <= (_limit - INT_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of int(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, INT_SIZE); + + *reinterpret_cast (&__pArrayStart[index]) = value; + + return E_SUCCESS; +} + +result +ByteBuffer::SetLong(long value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= LONG_SIZE, E_OVERFLOW, E_OVERFLOW, + "[%s] The remaining bytes of this buffer are smaller than size of long.", GetErrorMessage(E_OVERFLOW)); + + *reinterpret_cast (&__pArrayStart[_position]) = value; + _position += LONG_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::SetLong(int index, long value) +{ + SysTryReturn(NID_BASE, + index <= (_limit - LONG_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of long(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, LONG_SIZE); + + *reinterpret_cast (&__pArrayStart[index]) = value; + + return E_SUCCESS; +} + +result +ByteBuffer::SetLongLong(long long value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= LONGLONG_SIZE, E_OVERFLOW, E_OVERFLOW, + "[%s] The remaining bytes of this buffer are smaller than size of long long.", GetErrorMessage(E_OVERFLOW)); + + *reinterpret_cast (&__pArrayStart[_position]) = value; + _position += LONGLONG_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::SetLongLong(int index, long long value) +{ + SysTryReturn(NID_BASE, + index <= (_limit - LONGLONG_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of long long(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, LONGLONG_SIZE); + + *reinterpret_cast (&__pArrayStart[index]) = value; + + return E_SUCCESS; +} + +result +ByteBuffer::SetMchar(wchar_t value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= MCHAR_SIZE, E_OVERFLOW, E_OVERFLOW, + "[%s] The remaining bytes of this buffer are smaller than size of wchar_t.", GetErrorMessage(E_OVERFLOW)); + + *reinterpret_cast (&__pArrayStart[_position]) = value; + _position += MCHAR_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::SetWchar(wchar_t value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= MCHAR_SIZE, E_OVERFLOW, E_OVERFLOW, + "[%s] The remaining bytes of this buffer are smaller than size of wchar_t.", GetErrorMessage(E_OVERFLOW)); + + *reinterpret_cast (&__pArrayStart[_position]) = value; + _position += MCHAR_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::SetMchar(int index, wchar_t value) +{ + SysTryReturn(NID_BASE, + index <= (_limit - MCHAR_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of wchar_t(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, MCHAR_SIZE); + + *reinterpret_cast (&__pArrayStart[index]) = value; + + return E_SUCCESS; +} + +result +ByteBuffer::SetWchar(int index, wchar_t value) +{ + SysTryReturn(NID_BASE, + index <= (_limit - MCHAR_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of wchar_t(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, MCHAR_SIZE); + + *reinterpret_cast (&__pArrayStart[index]) = value; + + return E_SUCCESS; +} + +result +ByteBuffer::SetShort(short value) +{ + SysTryReturn(NID_BASE, + GetRemaining() >= SHORT_SIZE, E_OVERFLOW, E_OVERFLOW, + "[%s] The remaining bytes of this buffer are smaller than size of short.", GetErrorMessage(E_OVERFLOW)); + + *reinterpret_cast (&__pArrayStart[_position]) = value; + _position += SHORT_SIZE; + + return E_SUCCESS; +} + +result +ByteBuffer::SetShort(int index, short value) +{ + SysTryReturn(NID_BASE, + index <= (_limit - SHORT_SIZE) && index >= 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less then the 'current limit(%d) - size of short(%d)'.", + GetErrorMessage(E_OUT_OF_RANGE), index, _limit, SHORT_SIZE); + + *reinterpret_cast (&__pArrayStart[index]) = value; + + return E_SUCCESS; +} + +ByteBuffer* +ByteBuffer::SliceN(void) const +{ + std::unique_ptr pBuffer(new (std::nothrow) ByteBuffer()); + pBuffer->_pData = _pData; + AddRef(); + pBuffer->_capacity = GetRemaining(); + pBuffer->_limit = pBuffer->_capacity; + if (pBuffer->_capacity > 0) + { + pBuffer->__pArrayStart = &__pArrayStart[_position]; + } + + return pBuffer.release(); +} + +const byte* +ByteBuffer::GetPointer(void) const +{ + return __pArrayStart; +} + +bool +ByteBuffer::Equals(const Tizen::Base::Object& obj) const +{ + bool out = false; + const ByteBuffer* pOther = dynamic_cast (&obj); + if (pOther == null) + { + out = false; + } + else if ((pOther == this) || (*pOther == *this)) + { + out = true; + } + + return out; +} + +int +ByteBuffer::GetHashCode(void) const +{ + int len = GetRemaining() / sizeof(len); + + int hash = 0; + int offset = _position; + for (int i = 0; i < len; ++i) + { + hash = (hash << 5) - hash + static_cast (__pArrayStart[offset + (i * sizeof(hash))]); + } + + return hash; +} + +int +ByteBuffer::GetTypeSize(void) const +{ + return 1; +} + +}} // Tizen::Base diff --git a/src/base/FBaseCharacter.cpp b/src/base/FBaseCharacter.cpp new file mode 100644 index 0000000..1d721d6 --- /dev/null +++ b/src/base/FBaseCharacter.cpp @@ -0,0 +1,292 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseCharacter.cpp + * @brief This is the implementation file for Char class. + */ + +#include +#include +#include +#include +#include "FBase_CharacterImpl.h" + + +namespace Tizen { namespace Base +{ + +Character::Character(wchar_t value) + : __val(value) + , __pCharacterImpl(null) +{ +} + +Character::Character(const Character& value) + : __val(value.__val) + , __pCharacterImpl(null) +{ +} + +Character::~Character(void) +{ +} + +Character& +Character::operator =(const Character& rhs) +{ + if (&rhs != this) + { + __val = rhs.__val; + } + return *this; +} + +int +Character::CompareTo(const Character& value) const +{ + return __val - value.__val; +} + +bool +Character::Equals(const Object& obj) const +{ + const Character* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + return((*this).CompareTo((*pOther).ToMchar()) == 0 ? true : false); +} + +int +Character::GetHashCode(void) const +{ + return __val; +} + +wchar_t +Character::ToMchar(void) const +{ + return __val; +} + +void +Character::ToLower(void) +{ + if (IsUpper(__val)) + { + __val = towlower(__val); + } +} + +void +Character::ToLowerCase(void) +{ + __val = _CharacterImpl::ToLowerCase(__val); +} + +void +Character::ToUpper(void) +{ + if (IsLower(__val)) + { + __val = towupper(__val); + } +} + +void +Character::ToUpperCase(void) +{ + __val = _CharacterImpl::ToUpperCase(__val); +} + +String +Character::ToString(void) const +{ + return Character::ToString(__val); +} + +String +Character::ToString(wchar_t value) +{ + return String(value); +} + +UnicodeCategory +Character::GetUnicodeCategory(wchar_t ch) +{ + return _CharacterImpl::GetUnicodeCategory(ch); +} + +wchar_t +Character::ToLower(wchar_t ch) +{ + if (IsUpper(ch)) + { + return towlower(ch); + } + else + { + return ch; + } +} + +wchar_t +Character::ToLowerCase(wchar_t ch) +{ + return _CharacterImpl::ToLowerCase(ch); +} + +wchar_t +Character::ToUpper(wchar_t ch) +{ + if (IsLower(ch)) + { + return towupper(ch); + } + else + { + return ch; + } +} + +wchar_t +Character::ToUpperCase(wchar_t ch) +{ + return _CharacterImpl::ToUpperCase(ch); +} + +bool +Character::IsAlphaNumeric(wchar_t ch) +{ + if (_CharacterImpl::IsLetter(ch)) + { + return true; + } + + if (_CharacterImpl::IsDigit(ch)) + { + return true; + } + + return false; +} + +bool +Character::IsDigit(wchar_t ch) +{ + if (_CharacterImpl::IsDigit(ch)) + { + return true; + } + + return false; +} + +bool +Character::IsLetter(wchar_t ch) +{ + + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + return(iswalpha(ch) !=0); + } + else + { + return _CharacterImpl::IsLetter(ch); + } +} + +bool +Character::IsLower(wchar_t ch) +{ + return(iswlower(ch) != 0); +} + +bool +Character::IsLowerCase(wchar_t ch) +{ + return(Character::ToUpperCase(ch) != ch); +} + +bool +Character::IsUpper(wchar_t ch) +{ + return(iswupper(ch) != 0); +} + +bool +Character::IsUpperCase(wchar_t ch) +{ + return(Character::ToLowerCase(ch) != ch); +} + +int +Character::ToDigit(wchar_t ch, int radix) +{ + return _CharacterImpl::ToDigit(ch, radix); +} + + +wchar_t +Character::ForDigit(int digit, int radix) +{ + return _CharacterImpl::ForDigit(digit, radix); +} + + +double +Character::GetNumericValue(wchar_t ch) +{ + return _CharacterImpl::GetNumericValue(ch); +} + + +bool +Character::IsDefined(wchar_t ch) +{ + return _CharacterImpl::IsDefined(ch); +} + + +bool +Character::IsWhitespace(wchar_t ch) +{ + return _CharacterImpl::IsWhitespace(ch); +} + +bool +Character::IsTitleCase(wchar_t ch) +{ + return _CharacterImpl::IsTitleCase(ch); +} + +wchar_t +Character::ToTitleCase(wchar_t ch) +{ + return _CharacterImpl::ToTitleCase(ch); +} + +bool +Character::IsISOControl(wchar_t ch) +{ + return _CharacterImpl::IsISOControl(ch); +} + +}} // Tizen::Base diff --git a/src/base/FBaseDateTime.cpp b/src/base/FBaseDateTime.cpp new file mode 100644 index 0000000..ced0cea --- /dev/null +++ b/src/base/FBaseDateTime.cpp @@ -0,0 +1,925 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDateTime.cpp + * @brief This file contains implementation of DateTime class + */ + +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base +{ + +enum DateTimeLimits +{ + MIN_YEAR = 1, + MIN_MONTH = 1, + MIN_DAY = 1, + MIN_HOUR = 0, + MIN_MINUTE = 0, + MIN_SECOND = 0, + _MAX_YEAR = 9999, + MAX_MONTH = 12, + MAX_DAY = 31, + MAX_HOUR = 23, + MAX_MINUTE = 59, + MAX_SECOND = 59, + NUM_OF_SEC_IN_DAY = 86400, + NUM_OF_SEC_IN_HOUR = 3600, + NUM_OF_SEC_IN_MINUTE = 60, + NUM_OF_MILLISEC_IN_DAY = 86400000LL, + NUM_OF_MILLISEC_IN_HOUR = 3600000LL, + NUM_OF_MILLISEC_IN_MINUTE = 60000LL +}; + +static const long SEC_IN_A_DAY = (24L * 60L * 60L); +static const long long MINIMUM_VALUE_IN_SEC = 86400LL; +static const int DAYS_IN_LEAP_YEAR[] = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; +static const int DAYS[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; + +DateTime::DateTime(void) + : __pDateTimeImpl(null) +{ + SetValue(MIN_YEAR, MIN_MONTH, MIN_DAY, MIN_HOUR, MIN_MINUTE, MIN_SECOND); +} + +DateTime::DateTime(const DateTime& value) + : __pDateTimeImpl(null) +{ + SetValue(value); +} + +DateTime::~DateTime(void) +{ +} + +result +DateTime::SetValue(const TimeSpan& value) +{ + long long total = (long long) (value.GetTicks() / 1000) + MINIMUM_VALUE_IN_SEC; + SysTryReturn(NID_BASE, total >= NUM_OF_SEC_IN_DAY, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The value of the argument is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE)); + + long long maxSeconds = (long long) (DateTime::GetMaxValue().GetTime().GetTicks() / 1000) + MINIMUM_VALUE_IN_SEC; + SysTryReturn(NID_BASE, total <= maxSeconds, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The value of the argument is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE)); + + return ConvertSecondsToDate(total, &__dateTime); +} + +void +DateTime::SetValue(const DateTime& value) +{ + __dateTime.year = value.__dateTime.year; + __dateTime.month = value.__dateTime.month; + __dateTime.day = value.__dateTime.day; + __dateTime.hour = value.__dateTime.hour; + __dateTime.minute = value.__dateTime.minute; + __dateTime.second = value.__dateTime.second; +} + +result +DateTime::SetValue(int year, int month, int day, int hour, int minute, int second) +{ + SysTryReturn(NID_BASE, + ((year >= MIN_YEAR && year <= _MAX_YEAR) && + (month >= MIN_MONTH && month <= MAX_MONTH) && + (hour >= MIN_HOUR && hour <= MAX_HOUR) && + (minute >= MIN_MINUTE && minute <= MAX_MINUTE) && + (second >= MIN_SECOND && second <= MAX_SECOND)), + E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] One of the year(%d), month(%d), day(%d), hour(%d), minute(%d), and second(%d) is in out of allowable range.", + GetErrorMessage(E_OUT_OF_RANGE), year, month, day, hour, minute, second); + + int daysInMonth = 0; + result r = GetDaysInMonth(year, month, daysInMonth); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + SysTryReturn(NID_BASE, (day >= MIN_DAY && day <= daysInMonth), E_OUT_OF_RANGE, E_OUT_OF_RANGE, + ("[%s] day is in out of allowable range."), GetErrorMessage(E_OUT_OF_RANGE)); + + __dateTime.year = year; + __dateTime.month = month; + __dateTime.day = day; + __dateTime.hour = hour; + __dateTime.minute = minute; + __dateTime.second = second; + + return(E_SUCCESS); +} + +DateTime& +DateTime::operator =(const DateTime& rhs) +{ + if (&rhs != this) + { + SetValue(rhs); + } + + return(*this); +} + +bool +DateTime::operator ==(const DateTime& rhs) const +{ + return((__dateTime.year == rhs.__dateTime.year) && (__dateTime.month == rhs.__dateTime.month) + && (__dateTime.day == rhs.__dateTime.day) && (__dateTime.hour == rhs.__dateTime.hour) && + (__dateTime.minute == rhs.__dateTime.minute) && (__dateTime.second == rhs.__dateTime.second)); +} + +bool +DateTime::operator !=(const DateTime& rhs) const +{ + return !(*this == rhs); +} + +bool +DateTime::operator <(const DateTime& rhs) const +{ + if (__dateTime.year < rhs.__dateTime.year) + { + return true; + } + if (__dateTime.year > rhs.__dateTime.year) + { + return false; + } + if (__dateTime.month < rhs.__dateTime.month) + { + return true; + } + if (__dateTime.month > rhs.__dateTime.month) + { + return false; + } + if (__dateTime.day < rhs.__dateTime.day) + { + return true; + } + if (__dateTime.day > rhs.__dateTime.day) + { + return false; + } + if (__dateTime.hour < rhs.__dateTime.hour) + { + return true; + } + if (__dateTime.hour > rhs.__dateTime.hour) + { + return false; + } + if (__dateTime.minute < rhs.__dateTime.minute) + { + return true; + } + if (__dateTime.minute > rhs.__dateTime.minute) + { + return false; + } + if (__dateTime.second < rhs.__dateTime.second) + { + return true; + } + + return false; +} + +bool +DateTime::operator >(const DateTime& rhs) const +{ + if (__dateTime.year > rhs.__dateTime.year) + { + return true; + } + if (__dateTime.year < rhs.__dateTime.year) + { + return false; + } + if (__dateTime.month > rhs.__dateTime.month) + { + return true; + } + if (__dateTime.month < rhs.__dateTime.month) + { + return false; + } + if (__dateTime.day > rhs.__dateTime.day) + { + return true; + } + if (__dateTime.day < rhs.__dateTime.day) + { + return false; + } + if (__dateTime.hour > rhs.__dateTime.hour) + { + return true; + } + if (__dateTime.hour < rhs.__dateTime.hour) + { + return false; + } + if (__dateTime.minute > rhs.__dateTime.minute) + { + return true; + } + if (__dateTime.minute < rhs.__dateTime.minute) + { + return false; + } + if (__dateTime.second > rhs.__dateTime.second) + { + return true; + } + return false; +} + +bool +DateTime::operator <=(const DateTime& rhs) const +{ + return((*this == rhs) || (*this < rhs)); +} + +bool +DateTime::operator >=(const DateTime& rhs) const +{ + return((*this == rhs) || (*this > rhs)); +} + +result +DateTime::Add(const TimeSpan& t) +{ + + long long seconds = ConvertDateToSeconds(&__dateTime); + long long total = (long long) (t.GetTicks() / 1000) + seconds; + + SysTryReturn(NID_BASE, total >= NUM_OF_SEC_IN_DAY, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The value of the argument is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE)); + + long long maxSeconds = ConvertDateToSeconds(&(DateTime::GetMaxValue().__dateTime)); + SysTryReturn(NID_BASE, total <= maxSeconds, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The value of the argument is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE)); + + result r = ConvertSecondsToDate(total, &__dateTime); + if (r != E_SUCCESS) + { + SysLogException(NID_BASE, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; +} + +result +DateTime::AddDays(int days) +{ + TimeSpan ts(days * NUM_OF_SEC_IN_DAY * 1000LL); + + result r = Add(ts); + if (IsFailed(r)) + { + SysLogException(NID_BASE, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; +} + +result +DateTime::AddHours(int hours) +{ + TimeSpan ts(hours * NUM_OF_SEC_IN_HOUR * 1000LL); + + result r = Add(ts); + if (IsFailed(r)) + { + SysLogException(NID_BASE, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; +} + +result +DateTime::AddMinutes(int minutes) +{ + TimeSpan ts(minutes * NUM_OF_SEC_IN_MINUTE * 1000LL); + + result r = Add(ts); + if (IsFailed(r)) + { + SysLogException(NID_BASE, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; +} + +result +DateTime::AddMonths(int months) +{ + DateTime tmp; + tmp.SetValue(*this); + + tmp.__dateTime.year += months / MAX_MONTH; + + int tempMonth = tmp.__dateTime.month + months % MAX_MONTH; + if (tempMonth > MAX_MONTH) + { + tmp.__dateTime.year++; + tmp.__dateTime.month = tempMonth - MAX_MONTH; + } + else if (tempMonth < 0) + { + tmp.__dateTime.year--; + tmp.__dateTime.month = MAX_MONTH + tempMonth; + } + else if (tempMonth == 0) + { + tmp.__dateTime.year--; + tmp.__dateTime.month = MAX_MONTH; + } + else + { + tmp.__dateTime.month += months % MAX_MONTH; + } + + // Check the days in Month + if (tmp.__dateTime.month != 2) // Not Feb + { + if (tmp.__dateTime.day == 31) + { + result r = SetValue(tmp.__dateTime.year, tmp.__dateTime.month, tmp.__dateTime.day); + if (IsFailed(r)) + { + r = tmp.AddDays(-1); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + } + } + } + else // Feb + { + if (tmp.__dateTime.day > 28) + { + if (tmp.IsLeapYear()) + { + tmp.__dateTime.day = 29; + } + else + { + tmp.__dateTime.day = 28; + } + } + + } + + SysTryReturn(NID_BASE, (tmp <= DateTime::GetMaxValue()) && (tmp >= DateTime::GetMinValue()), E_OUT_OF_RANGE, + E_OUT_OF_RANGE, "[%s] The value of the argument is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE)); + + SetValue(tmp); + + return E_SUCCESS; +} + +result +DateTime::AddSeconds(int seconds) +{ + TimeSpan ts(seconds * 1000LL); + + result r = Add(ts); + if (IsFailed(r)) + { + SysLogException(NID_BASE, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; +} + +result +DateTime::AddYears(int years) +{ + DateTime tmp; + tmp.SetValue(*this); + + int sum = years + tmp.__dateTime.year; + + SysTryReturn(NID_BASE, (sum >= MIN_YEAR && sum <= _MAX_YEAR), E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The years(%d) + current year(%d) MUST be within the %d and %d (inclusive).", + GetErrorMessage(E_OUT_OF_RANGE), years, __dateTime.year, MIN_YEAR, _MAX_YEAR); + + tmp.__dateTime.year = sum; + + // Check the days in Month + if (tmp.__dateTime.month == 2) // Feb + { + if (tmp.__dateTime.day > 28) + { + if (tmp.IsLeapYear()) // Check the leap year + { + tmp.__dateTime.day = 29; + } + else + { + tmp.__dateTime.day = 28; + } + } + } + + SetValue(tmp); + + return E_SUCCESS; +} + +int +DateTime::Compare(const DateTime& dt1, const DateTime& dt2) +{ + if (dt1 > dt2) + { + return 1; + } + else if (dt1 < dt2) + { + return -1; + } + else + { + return(0); + } +} + +int +DateTime::CompareTo(const DateTime& value) const +{ + return DateTime::Compare(*this, value); +} + +bool +DateTime::Equals(const Object& obj) const +{ + const DateTime* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + return(*this == *pOther); +} + +int +DateTime::GetHashCode(void) const +{ + TimeSpan t = GetTime(); + int hash = t.GetHashCode(); + return(hash ^ (hash >> 16)); +} + +TimeSpan +DateTime::GetTimeOfDay(void) const +{ + long long total = ConvertDateToSeconds(&__dateTime); + + TmDateTime midnight; + midnight.year = __dateTime.year; + midnight.month = __dateTime.month; + midnight.day = __dateTime.day; + midnight.hour = MIN_HOUR; + midnight.minute = MIN_MINUTE; + midnight.second = MIN_SECOND; + + long long since = ConvertDateToSeconds(&midnight); + + long long span = total - since; + + return(TimeSpan(span * 1000)); +} + +result +DateTime::GetDaysInMonth(int year, int month, int& days) +{ + const static int daysInMonth[] = { 0xFF, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + + SysTryReturn(NID_BASE, (year >= MIN_YEAR && year <= _MAX_YEAR), E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The year(%d) MUST be within the %d and %d (inclusive).", GetErrorMessage(E_OUT_OF_RANGE), + year, MIN_YEAR, _MAX_YEAR); + SysTryReturn(NID_BASE, (month >= MIN_MONTH && month <= MAX_MONTH), E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The month(%d) MUST be within the %d and %d (inclusive).", GetErrorMessage(E_OUT_OF_RANGE), + month, MIN_MONTH, MAX_MONTH); + + if (DateTime::IsLeapYear(year) && month == 2) + { + days = daysInMonth[month] + 1; + } + else + { + days = (daysInMonth[month]); + } + + return E_SUCCESS; +} + +result +DateTime::Subtract(const TimeSpan& t) +{ + long long total = ConvertDateToSeconds(&__dateTime); + long long span = total - (t.GetTicks() / 1000); + + SysTryReturn(NID_BASE, span > 0, E_OUT_OF_RANGE, E_OUT_OF_RANGE, "[%s] The arguments contain invalid values.", + GetErrorMessage(E_OUT_OF_RANGE)); + + SysTryReturn(NID_BASE, span >= NUM_OF_SEC_IN_DAY, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The arguments contain invalid values.", GetErrorMessage(E_OUT_OF_RANGE)); + + long long maxSeconds = ConvertDateToSeconds(&(DateTime::GetMaxValue().__dateTime)); + SysTryReturn(NID_BASE, span <= maxSeconds, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The value of the argument is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE)); + + result r = ConvertSecondsToDate(span, &__dateTime); + if (r != E_SUCCESS) + { + SysLogException(NID_BASE, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; +} + +String +DateTime::ToString(void) const +{ + wchar_t date[] = L"01/01/1970 00:00:00"; + + swprintf(date, (sizeof(date) / sizeof(wchar_t)), L"%2d/%2d/%4d %2d:%2d:%2d", + __dateTime.month, __dateTime.day, __dateTime.year, __dateTime.hour, __dateTime.minute, + __dateTime.second); + + if (__dateTime.month < 10) + { + date[0] = L'0'; + } + + if (__dateTime.day < 10) + { + date[3] = L'0'; + } + + if (__dateTime.year < 10) + { + date[6] = L'0'; + date[7] = L'0'; + date[8] = L'0'; + } + else if (__dateTime.year < 100) + { + date[6] = L'0'; + date[7] = L'0'; + } + else if (__dateTime.year < 1000) + { + date[6] = L'0'; + } + + if (__dateTime.hour < 10) + { + date[11] = L'0'; + } + + if (__dateTime.minute < 10) + { + date[14] = L'0'; + } + + if (__dateTime.second < 10) + { + date[17] = L'0'; + } + + String string(date); + + return string; +} + +result +DateTime::Parse(const String& str, DateTime& dt) +{ + SysTryReturn(NID_BASE, + (str.GetLength() == 19 + && str[2] == L'/' && str[5] == L'/' && str[10] == L' ' && str[13] == L':' && str[16] == L':'), + E_INVALID_FORMAT, E_INVALID_FORMAT, ("[%s] The str(%s) is not formatted like 'mm/dd/yyyy hh:mm:ss'."), + GetErrorMessage(E_INVALID_FORMAT), str.GetPointer()); + + std::unique_ptr pTmp(new (std::nothrow) wchar_t [5]); + SysTryReturn(NID_BASE, pTmp != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + wchar_t* pMchar = (wchar_t*) str.GetPointer(); + + // month + wcsncpy(pTmp.get(), pMchar, 2); + pTmp[2] = L'\0'; + + int month = (int) wcstol(pTmp.get(), null, 10); + + // day + wcsncpy(pTmp.get(), pMchar + 3, 2); + pTmp[2] = L'\0'; + + int day = (int) wcstol(pTmp.get(), null, 10); + + // year + wcsncpy(pTmp.get(), pMchar + 6, 4); + pTmp[4] = L'\0'; + + int year = (int) wcstol(pTmp.get(), null, 10); + + // hour + wcsncpy(pTmp.get(), pMchar + 11, 2); + pTmp[2] = L'\0'; + + int hour = (int) wcstol(pTmp.get(), null, 10); + + // minute + wcsncpy(pTmp.get(), pMchar + 14, 2); + pTmp[2] = L'\0'; + + int minute = (int) wcstol(pTmp.get(), null, 10); + + // second + wcsncpy(pTmp.get(), pMchar + 17, 2); + pTmp[2] = L'\0'; + + int sec = (int) wcstol(pTmp.get(), null, 10); + + // construct date time + DateTime tmpDt; + result r = tmpDt.SetValue(year, month, day, hour, minute, sec); + SysTryReturnResult(NID_BASE, !IsFailed(r), r, ("[%s] Propagating."), GetErrorMessage(r)); + + dt.SetValue(tmpDt); + + return E_SUCCESS; +} + +int +DateTime::GetYear(void) const +{ + return __dateTime.year; +} + +int +DateTime::GetMonth(void) const +{ + return __dateTime.month; +} + +int +DateTime::GetDay(void) const +{ + return __dateTime.day; +} + +int +DateTime::GetHour(void) const +{ + return __dateTime.hour; +} + +int +DateTime::GetMinute(void) const +{ + return __dateTime.minute; +} + +int +DateTime::GetSecond(void) const +{ + return __dateTime.second; +} + +TimeSpan +DateTime::GetTime(void) const +{ + long long seconds = ConvertDateToSeconds(&__dateTime) - ConvertDateToSeconds(&(DateTime::GetMinValue().__dateTime)); + + return TimeSpan(seconds * 1000); +} + +const DateTime& +DateTime::GetMaxValue(void) +{ + static DateTime maxValue(_MAX_YEAR, MAX_MONTH, MAX_DAY, MAX_HOUR, MAX_MINUTE, MAX_SECOND); + + return maxValue; +} + +const DateTime& +DateTime::GetMinValue(void) +{ + static DateTime minValue(MIN_YEAR, MIN_MONTH, MIN_DAY, MIN_HOUR, MIN_MINUTE, MIN_SECOND); + + return minValue; +} + +bool +DateTime::IsLeapYear(void) const +{ + return DateTime::IsLeapYear(__dateTime.year); +} + +bool +DateTime::IsLeapYear(int year) +{ + return year >= 0 && (!(year % 4) && ((year % 100) || !(year % 400))); +} + +DateTime::DateTime(int year, int month, int day, int hour, int minute, int second) + : __pDateTimeImpl(null) +{ + SetValue(year, month, day, hour, minute, second); +} + +result +DateTime::ConvertSecondsToDate(long long seconds, TmDateTime* pDateTime) +{ + DateTime dt; + + int year = 0; + int month = 0; + int day = 0; + int hour = 0; + int minute = 0; + int second = 0; + int totalDays = 0; + int tempDays = 0; + int tempSeconds = 0; + bool leapYear = false; + + totalDays = (int) (seconds / SEC_IN_A_DAY); + + // Get a year and leapYear + year = CountYears(totalDays); + SysTryReturn(NID_BASE, year >= MIN_YEAR && year <= _MAX_YEAR, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The arguments (%d) contain invalid values.", GetErrorMessage(E_OUT_OF_RANGE), seconds); + + // Check a leapYear + leapYear = DateTime::IsLeapYear(year); + + // Get days without year; + tempDays = totalDays - CountDays(year); + + // Check the boundary of days + if (leapYear) + { + if (tempDays > 366) + { + year += 1; + tempDays -= 366; + } + } + else + { + if (tempDays > 365) + { + year += 1; + tempDays -= 365; + } + } + + // Get month + if (tempDays == 0) // month = 0 , day = 0 + { + dt.__dateTime.year = year; + dt.__dateTime.month = 0; + dt.__dateTime.day = 0; + dt.__dateTime.hour = 0; + dt.__dateTime.minute = 0; + dt.__dateTime.second = 0; + + tempSeconds = (int) (seconds - ConvertDateToSeconds(&(dt.__dateTime))); + + // Get Hour + hour = tempSeconds / NUM_OF_SEC_IN_HOUR; + + tempSeconds -= hour * NUM_OF_SEC_IN_HOUR; + + // Get Minute + minute = tempSeconds / NUM_OF_SEC_IN_MINUTE; + + // Get Second + second = tempSeconds - minute * NUM_OF_SEC_IN_MINUTE; + + SetValue(year, 1, 1, hour, minute, second); + + return E_SUCCESS; + } + else if (leapYear) + { + int leapYearDaysCount = 0; + + for (; leapYearDaysCount < 12; leapYearDaysCount++) + { + if ((DAYS_IN_LEAP_YEAR[leapYearDaysCount] < tempDays) && (tempDays <= DAYS_IN_LEAP_YEAR[leapYearDaysCount + 1])) + { + month = leapYearDaysCount + 1; + break; + } + } + + SysTryReturn(NID_BASE, leapYearDaysCount != 12, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The arguments (%d) contain invalid values.", GetErrorMessage(E_OUT_OF_RANGE), seconds); + + day = tempDays - DAYS_IN_LEAP_YEAR[month - 1]; + } + else + { + int daysCount = 0; + + for (; daysCount < 12; daysCount++) + { + if ((DAYS[daysCount] < tempDays) && (tempDays <= DAYS[daysCount + 1])) + { + month = daysCount + 1; + break; + } + } + + SysTryReturn(NID_BASE, daysCount != 12, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The arguments (%d) contain invalid values.", GetErrorMessage(E_OUT_OF_RANGE), seconds); + + // Get day + day = tempDays - DAYS[month - 1]; + } + + dt.SetValue(year, month, day, 0, 0, 0); + + // Get Hour + tempSeconds = (int) (seconds - ConvertDateToSeconds(&(dt.__dateTime))); + hour = tempSeconds / NUM_OF_SEC_IN_HOUR; + + // Get Minute + tempSeconds -= hour * NUM_OF_SEC_IN_HOUR; + minute = tempSeconds / NUM_OF_SEC_IN_MINUTE; + + // Get Second + second = tempSeconds - minute * NUM_OF_SEC_IN_MINUTE; + + SetValue(year, month, day, hour, minute, second); + + return E_SUCCESS; +} + +long long +DateTime::ConvertDateToSeconds(const TmDateTime* pDateTime) const +{ + long long days = 0; + long long seconds = 0; + + // Add year + days = CountDays(pDateTime->year); + + // Add month + if (pDateTime->month != 0) + { + if (DateTime::IsLeapYear(pDateTime->year)) + { + days += DAYS_IN_LEAP_YEAR[pDateTime->month - 1]; + } + else + { + days += DAYS[pDateTime->month - 1]; + } + } + + // Add days + days += pDateTime->day; + + // Convert to Seconds + seconds = days * NUM_OF_SEC_IN_DAY; + + // Add hours + seconds += pDateTime->hour * NUM_OF_SEC_IN_HOUR; + + // Add minutes + seconds += pDateTime->minute * NUM_OF_SEC_IN_MINUTE; + + // Add minutes + seconds += pDateTime->second; + + return seconds; +} + +}} // Tizen::Base diff --git a/src/base/FBaseDouble.cpp b/src/base/FBaseDouble.cpp new file mode 100644 index 0000000..a8d22d2 --- /dev/null +++ b/src/base/FBaseDouble.cpp @@ -0,0 +1,293 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDouble.cpp + * @brief This is the implementation file for Double class. + * @see Number + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBase_NativeError.h" +#include + + +namespace Tizen { namespace Base +{ + +union DoubleBitRep +{ + explicit + DoubleBitRep(double d = 0.0) + : value(d) + { + }; + + DoubleBitRep(long long l) + : rep(l) + { + }; + + double value; + long long rep; +}; + +Double::Double(double value) + : value(value) + , __pDoubleImpl(null) +{ +} + +Double::Double(const Double& value) + : value(value.value) + , __pDoubleImpl(null) +{ +} + +Double::~Double(void) +{ +} + +Double& +Double::operator =(const Double& rhs) +{ + if (&rhs != this) + { + value = rhs.value; + } + return *this; +} + +int +Double::Compare(double d1, double d2) +{ + int ret = 0; + if (d1 > d2) + { + ret = 1; + } + else if (d1 < d2) + { + ret = -1; + } + else + { + ret = 0; + } + return ret; +} + +int +Double::CompareTo(double value) const +{ + return(Double::Compare(this->value, value)); +} + +int +Double::CompareTo(const Double& value) const +{ + return(Double::Compare(this->value, value.value)); +} + +bool +Double::Equals(const Object& obj) const +{ + const Double* pOther = dynamic_cast (&obj); + + if (pOther == null) + { + return false; + } + + if (Double::Compare(this->value, (*pOther).value) == 0) + { + return true; + } + else + { + return false; + } +} + +int +Double::GetHashCode(void) const +{ + double* pTemp = const_cast (&value); + int* pValueLow = reinterpret_cast (pTemp); + int* pValueHigh = pValueLow + 1; + return *pValueLow + *pValueHigh; +} + +int +Double::GetHashCode(double val) +{ + int* pValueLow = reinterpret_cast (&val); + int* pValueHigh = pValueLow + 1; + return *pValueLow + *pValueHigh; +} + +result +Double::Parse(const String& s, double& ret) +{ + wchar_t* pEnd = null; + + errno = 0; + ret = wcstod(s.GetPointer(), &pEnd); + SysTryReturnResult(NID_BASE, ((!(!Double::Compare(ret, 0) && errno == EINVAL)) && (pEnd[0] == 0)), E_NUM_FORMAT, + "Double parse failed with reason (%s). Scan stopped at (%ls)", __ConvertNativeErrorToMessage(errno), pEnd); + SysTryReturnResult(NID_BASE, !(errno != 0 && (!Double::Compare(ret, HUGE_VAL)|| !Double::Compare(ret, -HUGE_VAL))), + E_NUM_FORMAT, "Parsed value cannot fit into a Double."); + + return E_SUCCESS; +} + +char +Double::ToChar(void) const +{ + return static_cast (value); +} + +short +Double::ToShort(void) const +{ + return static_cast (value); +} + +int +Double::ToInt(void) const +{ + return static_cast (value); +} + +long +Double::ToLong(void) const +{ + return static_cast (value); +} + +long long +Double::ToLongLong(void) const +{ + return static_cast (value); +} + +float +Double::ToFloat(void) const +{ + return static_cast (value); +} + +double +Double::ToDouble(void) const +{ + return value; +} + +String +Double::ToString(void) const +{ + return(Double::ToString(value)); +} + +String +Double::ToString(double value) +{ + const static unsigned int MAX_DIG = 17 + 3; + const static unsigned int DOUBLE_LENGTH_MAX = __DBL_MAX_10_EXP + MAX_DIG; + + if (Double::IsNaN(value)) + { + return String(L"NaN"); + } + else if (Double::IsInfinity(value)) + { + return String(L"Infinity"); + } + else + { + wchar_t sValue[DOUBLE_LENGTH_MAX + 1] = {0, }; + swprintf(sValue, (sizeof(sValue) / sizeof(sValue[0])), L"%#lg", value); + return String(sValue); + } +} + +long long +Double::ToBits(double value) +{ + DoubleBitRep bitRep; + bitRep.value = value; + return (long long) bitRep.rep; +} + +double +Double::ToDoubleFromBits(long long value) +{ + DoubleBitRep bitRep; + bitRep.rep = value; + return bitRep.value; +} + +bool +Double::IsFinite(double d) +{ + return((isfinite(d) != 0) ? true : false); +} + +bool +Double::IsInfinity(void) const +{ + return(Double::IsInfinity(value)); +} + +bool +Double::IsInfinity(double value) +{ + return(!Double::IsFinite(value)); +} + +bool +Double::IsNaN(void) const +{ + return(Double::IsNaN(value)); +} + +bool +Double::IsNaN(double value) +{ + return((isnan(value) != 0) ? true : false); +} + +double +Double::GetMaxValue(void) +{ + return DBL_MAX; +} + +double +Double::GetMinValue(void) +{ + return DBL_MIN; +} + +}} // Tizen::Base diff --git a/src/base/FBaseDoubleComparer.cpp b/src/base/FBaseDoubleComparer.cpp new file mode 100644 index 0000000..a3eeb47 --- /dev/null +++ b/src/base/FBaseDoubleComparer.cpp @@ -0,0 +1,57 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDoubleComparer.cpp + * @brief This is the implementation file for DoubleComparer class. + * @see Double and Tizen::Base::Collection::IComparer + */ + +#include +#include +#include +#include + + +namespace Tizen { namespace Base +{ + + +DoubleComparer::DoubleComparer(void) + : __pDoubleComparerImpl(null) +{ +} + +DoubleComparer::~DoubleComparer(void) +{ +} + +result +DoubleComparer::Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const +{ + const Double* pDouble1 = dynamic_cast (&obj1); + const Double* pDouble2 = dynamic_cast (&obj2); + SysTryReturn(NID_BASE, (pDouble1 != null && pDouble2 != null), E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used. Both of the obj1 and obj2 MUST be Double.", GetErrorMessage(E_INVALID_ARG)); + + cmp = Double::Compare(pDouble1->ToDouble(), pDouble2->ToDouble()); + + return E_SUCCESS; +} + + +}} //Tizen::Base diff --git a/src/base/FBaseDoubleMatrix.cpp b/src/base/FBaseDoubleMatrix.cpp new file mode 100644 index 0000000..1e03362 --- /dev/null +++ b/src/base/FBaseDoubleMatrix.cpp @@ -0,0 +1,875 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDoubleMatrix.cpp + * @brief This is the implementation for DoubleMatrix class. + */ + +#include +#include +#include + +namespace Tizen { namespace Base +{ + +DoubleMatrix::DoubleMatrix(void) + : __pImpl(null) + , __pMatrix(null) + , __row(0) + , __column(0) +{ +} + +DoubleMatrix::DoubleMatrix(const DoubleMatrix& rhs) + : __pImpl(null) + , __row(rhs.__row) + , __column(rhs.__column) +{ + AllocateCapacity(__row, __column); + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = rhs.__pMatrix[i][j]; + } + } +} + +DoubleMatrix::DoubleMatrix(int rowCount, int columnCount) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + SetAsNull(); +} + +DoubleMatrix::DoubleMatrix(int rowCount, int columnCount, const double* pArray, bool rowMajor) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + if (pArray != null) + { + if (rowMajor == true) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i * __row + j]; + } + } + } + else + { + for (int i = 0; i < __column; i++) + { + for (int j = 0; j < __row; j++) + { + __pMatrix[j][i] = pArray[i * __column + j]; + } + } + } + } + else + { + SetAsNull(); + } +} + +DoubleMatrix::DoubleMatrix(int rowCount, int columnCount, const double* pArray[]) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + if (pArray != null) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i][j]; + } + } + } + else + { + SetAsIdentity(); + } +} + +DoubleMatrix::~DoubleMatrix(void) +{ + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + + delete[] __pMatrix; +} + +bool +DoubleMatrix::operator ==(const DoubleMatrix& rhs) const +{ + if (this == &rhs) + { + return true; + } + + if ((__row != rhs.__row) || (__column != rhs.__column)) + { + return false; + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + if (__pMatrix[i][j] != rhs.__pMatrix[i][j]) + { + return false; + } + } + } + + return true; +} + +bool +DoubleMatrix::operator !=(const DoubleMatrix& rhs) const +{ + return !(*this == rhs); +} + +DoubleMatrix& +DoubleMatrix::operator =(const DoubleMatrix& rhs) +{ + if (this == &rhs) + { + return *this; + } + + SysTryReturn(NID_BASE, (__row == rhs.__row) && (__column == rhs.__column), *this, E_INVALID_ARG, + "[%s] Invalid argument is used. Either row or column count of the current instance is not same with that of the specified instance.", + GetErrorMessage(E_INVALID_ARG)); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = rhs.__pMatrix[i][j]; + } + } + + return *this; +} + +bool +DoubleMatrix::Equals(const Tizen::Base::Object& obj) const +{ + const DoubleMatrix* pOther = dynamic_cast (&obj); + + if (pOther == null) + { + return false; + } + + return (*this == *pOther); +} + +int +DoubleMatrix::GetHashCode(void) const +{ + int hash = 0; + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + hash = hash + Tizen::Base::Double::GetHashCode(__pMatrix[i][j]); + } + } + + return hash; +} + +result +DoubleMatrix::Add(const DoubleMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, (__row == matrix.__row) && (__column == matrix.__column), E_INVALID_ARG, + "Either row or column count of the current instance is not same with that of the specified instance."); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] + matrix.__pMatrix[i][j]; + } + } + + return E_SUCCESS; +} + +void +DoubleMatrix::AddToEachElement(double value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] + value; + } + } +} + +bool +DoubleMatrix::AllocateCapacity(int rowCount, int columnCount) +{ + std::unique_ptr pMatrix(new (std::nothrow) double* [rowCount]); + SysTryReturn(NID_BASE, pMatrix != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for ( int i = 0 ; i < rowCount ; i++ ) + { + pMatrix[i] = new (std::nothrow) double[columnCount]; + if (pMatrix[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMatrix[j]; + } + return false; + } + } + + __pMatrix = pMatrix.release(); + + return true; +} + +double +DoubleMatrix::CalculateDeterminant(double** pMatrix, int order) const // For perfomance, we have to change the logic of recursive to LU decomposition. +{ + SysTryReturn(NID_BASE, pMatrix != null, 0.0f, E_INVALID_ARG, "[%s] Invalid argument is used. pMatrix is null.", + GetErrorMessage(E_INVALID_ARG)); + + if (order == 1) + { + return pMatrix[0][0]; + } + + double determinant = 0.0f; + std::unique_ptr pMinor(new (std::nothrow) double* [order - 1]); + SysTryReturn(NID_BASE, pMinor != null, determinant, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + for (int i = 0; i < order - 1; i++) + { + pMinor[i] = new (std::nothrow) double[order - 1]; + if (pMinor[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + return determinant; + } + } + + bool signFlag = true; + for (int i = 0; i < order; i++) + { + GetMinor(pMatrix, pMinor.get(), 0, i, order); + + if (signFlag == true) + { + determinant += pMatrix[0][i] * CalculateDeterminant(pMinor.get(), order - 1); + signFlag = false; + } + else + { + determinant += -pMatrix[0][i] * CalculateDeterminant(pMinor.get(), order - 1); + signFlag = true; + } + } + + for (int i = 0; i < order - 1; i++) + { + delete[] pMinor[i]; + } + + return determinant; +} + +int +DoubleMatrix::GetColumnCount(void) const +{ + return __column; +} + +double* +DoubleMatrix::GetColumnN(int columnIndex) const +{ + SysTryReturn(NID_BASE, columnIndex <= __column, null, E_INVALID_ARG, + "[%s] Invalid argument is used. The columnIndex is larger than the column count of the current instance.", + GetErrorMessage(E_INVALID_ARG)); + + std::unique_ptr pColumn(new (std::nothrow) double [__row]); + SysTryReturn(NID_BASE, pColumn != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row; i++) + { + pColumn[i] = __pMatrix[i][columnIndex]; + } + + return pColumn.release(); +} + +double +DoubleMatrix::GetDeterminant(void) const +{ + SysTryReturn(NID_BASE, __row == __column, 0.0f, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + return CalculateDeterminant(__pMatrix, __row); +} + +double +DoubleMatrix::GetElement(int rowIndex, int columnIndex) const +{ + SysTryReturn(NID_BASE, (rowIndex <= __row) && (columnIndex <= __column), 0.0f, E_INVALID_ARG, + "[%s] Invalid argument is used. The current instance is not a square matrix.", GetErrorMessage(E_INVALID_ARG)); + + return __pMatrix[rowIndex][columnIndex]; +} + +DoubleMatrix* +DoubleMatrix::GetInverseN(void) const +{ + SysTryReturn(NID_BASE, __row == __column, null, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + std::unique_ptr pInverseMatrix(new (std::nothrow) DoubleMatrix(__row, __column)); + SysTryReturn(NID_BASE, pInverseMatrix != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + double determinant = CalculateDeterminant(__pMatrix, __row); + + if (Tizen::Base::Double::Compare(determinant,0.0f) == 0) + { + return null; + } + + std::unique_ptr pMinor(new (std::nothrow) double* [__row - 1]); + SysTryReturn(NID_BASE, pMinor != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row -1; i++) + { + pMinor[i] = new (std::nothrow) double[__row - 1]; + if (pMinor[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + return null; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __row; j++) + { + GetMinor(__pMatrix, pMinor.get(), i, j, __row); + pInverseMatrix->__pMatrix[j][i] = CalculateDeterminant(pMinor.get(), __row - 1) / determinant; + if ((i + j + 2) % 2 == 1) + { + pInverseMatrix->__pMatrix[j][i] = -pInverseMatrix->__pMatrix[j][i]; + } + } + } + + for ( int i = 0 ; i < __row -1 ; i++ ) + { + delete[] pMinor[i]; + } + + return pInverseMatrix.release(); +} + +void +DoubleMatrix::GetMinor(double** pSrc, double** pDest, int rowIndex, int columnIndex, int order) const +{ + SysTryReturn(NID_BASE, pSrc != null, , E_INVALID_ARG, "[%s] Invalid argument is used. pSrc is null.", + GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_BASE, pDest != null, , E_INVALID_ARG, "[%s] Invalid argument is used. pDest is null.", + GetErrorMessage(E_INVALID_ARG)); + + int rowCount = 0; + int columnCount = 0; + + for (int i = 0; i < order; i++) + { + if (i != rowIndex) + { + columnCount = 0; + + for (int j = 0; j < order; j++) + { + if (j != columnIndex) + { + pDest[rowCount][columnCount] = pSrc[i][j]; + columnCount++; + } + } + rowCount++; + } + } +} + +int +DoubleMatrix::GetRowCount(void) const +{ + return __row; +} + +double* +DoubleMatrix::GetRowN(int rowIndex) const +{ + SysTryReturn(NID_BASE, rowIndex <= __row, null, E_INVALID_ARG, + "[%s] Invalid argument is used. The rowIndex is larger than the row count of the current instance.", + GetErrorMessage(E_INVALID_ARG)); + + std::unique_ptr pRow(new (std::nothrow) double [__column]); + SysTryReturn(NID_BASE, pRow != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __column; i++) + { + pRow[i] = __pMatrix[rowIndex][i]; + } + + return pRow.release(); +} + +result +DoubleMatrix::GetTrace(double& value) const +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + value = 0.0f; + + for (int i = 0; i < __row; i++) + { + value += __pMatrix[i][i]; + } + + return E_SUCCESS; +} + +DoubleMatrix* +DoubleMatrix::GetTransposeN(void) const +{ + SysTryReturn(NID_BASE, __row == __column, null, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + std::unique_ptr pTransposeMatrix(new (std::nothrow) DoubleMatrix(*this)); + SysTryReturn(NID_BASE, pTransposeMatrix != null, null, E_OUT_OF_MEMORY, + "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + int columnIndex = 1; + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < columnIndex; j++) + { + double temp = pTransposeMatrix->__pMatrix[i][j]; + pTransposeMatrix->__pMatrix[i][j] = pTransposeMatrix->__pMatrix[j][i]; + pTransposeMatrix->__pMatrix[j][i] = temp; + } + + columnIndex++; + } + + return pTransposeMatrix.release(); +} + +bool +DoubleMatrix::IsIdentity(void) const +{ + if (__row != __column) + { + return false; + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + if (i == j) + { + if (Tizen::Base::Double::Compare(__pMatrix[i][j],1.0f) != 0) + { + return false; + } + } + else + { + if (Tizen::Base::Double::Compare(__pMatrix[i][j],0.0f) != 0) + { + return false; + } + } + + + } + } + return true; +} + +bool +DoubleMatrix::IsInvertible(void) const +{ + int ret = Tizen::Base::Double::Compare(GetDeterminant(),0.0f); + + if (ret == 0) + { + return false; + } + else + { + return true; + } +} + +result +DoubleMatrix::Multiply(const DoubleMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, __column == matrix.__row, E_INVALID_ARG, + "The column count of the current instance is not same with the row count of the specified instance."); + + std::unique_ptr pResult(new (std::nothrow) double* [__row]); + SysTryReturnResult(NID_BASE, pResult != null, E_OUT_OF_MEMORY, "Allocating memory is failed."); + + for ( int i = 0 ; i < __row ; i++ ) + { + pResult[i] = new (std::nothrow) double[matrix.__column]; + if (pResult[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pResult[j]; + } + return E_OUT_OF_MEMORY; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < matrix.__column; j++) + { + pResult[i][j] = 0.0f; + + for (int k = 0; k < __column; k++) + { + pResult[i][j] += __pMatrix[i][k] * matrix.__pMatrix[k][j]; + } + } + } + + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + + delete[] __pMatrix; + + __pMatrix = pResult.release(); + + return E_SUCCESS; +} + +void +DoubleMatrix::Multiply(double value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] * value; + } + } +} + +void +DoubleMatrix::Negate(void) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = -__pMatrix[i][j]; + } + } +} + +result +DoubleMatrix::SetAsIdentity(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + if (i == j) + { + __pMatrix[i][j] = 1.0f; + } + else + { + __pMatrix[i][j] = 0.0f; + } + } + } + + return E_SUCCESS; +} + +result +DoubleMatrix::Invert(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + double determinant = CalculateDeterminant(__pMatrix, __row); + SysTryReturnResult(NID_BASE, Tizen::Base::Double::Compare(determinant, 0.0f) != 0, E_INVALID_OPERATION, + "The current instance is not invertible."); + + std::unique_ptr pInverse(new (std::nothrow) double* [__row]); + SysTryReturnResult(NID_BASE, pInverse != null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row; i++) + { + pInverse[i] = new (std::nothrow) double[__row]; + if (pInverse[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pInverse[j]; + } + return E_OUT_OF_MEMORY; + } + } + + std::unique_ptr pMinor(new (std::nothrow) double* [__row - 1]); + if (pMinor == null) + { + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] pInverse[i]; + } + return E_OUT_OF_MEMORY; + } + + for (int i = 0; i < __row -1; i++) + { + pMinor[i] = new double[__row - 1]; + if (pMinor[i] == null) + { + for( int i = 0 ; i < __row ; i++ ) + { + delete[] pInverse[i]; + } + + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + return E_OUT_OF_MEMORY; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __row; j++) + { + GetMinor(__pMatrix, pMinor.get(), i, j, __row); + pInverse[j][i] = CalculateDeterminant(pMinor.get(), __row - 1) / determinant; + if ((i +j +2) % 2 == 1) + { + pInverse[j][i] = -pInverse[j][i]; + } + } + } + + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + delete[] __pMatrix; + + __pMatrix = pInverse.release(); + + for (int i = 0 ; i < __row -1; i++ ) + { + delete[] pMinor[i]; + } + + return E_SUCCESS; +} + +result +DoubleMatrix::Transpose(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + int columnIndex = 1; + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < columnIndex; j++) + { + double temp = __pMatrix[i][j]; + __pMatrix[i][j] = __pMatrix[j][i]; + __pMatrix[j][i] = temp; + } + + columnIndex++; + } + + return E_SUCCESS; +} + +result +DoubleMatrix::SetColumn(int columnIndex, const double* pArray) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null"); + SysTryReturnResult(NID_BASE, columnIndex <= __column, E_INVALID_ARG, + "columnIndex is larger than the column count of the current instance."); + + for (int i = 0; i < __row; i++) + { + __pMatrix[i][columnIndex] = pArray[i]; + } + + return E_SUCCESS; +} + +result +DoubleMatrix::SetRow(int rowIndex, const double* pArray) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null"); + SysTryReturnResult(NID_BASE, rowIndex <= __row, E_INVALID_ARG, + "rowIndex is larger than the row count of the current instance."); + + for (int i = 0; i < __column; i++) + { + __pMatrix[rowIndex][i] = pArray[i]; + } + + return E_SUCCESS; +} + +result +DoubleMatrix::SetElement(int rowIndex, int columnIndex, double value) +{ + SysTryReturnResult(NID_BASE, columnIndex <= __column, E_INVALID_ARG, + "columnIndex is larger than the column count of the current instance."); + SysTryReturnResult(NID_BASE, rowIndex <= __row, E_INVALID_ARG, + "rowIndex is larger than the row count of the current instance."); + + __pMatrix[rowIndex][columnIndex] = value; + + return E_SUCCESS; +} + +result +DoubleMatrix::SetValue(const double* pArray, bool rowMajor) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null."); + + if (rowMajor == true) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i * __row + j]; + } + } + } + else + { + for (int i = 0; i < __column; i++) + { + for (int j = 0; j < __row; j++) + { + __pMatrix[j][i] = pArray[i * __column + j]; + } + } + } + + return E_SUCCESS; +} + +void +DoubleMatrix::SetAsNull(void) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = 0.0f; + } + } +} + +result +DoubleMatrix::Subtract(const DoubleMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, (__row == matrix.__row) && (__column == matrix.__column), E_INVALID_ARG, + "Either row or column count of the current instance is not same with that of the specified instance."); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] - matrix.__pMatrix[i][j]; + } + } + + return E_SUCCESS; +} + +void +DoubleMatrix::SubtractToEachElement(double value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] - value; + } + } +} + +}} // Tizen::Base diff --git a/src/base/FBaseDoubleMatrix3.cpp b/src/base/FBaseDoubleMatrix3.cpp new file mode 100644 index 0000000..794dfda --- /dev/null +++ b/src/base/FBaseDoubleMatrix3.cpp @@ -0,0 +1,492 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDoubleMatrix3.cpp + * @brief This is the implementation for DoubleMatrix class. + */ + +#include +#include + +namespace Tizen { namespace Base +{ + +static const int MATRIX_SIZE = sizeof(double) * 9; +#define SWAP_VALUES(a, b, tmp) \ + tmp = a; \ + a = b; \ + b = tmp; + +DoubleMatrix3::DoubleMatrix3(void) + : __pImpl(null) +{ + SetAsNull(); +} + +DoubleMatrix3::DoubleMatrix3(const DoubleMatrix3& rhs) + : __pImpl(null) +{ + memcpy(matrix, rhs.matrix, MATRIX_SIZE); +} + +DoubleMatrix3::DoubleMatrix3(const double matrix[3][3]) + : __pImpl(null) +{ + memcpy(this->matrix, matrix, MATRIX_SIZE); +} + +DoubleMatrix3::~DoubleMatrix3(void) +{ +} + +bool +DoubleMatrix3::operator ==(const DoubleMatrix3& rhs) const +{ + if (this == &rhs) + { + return true; + } + + return (matrix[0][0] == rhs.matrix[0][0] && + matrix[0][1] == rhs.matrix[0][1] && + matrix[0][2] == rhs.matrix[0][2] && + matrix[1][0] == rhs.matrix[1][0] && + matrix[1][1] == rhs.matrix[1][1] && + matrix[1][2] == rhs.matrix[1][2] && + matrix[2][0] == rhs.matrix[2][0] && + matrix[2][1] == rhs.matrix[2][1] && + matrix[2][2] == rhs.matrix[2][2]); +} + +bool +DoubleMatrix3::operator !=(const DoubleMatrix3& rhs) const +{ + return !(*this == rhs); +} + +DoubleMatrix3& +DoubleMatrix3::operator =(const DoubleMatrix3& rhs) +{ + if (this != &rhs) + { + memcpy(matrix, rhs.matrix, sizeof(double) * 9); + } + + return *this; +} + +DoubleMatrix3& +DoubleMatrix3::operator =(double value) +{ + matrix[0][0] = value; + matrix[1][0] = value; + matrix[2][0] = value; + + matrix[0][1] = value; + matrix[1][1] = value; + matrix[2][1] = value; + + matrix[0][2] = value; + matrix[1][2] = value; + matrix[2][2] = value; + + return *this; +} + +DoubleMatrix3 +DoubleMatrix3::operator *(const DoubleMatrix3& rhs) const // need to check performance +{ + DoubleMatrix3 resultMatrix; + + resultMatrix.matrix[0][0] = matrix[0][0] * rhs.matrix[0][0] + matrix[0][1] * rhs.matrix[1][0] + matrix[0][2] * rhs.matrix[2][0]; + resultMatrix.matrix[0][1] = matrix[0][0] * rhs.matrix[0][1] + matrix[0][1] * rhs.matrix[1][1] + matrix[0][2] * rhs.matrix[2][1]; + resultMatrix.matrix[0][2] = matrix[0][0] * rhs.matrix[0][2] + matrix[0][1] * rhs.matrix[1][2] + matrix[0][2] * rhs.matrix[2][2]; + + resultMatrix.matrix[1][0] = matrix[1][0] * rhs.matrix[0][0] + matrix[1][1] * rhs.matrix[1][0] + matrix[1][2] * rhs.matrix[2][0]; + resultMatrix.matrix[1][1] = matrix[1][0] * rhs.matrix[0][1] + matrix[1][1] * rhs.matrix[1][1] + matrix[1][2] * rhs.matrix[2][1]; + resultMatrix.matrix[1][2] = matrix[1][0] * rhs.matrix[0][2] + matrix[1][1] * rhs.matrix[1][2] + matrix[1][2] * rhs.matrix[2][2]; + + resultMatrix.matrix[2][0] = matrix[2][0] * rhs.matrix[0][0] + matrix[2][1] * rhs.matrix[1][0] + matrix[2][2] * rhs.matrix[2][0]; + resultMatrix.matrix[2][1] = matrix[2][0] * rhs.matrix[0][1] + matrix[2][1] * rhs.matrix[1][1] + matrix[2][2] * rhs.matrix[2][1]; + resultMatrix.matrix[2][2] = matrix[2][0] * rhs.matrix[0][2] + matrix[2][1] * rhs.matrix[1][2] + matrix[2][2] * rhs.matrix[2][2]; + + return resultMatrix; +} + +DoubleMatrix3 +DoubleMatrix3::operator *(double value) const +{ + DoubleMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] *= value; + resultMatrix.matrix[0][1] *= value; + resultMatrix.matrix[0][2] *= value; + + resultMatrix.matrix[1][0] *= value; + resultMatrix.matrix[1][1] *= value; + resultMatrix.matrix[1][2] *= value; + + resultMatrix.matrix[2][0] *= value; + resultMatrix.matrix[2][1] *= value; + resultMatrix.matrix[2][2] *= value; + + return resultMatrix; +} + +DoubleMatrix3 +DoubleMatrix3::operator +(const DoubleMatrix3& rhs) const +{ + DoubleMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] += rhs.matrix[0][0]; + resultMatrix.matrix[0][1] += rhs.matrix[0][1]; + resultMatrix.matrix[0][2] += rhs.matrix[0][2]; + + resultMatrix.matrix[1][0] += rhs.matrix[1][0]; + resultMatrix.matrix[1][1] += rhs.matrix[1][1]; + resultMatrix.matrix[1][2] += rhs.matrix[1][2]; + + resultMatrix.matrix[2][0] += rhs.matrix[2][0]; + resultMatrix.matrix[2][1] += rhs.matrix[2][1]; + resultMatrix.matrix[2][2] += rhs.matrix[2][2]; + + return resultMatrix; +} + +DoubleMatrix3 +DoubleMatrix3::operator +(double value) const +{ + DoubleMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] += value; + resultMatrix.matrix[0][1] += value; + resultMatrix.matrix[0][2] += value; + + resultMatrix.matrix[1][0] += value; + resultMatrix.matrix[1][1] += value; + resultMatrix.matrix[1][2] += value; + + resultMatrix.matrix[2][0] += value; + resultMatrix.matrix[2][1] += value; + resultMatrix.matrix[2][2] += value; + + return resultMatrix; +} + +DoubleMatrix3 +DoubleMatrix3::operator -(const DoubleMatrix3& rhs) const +{ + DoubleMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] -= rhs.matrix[0][0]; + resultMatrix.matrix[0][1] -= rhs.matrix[0][1]; + resultMatrix.matrix[0][2] -= rhs.matrix[0][2]; + + resultMatrix.matrix[1][0] -= rhs.matrix[1][0]; + resultMatrix.matrix[1][1] -= rhs.matrix[1][1]; + resultMatrix.matrix[1][2] -= rhs.matrix[1][2]; + + resultMatrix.matrix[2][0] -= rhs.matrix[2][0]; + resultMatrix.matrix[2][1] -= rhs.matrix[2][1]; + resultMatrix.matrix[2][2] -= rhs.matrix[2][2]; + + return resultMatrix; +} + +DoubleMatrix3 +DoubleMatrix3::operator -(double value) const +{ + DoubleMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] -= value; + resultMatrix.matrix[0][1] -= value; + resultMatrix.matrix[0][2] -= value; + + resultMatrix.matrix[1][0] -= value; + resultMatrix.matrix[1][1] -= value; + resultMatrix.matrix[1][2] -= value; + + resultMatrix.matrix[2][0] -= value; + resultMatrix.matrix[2][1] -= value; + resultMatrix.matrix[2][2] -= value; + + return resultMatrix; +} + +DoubleMatrix3& +DoubleMatrix3::operator *=(const DoubleMatrix3& rhs) +{ + *this = *this * rhs; + return *this; +} + +DoubleMatrix3& +DoubleMatrix3::operator *=(double value) +{ + *this = *this * value; + return *this; +} + +DoubleMatrix3& +DoubleMatrix3::operator +=(const DoubleMatrix3& rhs) +{ + *this = *this + rhs; + return *this; +} + +DoubleMatrix3& +DoubleMatrix3::operator +=(double value) +{ + *this = *this + value; + return *this; +} + +DoubleMatrix3& +DoubleMatrix3::operator -=(const DoubleMatrix3& rhs) +{ + *this = *this - rhs; + return *this; +} + +DoubleMatrix3& +DoubleMatrix3::operator -=(double value) +{ + *this = *this - value; + return *this; +} + +DoubleMatrix3 +operator +(const double& value, const DoubleMatrix3& rhs) +{ + return rhs + value; +} + +DoubleMatrix3 +operator *(const double& value, const DoubleMatrix3& rhs) +{ + return rhs * value; +} + +DoubleMatrix3 +operator -(const double& value, const DoubleMatrix3& rhs) +{ + DoubleMatrix3 returnMatrix(rhs); + returnMatrix.Negate(); + returnMatrix += value; + return returnMatrix; +} + +bool +DoubleMatrix3::Equals(const Tizen::Base::Object& obj) const +{ + const DoubleMatrix3* pMatrix = dynamic_cast (&obj); + + if (pMatrix == null) + { + return false; + } + + return (*this == *pMatrix); +} + +int +DoubleMatrix3::GetHashCode(void) const +{ + return (Tizen::Base::Double::GetHashCode(this->matrix[0][0]) + Tizen::Base::Double::GetHashCode(this->matrix[1][0]) + + Tizen::Base::Double::GetHashCode(this->matrix[2][0]) + Tizen::Base::Double::GetHashCode(this->matrix[0][1]) + + Tizen::Base::Double::GetHashCode(this->matrix[1][1]) + Tizen::Base::Double::GetHashCode(this->matrix[2][1]) + + Tizen::Base::Double::GetHashCode(this->matrix[0][2]) + Tizen::Base::Double::GetHashCode(this->matrix[1][2]) + + Tizen::Base::Double::GetHashCode(this->matrix[2][2])); +} + +double +DoubleMatrix3::GetDeterminant(void) const +{ + double a0 = matrix[1][1] * matrix[2][2] - matrix[2][1] * matrix[1][2]; + double a1 = matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]; + double a2 = matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]; + + return matrix[0][0] * a0 - matrix[0][1] * a1 + matrix[0][2] * a2; +} + +DoubleMatrix3 +DoubleMatrix3::GetInverse(void) const +{ + double a0 = matrix[1][1] * matrix[2][2] - matrix[2][1] * matrix[1][2]; + double a1 = matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]; + double a2 = matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]; + + double determinant = matrix[0][0] * a0 - matrix[0][1] * a1 + matrix[0][2] * a2; + + if (Tizen::Base::Double::Compare(determinant, 0.0f) == 0) + { + return *this; + } + + double inverseMatrix[3][3]; + + inverseMatrix[0][0] = (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1]) / determinant; + inverseMatrix[1][0] = (-matrix[1][0] * matrix[2][2] + matrix[1][2] * matrix[2][0]) / determinant; + inverseMatrix[2][0] = (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]) / determinant; + + inverseMatrix[0][1] = (-matrix[0][1] * matrix[2][2] + matrix[0][2] * matrix[2][1]) / determinant; + inverseMatrix[1][1] = (matrix[0][0] * matrix[2][2] - matrix[0][2] * matrix[2][0]) / determinant; + inverseMatrix[2][1] = (-matrix[0][0] * matrix[2][1] + matrix[0][1] * matrix[2][0]) / determinant; + + inverseMatrix[0][2] = (matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]) / determinant; + inverseMatrix[1][2] = (-matrix[0][0] * matrix[1][2] + matrix[0][2] * matrix[1][0]) / determinant; + inverseMatrix[2][2] = (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]) / determinant; + + return DoubleMatrix3(inverseMatrix); +} + +double +DoubleMatrix3::GetTrace(void) const +{ + return matrix[0][0] + matrix[1][1] + matrix[2][2]; +} + +DoubleMatrix3 +DoubleMatrix3::GetTranspose(void) const +{ + DoubleMatrix3 transposeMatrix(matrix); + transposeMatrix.Transpose(); + + return transposeMatrix; +} + +bool +DoubleMatrix3::IsIdentity(void) const +{ + if ((Tizen::Base::Double::Compare(matrix[0][0], 1.0f) != 0) || (Tizen::Base::Double::Compare(matrix[1][1], 1.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[2][2], 1.0f) != 0)) + { + return false; + } + + if ((Tizen::Base::Double::Compare(matrix[0][1], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[0][2], 0.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[1][0], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[1][2], 0.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[2][0], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[2][1], 0.0f) != 0)) + { + return false; + } + + return true; +} + +bool +DoubleMatrix3::IsInvertible(void) const +{ + if (Tizen::Base::Double::Compare(GetDeterminant(), 0.0f) == 0) + { + return false; + } + + return true; +} + +void +DoubleMatrix3::Negate(void) +{ + matrix[0][0] = -matrix[0][0]; + matrix[0][1] = -matrix[0][1]; + matrix[0][2] = -matrix[0][2]; + + matrix[1][0] = -matrix[1][0]; + matrix[1][1] = -matrix[1][1]; + matrix[1][2] = -matrix[1][2]; + + matrix[2][0] = -matrix[2][0]; + matrix[2][1] = -matrix[2][1]; + matrix[2][2] = -matrix[2][2]; +} + +void +DoubleMatrix3::SetAsIdentity(void) +{ + matrix[0][0] = 1.0f; + matrix[0][1] = 0.0f; + matrix[0][2] = 0.0f; + + matrix[1][0] = 0.0f; + matrix[1][1] = 1.0f; + matrix[1][2] = 0.0f; + + matrix[2][0] = 0.0f; + matrix[2][1] = 0.0f; + matrix[2][2] = 1.0f; +} + +result +DoubleMatrix3::Invert(void) +{ + double a0 = matrix[1][1] * matrix[2][2] - matrix[2][1] * matrix[1][2]; + double a1 = matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]; + double a2 = matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]; + + double determinant = matrix[0][0] * a0 - matrix[0][1] * a1 + matrix[0][2] * a2; + + SysTryReturnResult(NID_BASE, Tizen::Base::Double::Compare(determinant, 0.0f) != 0, E_INVALID_OPERATION, + "The current instance is not invertible."); + + double inverseMatrix[3][3]; + + inverseMatrix[0][0] = (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1]) / determinant; + inverseMatrix[1][0] = (-matrix[1][0] * matrix[2][2] + matrix[1][2] * matrix[2][0]) / determinant; + inverseMatrix[2][0] = (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]) / determinant; + + inverseMatrix[0][1] = (-matrix[0][1] * matrix[2][2] + matrix[0][2] * matrix[2][1]) / determinant; + inverseMatrix[1][1] = (matrix[0][0] * matrix[2][2] - matrix[0][2] * matrix[2][0]) / determinant; + inverseMatrix[2][1] = (-matrix[0][0] * matrix[2][1] + matrix[0][1] * matrix[2][0]) / determinant; + + inverseMatrix[0][2] = (matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]) / determinant; + inverseMatrix[1][2] = (-matrix[0][0] * matrix[1][2] + matrix[0][2] * matrix[1][0]) / determinant; + inverseMatrix[2][2] = (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]) / determinant; + + memcpy(matrix, inverseMatrix, MATRIX_SIZE); + + return E_SUCCESS; +} + +void +DoubleMatrix3::Transpose(void) +{ + double tmp = 0.0f; + SWAP_VALUES(matrix[0][1], matrix[1][0], tmp); + SWAP_VALUES(matrix[0][2], matrix[2][0], tmp); + + SWAP_VALUES(matrix[1][2], matrix[2][1], tmp); +} + +void +DoubleMatrix3::SetAsNull(void) +{ + matrix[0][0] = 0.0f; + matrix[0][1] = 0.0f; + matrix[0][2] = 0.0f; + + matrix[1][0] = 0.0f; + matrix[1][1] = 0.0f; + matrix[1][2] = 0.0f; + + matrix[2][0] = 0.0f; + matrix[2][1] = 0.0f; + matrix[2][2] = 0.0f; +} + +}} // Tizen::Base diff --git a/src/base/FBaseDoubleMatrix4.cpp b/src/base/FBaseDoubleMatrix4.cpp new file mode 100644 index 0000000..556df17 --- /dev/null +++ b/src/base/FBaseDoubleMatrix4.cpp @@ -0,0 +1,635 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseDoubleMatrix4.cpp + * @brief This is the implementation for DoubleMatrix class. + */ + +#include +#include + +namespace Tizen { namespace Base +{ + +static const int MATRIX_SIZE = sizeof(double) * 16; +#define SWAP_VALUES(a, b, tmp) \ + tmp = a; \ + a = b; \ + b = tmp; + +DoubleMatrix4::DoubleMatrix4(void) + : __pImpl(null) +{ + SetAsNull(); +} + +DoubleMatrix4::DoubleMatrix4(const DoubleMatrix4& rhs) + : __pImpl(null) +{ + memcpy(matrix, rhs.matrix, MATRIX_SIZE); +} + +DoubleMatrix4::DoubleMatrix4(const double matrix[4][4]) + : __pImpl(null) +{ + memcpy(this->matrix, matrix, MATRIX_SIZE); +} + +DoubleMatrix4::~DoubleMatrix4(void) +{ +} + +bool +DoubleMatrix4::operator ==(const DoubleMatrix4& rhs) const +{ + if (this == &rhs) + { + return true; + } + + return (matrix[0][0] == rhs.matrix[0][0] && + matrix[0][1] == rhs.matrix[0][1] && + matrix[0][2] == rhs.matrix[0][2] && + matrix[0][3] == rhs.matrix[0][3] && + matrix[1][0] == rhs.matrix[1][0] && + matrix[1][1] == rhs.matrix[1][1] && + matrix[1][2] == rhs.matrix[1][2] && + matrix[1][3] == rhs.matrix[1][3] && + matrix[2][0] == rhs.matrix[2][0] && + matrix[2][1] == rhs.matrix[2][1] && + matrix[2][2] == rhs.matrix[2][2] && + matrix[2][3] == rhs.matrix[2][3] && + matrix[3][0] == rhs.matrix[3][0] && + matrix[3][1] == rhs.matrix[3][1] && + matrix[3][2] == rhs.matrix[3][2] && + matrix[3][3] == rhs.matrix[3][3]); +} + +bool +DoubleMatrix4::operator !=(const DoubleMatrix4& rhs) const +{ + return !(*this == rhs); +} + +DoubleMatrix4& +DoubleMatrix4::operator =(const DoubleMatrix4& rhs) +{ + if (this != &rhs) + { + memcpy(matrix, rhs.matrix, MATRIX_SIZE); + } + + return *this; +} + +DoubleMatrix4& +DoubleMatrix4::operator =(double value) +{ + matrix[0][0] = value; + matrix[1][0] = value; + matrix[2][0] = value; + matrix[3][0] = value; + + matrix[0][1] = value; + matrix[1][1] = value; + matrix[2][1] = value; + matrix[3][1] = value; + + matrix[0][2] = value; + matrix[1][2] = value; + matrix[2][2] = value; + matrix[3][2] = value; + + matrix[0][3] = value; + matrix[1][3] = value; + matrix[2][3] = value; + matrix[3][3] = value; + + return *this; +} + +DoubleMatrix4 +DoubleMatrix4::operator *(const DoubleMatrix4& rhs) const // need to check performance +{ + DoubleMatrix4 resultMatrix; + + resultMatrix.matrix[0][0] = matrix[0][0] * rhs.matrix[0][0] + matrix[0][1] * rhs.matrix[1][0] + matrix[0][2] * rhs.matrix[2][0] + matrix[0][3] * rhs.matrix[3][0]; + resultMatrix.matrix[0][1] = matrix[0][0] * rhs.matrix[0][1] + matrix[0][1] * rhs.matrix[1][1] + matrix[0][2] * rhs.matrix[2][1] + matrix[0][3] * rhs.matrix[3][1]; + resultMatrix.matrix[0][2] = matrix[0][0] * rhs.matrix[0][2] + matrix[0][1] * rhs.matrix[1][2] + matrix[0][2] * rhs.matrix[2][2] + matrix[0][3] * rhs.matrix[3][2]; + resultMatrix.matrix[0][3] = matrix[0][0] * rhs.matrix[0][3] + matrix[0][1] * rhs.matrix[1][3] + matrix[0][2] * rhs.matrix[2][3] + matrix[0][3] * rhs.matrix[3][3]; + + resultMatrix.matrix[1][0] = matrix[1][0] * rhs.matrix[0][0] + matrix[1][1] * rhs.matrix[1][0] + matrix[1][2] * rhs.matrix[2][0] + matrix[1][3] * rhs.matrix[3][0]; + resultMatrix.matrix[1][1] = matrix[1][0] * rhs.matrix[0][1] + matrix[1][1] * rhs.matrix[1][1] + matrix[1][2] * rhs.matrix[2][1] + matrix[1][3] * rhs.matrix[3][1]; + resultMatrix.matrix[1][2] = matrix[1][0] * rhs.matrix[0][2] + matrix[1][1] * rhs.matrix[1][2] + matrix[1][2] * rhs.matrix[2][2] + matrix[1][3] * rhs.matrix[3][2]; + resultMatrix.matrix[1][3] = matrix[1][0] * rhs.matrix[0][3] + matrix[1][1] * rhs.matrix[1][3] + matrix[1][2] * rhs.matrix[2][3] + matrix[1][3] * rhs.matrix[3][3]; + + resultMatrix.matrix[2][0] = matrix[2][0] * rhs.matrix[0][0] + matrix[2][1] * rhs.matrix[1][0] + matrix[2][2] * rhs.matrix[2][0] + matrix[2][3] * rhs.matrix[3][0]; + resultMatrix.matrix[2][1] = matrix[2][0] * rhs.matrix[0][1] + matrix[2][1] * rhs.matrix[1][1] + matrix[2][2] * rhs.matrix[2][1] + matrix[2][3] * rhs.matrix[3][1]; + resultMatrix.matrix[2][2] = matrix[2][0] * rhs.matrix[0][2] + matrix[2][1] * rhs.matrix[1][2] + matrix[2][2] * rhs.matrix[2][2] + matrix[2][3] * rhs.matrix[3][2]; + resultMatrix.matrix[2][3] = matrix[2][0] * rhs.matrix[0][3] + matrix[2][1] * rhs.matrix[1][3] + matrix[2][2] * rhs.matrix[2][3] + matrix[2][3] * rhs.matrix[3][3]; + + resultMatrix.matrix[3][0] = matrix[3][0] * rhs.matrix[0][0] + matrix[3][1] * rhs.matrix[1][0] + matrix[3][2] * rhs.matrix[2][0] + matrix[3][3] * rhs.matrix[3][0]; + resultMatrix.matrix[3][1] = matrix[3][0] * rhs.matrix[0][1] + matrix[3][1] * rhs.matrix[1][1] + matrix[3][2] * rhs.matrix[2][1] + matrix[3][3] * rhs.matrix[3][1]; + resultMatrix.matrix[3][2] = matrix[3][0] * rhs.matrix[0][2] + matrix[3][1] * rhs.matrix[1][2] + matrix[3][2] * rhs.matrix[2][2] + matrix[3][3] * rhs.matrix[3][2]; + resultMatrix.matrix[3][3] = matrix[3][0] * rhs.matrix[0][3] + matrix[3][1] * rhs.matrix[1][3] + matrix[3][2] * rhs.matrix[2][3] + matrix[3][3] * rhs.matrix[3][3]; + + return resultMatrix; +} + +DoubleMatrix4 +DoubleMatrix4::operator *(double value) const +{ + DoubleMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] *= value; + resultMatrix.matrix[0][1] *= value; + resultMatrix.matrix[0][2] *= value; + resultMatrix.matrix[0][3] *= value; + + resultMatrix.matrix[1][0] *= value; + resultMatrix.matrix[1][1] *= value; + resultMatrix.matrix[1][2] *= value; + resultMatrix.matrix[1][3] *= value; + + resultMatrix.matrix[2][0] *= value; + resultMatrix.matrix[2][1] *= value; + resultMatrix.matrix[2][2] *= value; + resultMatrix.matrix[2][3] *= value; + + resultMatrix.matrix[3][0] *= value; + resultMatrix.matrix[3][1] *= value; + resultMatrix.matrix[3][2] *= value; + resultMatrix.matrix[3][3] *= value; + + return resultMatrix; +} + +DoubleMatrix4 +DoubleMatrix4::operator +(const DoubleMatrix4& rhs) const +{ + DoubleMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] += rhs.matrix[0][0]; + resultMatrix.matrix[0][1] += rhs.matrix[0][1]; + resultMatrix.matrix[0][2] += rhs.matrix[0][2]; + resultMatrix.matrix[0][3] += rhs.matrix[0][3]; + + resultMatrix.matrix[1][0] += rhs.matrix[1][0]; + resultMatrix.matrix[1][1] += rhs.matrix[1][1]; + resultMatrix.matrix[1][2] += rhs.matrix[1][2]; + resultMatrix.matrix[1][3] += rhs.matrix[1][3]; + + resultMatrix.matrix[2][0] += rhs.matrix[2][0]; + resultMatrix.matrix[2][1] += rhs.matrix[2][1]; + resultMatrix.matrix[2][2] += rhs.matrix[2][2]; + resultMatrix.matrix[2][3] += rhs.matrix[2][3]; + + resultMatrix.matrix[3][0] += rhs.matrix[3][0]; + resultMatrix.matrix[3][1] += rhs.matrix[3][1]; + resultMatrix.matrix[3][2] += rhs.matrix[3][2]; + resultMatrix.matrix[3][3] += rhs.matrix[3][3]; + + return resultMatrix; +} + +DoubleMatrix4 +DoubleMatrix4::operator +(double value) const +{ + DoubleMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] += value; + resultMatrix.matrix[0][1] += value; + resultMatrix.matrix[0][2] += value; + resultMatrix.matrix[0][3] += value; + + resultMatrix.matrix[1][0] += value; + resultMatrix.matrix[1][1] += value; + resultMatrix.matrix[1][2] += value; + resultMatrix.matrix[1][3] += value; + + resultMatrix.matrix[2][0] += value; + resultMatrix.matrix[2][1] += value; + resultMatrix.matrix[2][2] += value; + resultMatrix.matrix[2][3] += value; + + resultMatrix.matrix[3][0] += value; + resultMatrix.matrix[3][1] += value; + resultMatrix.matrix[3][2] += value; + resultMatrix.matrix[3][3] += value; + + return resultMatrix; +} + +DoubleMatrix4 +DoubleMatrix4::operator -(const DoubleMatrix4& rhs) const +{ + DoubleMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] -= rhs.matrix[0][0]; + resultMatrix.matrix[0][1] -= rhs.matrix[0][1]; + resultMatrix.matrix[0][2] -= rhs.matrix[0][2]; + resultMatrix.matrix[0][3] -= rhs.matrix[0][3]; + + resultMatrix.matrix[1][0] -= rhs.matrix[1][0]; + resultMatrix.matrix[1][1] -= rhs.matrix[1][1]; + resultMatrix.matrix[1][2] -= rhs.matrix[1][2]; + resultMatrix.matrix[1][3] -= rhs.matrix[1][3]; + + resultMatrix.matrix[2][0] -= rhs.matrix[2][0]; + resultMatrix.matrix[2][1] -= rhs.matrix[2][1]; + resultMatrix.matrix[2][2] -= rhs.matrix[2][2]; + resultMatrix.matrix[2][3] -= rhs.matrix[2][3]; + + resultMatrix.matrix[3][0] -= rhs.matrix[3][0]; + resultMatrix.matrix[3][1] -= rhs.matrix[3][1]; + resultMatrix.matrix[3][2] -= rhs.matrix[3][2]; + resultMatrix.matrix[3][3] -= rhs.matrix[3][3]; + + return resultMatrix; +} + +DoubleMatrix4 +DoubleMatrix4::operator -(double value) const +{ + DoubleMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] -= value; + resultMatrix.matrix[0][1] -= value; + resultMatrix.matrix[0][2] -= value; + resultMatrix.matrix[0][3] -= value; + + resultMatrix.matrix[1][0] -= value; + resultMatrix.matrix[1][1] -= value; + resultMatrix.matrix[1][2] -= value; + resultMatrix.matrix[1][3] -= value; + + resultMatrix.matrix[2][0] -= value; + resultMatrix.matrix[2][1] -= value; + resultMatrix.matrix[2][2] -= value; + resultMatrix.matrix[2][3] -= value; + + resultMatrix.matrix[3][0] -= value; + resultMatrix.matrix[3][1] -= value; + resultMatrix.matrix[3][2] -= value; + resultMatrix.matrix[3][3] -= value; + + return resultMatrix; +} + +DoubleMatrix4& +DoubleMatrix4::operator *=(const DoubleMatrix4& rhs) +{ + *this = *this * rhs; + return *this; +} + +DoubleMatrix4& +DoubleMatrix4::operator *=(double value) +{ + *this = *this * value; + return *this; +} + +DoubleMatrix4& +DoubleMatrix4::operator +=(const DoubleMatrix4& rhs) +{ + *this = *this + rhs; + return *this; +} + +DoubleMatrix4& +DoubleMatrix4::operator +=(double value) +{ + *this = *this + value; + return *this; +} + +DoubleMatrix4& +DoubleMatrix4::operator -=(const DoubleMatrix4& rhs) +{ + *this = *this - rhs; + return *this; +} + +DoubleMatrix4& +DoubleMatrix4::operator -=(double value) +{ + *this = *this - value; + return *this; +} + +DoubleMatrix4 +operator +(const double& value, const DoubleMatrix4& rhs) +{ + return rhs + value; +} + +DoubleMatrix4 +operator *(const double& value, const DoubleMatrix4& rhs) +{ + return rhs * value; +} + +DoubleMatrix4 +operator -(const double& value, const DoubleMatrix4& rhs) +{ + DoubleMatrix4 returnMatrix(rhs); + returnMatrix.Negate(); + returnMatrix += value; + return returnMatrix; +} + +bool +DoubleMatrix4::Equals(const Tizen::Base::Object& obj) const +{ + const DoubleMatrix4* pMatrix = dynamic_cast (&obj); + + if (pMatrix == null) + { + return false; + } + + return (*this == *pMatrix); +} + +int +DoubleMatrix4::GetHashCode(void) const +{ + return (Tizen::Base::Double::GetHashCode(matrix[0][0]) + Tizen::Base::Double::GetHashCode(matrix[1][0]) + + Tizen::Base::Double::GetHashCode(matrix[2][0]) + Tizen::Base::Double::GetHashCode(matrix[3][0]) + + Tizen::Base::Double::GetHashCode(matrix[0][1]) + Tizen::Base::Double::GetHashCode(matrix[1][1]) + + Tizen::Base::Double::GetHashCode(matrix[2][1]) + Tizen::Base::Double::GetHashCode(matrix[3][1]) + + Tizen::Base::Double::GetHashCode(matrix[0][2]) + Tizen::Base::Double::GetHashCode(matrix[1][2]) + + Tizen::Base::Double::GetHashCode(matrix[2][2]) + Tizen::Base::Double::GetHashCode(matrix[3][2]) + + Tizen::Base::Double::GetHashCode(matrix[0][3]) + Tizen::Base::Double::GetHashCode(matrix[1][3]) + + Tizen::Base::Double::GetHashCode(matrix[2][3]) + Tizen::Base::Double::GetHashCode(matrix[3][3])); +} + +double +DoubleMatrix4::GetDeterminant(void) const +{ + double a0 = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; + double a1 = matrix[0][0] * matrix[1][2] - matrix[0][2] * matrix[1][0]; + double a2 = matrix[0][0] * matrix[1][3] - matrix[0][3] * matrix[1][0]; + double a3 = matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]; + double a4 = matrix[0][1] * matrix[1][3] - matrix[0][3] * matrix[1][1]; + double a5 = matrix[0][2] * matrix[1][3] - matrix[0][3] * matrix[1][2]; + + double b0 = matrix[2][0] * matrix[3][1] - matrix[2][1] * matrix[3][0]; + double b1 = matrix[2][0] * matrix[3][2] - matrix[2][2] * matrix[3][0]; + double b2 = matrix[2][0] * matrix[3][3] - matrix[2][3] * matrix[3][0]; + double b3 = matrix[2][1] * matrix[3][2] - matrix[2][2] * matrix[3][1]; + double b4 = matrix[2][1] * matrix[3][3] - matrix[2][3] * matrix[3][1]; + double b5 = matrix[2][2] * matrix[3][3] - matrix[2][3] * matrix[3][2]; + + return a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; +} + +DoubleMatrix4 +DoubleMatrix4::GetInverse(void) const +{ + double a0 = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; + double a1 = matrix[0][0] * matrix[1][2] - matrix[0][2] * matrix[1][0]; + double a2 = matrix[0][0] * matrix[1][3] - matrix[0][3] * matrix[1][0]; + double a3 = matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]; + double a4 = matrix[0][1] * matrix[1][3] - matrix[0][3] * matrix[1][1]; + double a5 = matrix[0][2] * matrix[1][3] - matrix[0][3] * matrix[1][2]; + + double b0 = matrix[2][0] * matrix[3][1] - matrix[2][1] * matrix[3][0]; + double b1 = matrix[2][0] * matrix[3][2] - matrix[2][2] * matrix[3][0]; + double b2 = matrix[2][0] * matrix[3][3] - matrix[2][3] * matrix[3][0]; + double b3 = matrix[2][1] * matrix[3][2] - matrix[2][2] * matrix[3][1]; + double b4 = matrix[2][1] * matrix[3][3] - matrix[2][3] * matrix[3][1]; + double b5 = matrix[2][2] * matrix[3][3] - matrix[2][3] * matrix[3][2]; + + double determinant = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; + + if (Tizen::Base::Double::Compare(determinant, 0.0f) == 0) + { + return *this; + } + + double inverseMatrix[4][4]; + + inverseMatrix[0][0] = (matrix[1][1] * b5 - matrix[1][2] * b4 + matrix[1][3] * b3) / determinant; + inverseMatrix[1][0] = (-matrix[1][0] * b5 + matrix[1][2] * b2 - matrix[1][3] * b1) / determinant; + inverseMatrix[2][0] = (matrix[1][0] * b4 - matrix[1][1] * b2 + matrix[1][3] * b0) / determinant; + inverseMatrix[3][0] = (-matrix[1][0] * b3 + matrix[1][1] * b1 - matrix[1][2] * b0) / determinant; + + inverseMatrix[0][1] = (-matrix[0][1] * b5 + matrix[0][2] * b4 - matrix[0][3] * b3) / determinant; + inverseMatrix[1][1] = (matrix[0][0] * b5 - matrix[0][2] * b2 + matrix[0][3] * b1) / determinant; + inverseMatrix[2][1] = (-matrix[0][0] * b4 + matrix[0][1] * b2 - matrix[0][3] * b0) / determinant; + inverseMatrix[3][1] = (matrix[0][0] * b3 - matrix[0][1] * b1 + matrix[0][2] * b0) / determinant; + + inverseMatrix[0][2] = (matrix[3][1] * a5 - matrix[3][2] * a4 + matrix[3][3] * a3) / determinant; + inverseMatrix[1][2] = (-matrix[3][0] * a5 + matrix[3][2] * a2 - matrix[3][3] * a1) / determinant; + inverseMatrix[2][2] = (matrix[3][0] * a4 - matrix[3][1] * a2 + matrix[3][3] * a0) / determinant; + inverseMatrix[3][2] = (-matrix[3][0] * a3 + matrix[3][1] * a1 - matrix[3][2] * a0) / determinant; + + inverseMatrix[0][3] = (-matrix[2][1] * a5 + matrix[2][2] * a4 - matrix[2][3] * a3) / determinant; + inverseMatrix[1][3] = (matrix[2][0] * a5 - matrix[2][2] * a2 + matrix[2][3] * a1) / determinant; + inverseMatrix[2][3] = (-matrix[2][0] * a4 + matrix[2][1] * a2 - matrix[2][3] * a0) / determinant; + inverseMatrix[3][3] = (matrix[2][0] * a3 - matrix[2][1] * a1 + matrix[2][2] * a0) / determinant; + + return DoubleMatrix4(inverseMatrix); +} + +double +DoubleMatrix4::GetTrace(void) const +{ + return matrix[0][0] + matrix[1][1] + matrix[2][2] + matrix[3][3]; +} + +DoubleMatrix4 +DoubleMatrix4::GetTranspose(void) const +{ + DoubleMatrix4 transposeMatrix(matrix); + transposeMatrix.Transpose(); + + return transposeMatrix; +} + +bool +DoubleMatrix4::IsIdentity(void) const +{ + if ((Tizen::Base::Double::Compare(matrix[0][0], 1.0f) != 0) || (Tizen::Base::Double::Compare(matrix[1][1], 1.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[2][2], 1.0f) != 0) || (Tizen::Base::Double::Compare(matrix[3][3], 1.0f) != 0)) + { + return false; + } + + if ((Tizen::Base::Double::Compare(matrix[0][1], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[0][2], 0.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[0][3], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[1][0], 0.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[1][2], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[1][3], 0.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[2][0], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[2][1], 0.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[2][3], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[3][0], 0.0f) != 0) || + (Tizen::Base::Double::Compare(matrix[3][1], 0.0f) != 0) || (Tizen::Base::Double::Compare(matrix[3][2], 0.0f) != 0)) + { + return false; + } + + return true; +} + +bool +DoubleMatrix4::IsInvertible(void) const +{ + if (Tizen::Base::Double::Compare(GetDeterminant(), 0.0f) == 0) + { + return false; + } + + return true; +} + +void +DoubleMatrix4::Negate(void) +{ + matrix[0][0] = -matrix[0][0]; + matrix[0][1] = -matrix[0][1]; + matrix[0][2] = -matrix[0][2]; + matrix[0][3] = -matrix[0][3]; + + matrix[1][0] = -matrix[1][0]; + matrix[1][1] = -matrix[1][1]; + matrix[1][2] = -matrix[1][2]; + matrix[1][3] = -matrix[1][3]; + + matrix[2][0] = -matrix[2][0]; + matrix[2][1] = -matrix[2][1]; + matrix[2][2] = -matrix[2][2]; + matrix[2][3] = -matrix[2][3]; + + matrix[3][0] = -matrix[3][0]; + matrix[3][1] = -matrix[3][1]; + matrix[3][2] = -matrix[3][2]; + matrix[3][3] = -matrix[3][3]; +} + +void +DoubleMatrix4::SetAsIdentity(void) +{ + matrix[0][0] = 1.0f; + matrix[0][1] = 0.0f; + matrix[0][2] = 0.0f; + matrix[0][3] = 0.0f; + + matrix[1][0] = 0.0f; + matrix[1][1] = 1.0f; + matrix[1][2] = 0.0f; + matrix[1][3] = 0.0f; + + matrix[2][0] = 0.0f; + matrix[2][1] = 0.0f; + matrix[2][2] = 1.0f; + matrix[2][3] = 0.0f; + + matrix[3][0] = 0.0f; + matrix[3][1] = 0.0f; + matrix[3][2] = 0.0f; + matrix[3][3] = 1.0f; +} + +result +DoubleMatrix4::Invert(void) +{ + double a0 = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; + double a1 = matrix[0][0] * matrix[1][2] - matrix[0][2] * matrix[1][0]; + double a2 = matrix[0][0] * matrix[1][3] - matrix[0][3] * matrix[1][0]; + double a3 = matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]; + double a4 = matrix[0][1] * matrix[1][3] - matrix[0][3] * matrix[1][1]; + double a5 = matrix[0][2] * matrix[1][3] - matrix[0][3] * matrix[1][2]; + + double b0 = matrix[2][0] * matrix[3][1] - matrix[2][1] * matrix[3][0]; + double b1 = matrix[2][0] * matrix[3][2] - matrix[2][2] * matrix[3][0]; + double b2 = matrix[2][0] * matrix[3][3] - matrix[2][3] * matrix[3][0]; + double b3 = matrix[2][1] * matrix[3][2] - matrix[2][2] * matrix[3][1]; + double b4 = matrix[2][1] * matrix[3][3] - matrix[2][3] * matrix[3][1]; + double b5 = matrix[2][2] * matrix[3][3] - matrix[2][3] * matrix[3][2]; + + double determinant = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; + + SysTryReturnResult(NID_BASE, Tizen::Base::Double::Compare(determinant, 0.0f) != 0, E_INVALID_OPERATION, + "The current instance is not invertible."); + + double inverseMatrix[4][4]; + + inverseMatrix[0][0] = (matrix[1][1] * b5 - matrix[1][2] * b4 + matrix[1][3] * b3) / determinant; + inverseMatrix[1][0] = (-matrix[1][0] * b5 + matrix[1][2] * b2 - matrix[1][3] * b1) / determinant; + inverseMatrix[2][0] = (matrix[1][0] * b4 - matrix[1][1] * b2 + matrix[1][3] * b0) / determinant; + inverseMatrix[3][0] = (-matrix[1][0] * b3 + matrix[1][1] * b1 - matrix[1][2] * b0) / determinant; + + inverseMatrix[0][1] = (-matrix[0][1] * b5 + matrix[0][2] * b4 - matrix[0][3] * b3) / determinant; + inverseMatrix[1][1] = (matrix[0][0] * b5 - matrix[0][2] * b2 + matrix[0][3] * b1) / determinant; + inverseMatrix[2][1] = (-matrix[0][0] * b4 + matrix[0][1] * b2 - matrix[0][3] * b0) / determinant; + inverseMatrix[3][1] = (matrix[0][0] * b3 - matrix[0][1] * b1 + matrix[0][2] * b0) / determinant; + + inverseMatrix[0][2] = (matrix[3][1] * a5 - matrix[3][2] * a4 + matrix[3][3] * a3) / determinant; + inverseMatrix[1][2] = (-matrix[3][0] * a5 + matrix[3][2] * a2 - matrix[3][3] * a1) / determinant; + inverseMatrix[2][2] = (matrix[3][0] * a4 - matrix[3][1] * a2 + matrix[3][3] * a0) / determinant; + inverseMatrix[3][2] = (-matrix[3][0] * a3 + matrix[3][1] * a1 - matrix[3][2] * a0) / determinant; + + inverseMatrix[0][3] = (-matrix[2][1] * a5 + matrix[2][2] * a4 - matrix[2][3] * a3) / determinant; + inverseMatrix[1][3] = (matrix[2][0] * a5 - matrix[2][2] * a2 + matrix[2][3] * a1) / determinant; + inverseMatrix[2][3] = (-matrix[2][0] * a4 + matrix[2][1] * a2 - matrix[2][3] * a0) / determinant; + inverseMatrix[3][3] = (matrix[2][0] * a3 - matrix[2][1] * a1 + matrix[2][2] * a0) / determinant; + + memcpy(matrix, inverseMatrix, MATRIX_SIZE); + + return E_SUCCESS; +} + +void +DoubleMatrix4::Transpose(void) +{ + double tmp = 0.0f; + SWAP_VALUES(matrix[0][1], matrix[1][0], tmp); + SWAP_VALUES(matrix[0][2], matrix[2][0], tmp); + SWAP_VALUES(matrix[0][3], matrix[3][0], tmp); + + SWAP_VALUES(matrix[1][2], matrix[2][1], tmp); + SWAP_VALUES(matrix[1][3], matrix[3][1], tmp); + + SWAP_VALUES(matrix[2][3], matrix[3][2], tmp); +} + +void +DoubleMatrix4::SetAsNull(void) +{ + matrix[0][0] = 0.0f; + matrix[0][1] = 0.0f; + matrix[0][2] = 0.0f; + matrix[0][3] = 0.0f; + + matrix[1][0] = 0.0f; + matrix[1][1] = 0.0f; + matrix[1][2] = 0.0f; + matrix[1][3] = 0.0f; + + matrix[2][0] = 0.0f; + matrix[2][1] = 0.0f; + matrix[2][2] = 0.0f; + matrix[2][3] = 0.0f; + + matrix[3][0] = 0.0f; + matrix[3][1] = 0.0f; + matrix[3][2] = 0.0f; + matrix[3][3] = 0.0f; +} + +}} // Tizen::Base diff --git a/src/base/FBaseErrors.cpp b/src/base/FBaseErrors.cpp new file mode 100644 index 0000000..9214c9f --- /dev/null +++ b/src/base/FBaseErrors.cpp @@ -0,0 +1,23 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FBaseErrors.cpp + * @brief This is the implementation file of Result class. + */ + +#include + diff --git a/src/base/FBaseFloat.cpp b/src/base/FBaseFloat.cpp new file mode 100644 index 0000000..4225a8f --- /dev/null +++ b/src/base/FBaseFloat.cpp @@ -0,0 +1,291 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloat.cpp + * @brief This is the implementation file for Float class. + * @see Number class + */ + +// Includes +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +union FloatBitRep +{ + explicit + FloatBitRep(float f = 0.0) + : value(f) + { + }; + + FloatBitRep(unsigned int i) + : rep(i) + { + }; + + float value; + unsigned int rep; +}; + +Float::Float(float value) + : value(value) + , __pFloatImpl(null) +{ +} + +Float::Float(const Float& value) + : value(value.value) + , __pFloatImpl(null) +{ +} + +Float::~Float(void) +{ +} + +Float& +Float::operator =(const Float& rhs) +{ + if (&rhs != this) + { + value = rhs.value; + } + return *this; +} + +int +Float::Compare(float f1, float f2) +{ + int ret = 0; + + if (f1 > f2) + { + ret = 1; + } + else if (f1 < f2) + { + ret = -1; + } + else + { + ret = 0; + } + + return ret; +} + +int +Float::CompareTo(const Float& value) const +{ + return(Float::Compare(this->value, value.value)); +} + +bool +Float::Equals(const Object& obj) const +{ + const Float* pOther = dynamic_cast (&obj); + + if (pOther == null) + { + return false; + } + + if (Float::Compare(this->value, (*pOther).value) == 0) + { + return true; + } + else + { + return false; + } +} + +int +Float::GetHashCode(void) const +{ + float* pTemp = const_cast (&value); + int* pValue = reinterpret_cast (pTemp); + return *pValue; +} + +int +Float::GetHashCode(float val) +{ + int* pValue = reinterpret_cast (&val); + return *pValue; +} + +result +Float::Parse(const String& s, float& ret) +{ + wchar_t* pEnd = null; + ret = 0; + + SysTryReturn(NID_BASE, s.GetLength() >= 1, E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of s MUST be greater than 0.", GetErrorMessage(E_NUM_FORMAT)); + + errno = 0; + ret = wcstof(s.GetPointer(), &pEnd); + SysTryReturn(NID_BASE, (!Float::Compare(pEnd[0], 0)), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Float parse failed. Scan stopped at (%ls).", GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryReturn(NID_BASE, !((!Float::Compare(ret, HUGE_VAL) || !Float::Compare(ret, -HUGE_VAL)) && (errno != 0)), + E_NUM_FORMAT, E_NUM_FORMAT, "[%s] Parsed value cannot fit into a Float.", GetErrorMessage(E_NUM_FORMAT)); + + return E_SUCCESS; +} + +char +Float::ToChar(void) const +{ + return static_cast (value); +} + +short +Float::ToShort(void) const +{ + return static_cast (value); +} + +int +Float::ToInt(void) const +{ + return static_cast (value); +} + +long +Float::ToLong(void) const +{ + return static_cast (value); +} + +long long +Float::ToLongLong(void) const +{ + return static_cast (value); +} + +float +Float::ToFloat(void) const +{ + return value; +} + +double +Float::ToDouble(void) const +{ + return static_cast (value); +} + +String +Float::ToString(void) const +{ + return(Float::ToString(value)); +} + +String +Float::ToString(float value) +{ + const static unsigned int MAX_DIG = 7 + 3; + const static unsigned int FLOAT_LENGTH_MAX = __DBL_MAX_10_EXP + MAX_DIG; + + if (Float::IsNaN(value)) + { + return String(L"NaN"); + } + else if (Float::IsInfinity(value)) + { + return String(L"Infinity"); + } + else + { + wchar_t sValue[FLOAT_LENGTH_MAX + 1] = {0, }; + swprintf(sValue, (sizeof(sValue) / sizeof(sValue[0])), L"%g", value); + + return String(sValue); + } +} + +int +Float::ToBits(float value) +{ + FloatBitRep bitRep; + bitRep.value = value; + return bitRep.rep; +} + +float +Float::ToFloatFromBits(int value) +{ + FloatBitRep bitRep; + bitRep.rep = value; + return bitRep.value; +} + +bool +Float::IsFinite(float value) +{ + return((isfinite(value) != 0) ? true : false); +} + +bool +Float::IsInfinity(void) const +{ + return(Float::IsInfinity(value)); +} + +bool +Float::IsInfinity(float value) +{ + return(!Float::IsFinite(value)); +} + +bool +Float::IsNaN(void) const +{ + return(Float::IsNaN(value)); +} + +bool +Float::IsNaN(float value) +{ + return((isnan(value) != 0) ? true : false); +} + +float +Float::GetMaxValue(void) +{ + return FLT_MAX; +} + +float +Float::GetMinValue(void) +{ + return FLT_MIN; +} + +}} // Tizen::Base diff --git a/src/base/FBaseFloatComparer.cpp b/src/base/FBaseFloatComparer.cpp new file mode 100644 index 0000000..bc9ffed --- /dev/null +++ b/src/base/FBaseFloatComparer.cpp @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloatComparer.cpp + * @brief This is the implementation file for FloatComparer class. + * @see Float and Tizen::Base::Collection::IComparer + */ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +FloatComparer::FloatComparer(void) + : __pFloatComparerImpl(null) +{ +} + +FloatComparer::~FloatComparer(void) +{ +} + +result +FloatComparer::Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const +{ + const Float* pFloat1 = dynamic_cast (&obj1); + const Float* pFloat2 = dynamic_cast (&obj2); + + SysTryReturn(NID_BASE, (pFloat1 != null && pFloat2 != null), E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used.Both of the obj1 and obj2 MUST be Float.", GetErrorMessage(E_INVALID_ARG)); + + cmp = Float::Compare(pFloat1->ToFloat(), pFloat2->ToFloat()); + + return E_SUCCESS; +} + +}} //Tizen::Base diff --git a/src/base/FBaseFloatMatrix.cpp b/src/base/FBaseFloatMatrix.cpp new file mode 100644 index 0000000..0ba1c1c --- /dev/null +++ b/src/base/FBaseFloatMatrix.cpp @@ -0,0 +1,874 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloatMatrix.cpp + * @brief This is the implementation for FloatMatrix class. + */ + +#include +#include +#include + +namespace Tizen { namespace Base +{ + +FloatMatrix::FloatMatrix(void) + : __pImpl(null) + , __pMatrix(null) + , __row(0) + , __column(0) +{ +} + +FloatMatrix::FloatMatrix(const FloatMatrix& rhs) + : __pImpl(null) + , __row(rhs.__row) + , __column(rhs.__column) +{ + AllocateCapacity(__row, __column); + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = rhs.__pMatrix[i][j]; + } + } +} + +FloatMatrix::FloatMatrix(int rowCount, int columnCount) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + SetAsNull(); +} + +FloatMatrix::FloatMatrix(int rowCount, int columnCount, const float* pArray, bool rowMajor) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + if (pArray != null) + { + if (rowMajor == true) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i * __row + j]; + } + } + } + else + { + for (int i = 0; i < __column; i++) + { + for (int j = 0; j < __row; j++) + { + __pMatrix[j][i] = pArray[i * __column + j]; + } + } + } + } + else + { + SetAsNull(); + } +} + +FloatMatrix::FloatMatrix(int rowCount, int columnCount, const float* pArray[]) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + if (pArray != null) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i][j]; + } + } + } + else + { + SetAsIdentity(); + } +} + +FloatMatrix::~FloatMatrix(void) +{ + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + + delete[] __pMatrix; +} + +bool +FloatMatrix::operator ==(const FloatMatrix& rhs) const +{ + if (this == &rhs) + { + return true; + } + + if ((__row != rhs.__row) || (__column != rhs.__column)) + { + return false; + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + if (__pMatrix[i][j] != rhs.__pMatrix[i][j]) + { + return false; + } + } + } + + return true; +} + +bool +FloatMatrix::operator !=(const FloatMatrix& rhs) const +{ + return !(*this == rhs); +} + +FloatMatrix& +FloatMatrix::operator =(const FloatMatrix& rhs) +{ + if (this == &rhs) + { + return *this; + } + + SysTryReturn(NID_BASE, (__row == rhs.__row) && (__column == rhs.__column), *this, E_INVALID_ARG, + "[%s] Invalid argument is used. Either row or column count of the current instance is not same with that of the specified instance.", + GetErrorMessage(E_INVALID_ARG)); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = rhs.__pMatrix[i][j]; + } + } + + return *this; +} + +bool +FloatMatrix::Equals(const Tizen::Base::Object& obj) const +{ + const FloatMatrix* pOther = dynamic_cast (&obj); + + if (pOther == null) + { + return false; + } + + return (*this == *pOther); +} + +int +FloatMatrix::GetHashCode(void) const +{ + int hash = 0; + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + hash = hash + Tizen::Base::Float::GetHashCode(__pMatrix[i][j]); + } + } + + return hash; +} + +result +FloatMatrix::Add(const FloatMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, (__row == matrix.__row) && (__column == matrix.__column), E_INVALID_ARG, + "Either row or column count of the current instance is not same with that of the specified instance."); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] + matrix.__pMatrix[i][j]; + } + } + + return E_SUCCESS; +} + +void +FloatMatrix::AddToEachElement(float value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] + value; + } + } +} + +bool +FloatMatrix::AllocateCapacity(int rowCount, int columnCount) +{ + std::unique_ptr pMatrix(new (std::nothrow) float* [rowCount]); + SysTryReturn(NID_BASE, pMatrix != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for ( int i = 0 ; i < rowCount ; i++ ) + { + pMatrix[i] = new (std::nothrow) float[columnCount]; + if (pMatrix[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMatrix[j]; + } + return false; + } + } + + __pMatrix = pMatrix.release(); + + return true; +} + +float +FloatMatrix::CalculateDeterminant(float** pMatrix, int order) const // For perfomance, we have to change the logic of recursive to LU decomposition. +{ + SysTryReturn(NID_BASE, pMatrix != null, 0.0f, E_INVALID_ARG, "[%s] Invalid argument is used. pMatrix is null.", + GetErrorMessage(E_INVALID_ARG)); + + if (order == 1) + { + return pMatrix[0][0]; + } + + float determinant = 0.0f; + std::unique_ptr pMinor(new (std::nothrow) float* [order - 1]); + SysTryReturn(NID_BASE, pMinor != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + for (int i = 0; i < order - 1; i++) + { + pMinor[i] = new (std::nothrow) float[order - 1]; + if (pMinor[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + return determinant; + } + } + + bool signFlag = true; + for (int i = 0; i < order; i++) + { + GetMinor(pMatrix, pMinor.get(), 0, i, order); + + if (signFlag == true) + { + determinant += pMatrix[0][i] * CalculateDeterminant(pMinor.get(), order - 1); + signFlag = false; + } + else + { + determinant += -pMatrix[0][i] * CalculateDeterminant(pMinor.get(), order - 1); + signFlag = true; + } + } + + for (int i = 0; i < order - 1; i++) + { + delete[] pMinor[i]; + } + + return determinant; +} + +int +FloatMatrix::GetColumnCount(void) const +{ + return __column; +} + +float* +FloatMatrix::GetColumnN(int columnIndex) const +{ + SysTryReturn(NID_BASE, columnIndex <= __column, null, E_INVALID_ARG, + "[%s] Invalid argument is used. The columnIndex is larger than the column count of the current instance.", + GetErrorMessage(E_INVALID_ARG)); + + std::unique_ptr pColumn(new (std::nothrow) float [__row]); + SysTryReturn(NID_BASE, pColumn != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row; i++) + { + pColumn[i] = __pMatrix[i][columnIndex]; + } + + return pColumn.release(); +} + +float +FloatMatrix::GetDeterminant(void) const +{ + SysTryReturn(NID_BASE, __row == __column, 0.0f, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + return CalculateDeterminant(__pMatrix, __row); +} + +float +FloatMatrix::GetElement(int rowIndex, int columnIndex) const +{ + SysTryReturn(NID_BASE, (rowIndex <= __row) && (columnIndex <= __column), 0.0f, E_INVALID_ARG, + "[%s] Invalid argument is used. The current instance is not a square matrix.", GetErrorMessage(E_INVALID_ARG)); + + return __pMatrix[rowIndex][columnIndex]; +} + +FloatMatrix* +FloatMatrix::GetInverseN(void) const +{ + SysTryReturn(NID_BASE, __row == __column, null, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + std::unique_ptr pInverseMatrix(new (std::nothrow) FloatMatrix(__row, __column)); + SysTryReturn(NID_BASE, pInverseMatrix != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + float determinant = CalculateDeterminant(__pMatrix, __row); + + if (Tizen::Base::Float::Compare(determinant,0.0f) == 0) + { + return null; + } + + std::unique_ptr pMinor(new (std::nothrow) float* [__row - 1]); + SysTryReturn(NID_BASE, pMinor != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row -1; i++) + { + pMinor[i] = new (std::nothrow) float[__row - 1]; + if (pMinor[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + + return null; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __row; j++) + { + GetMinor(__pMatrix, pMinor.get(), i, j, __row); + pInverseMatrix->__pMatrix[j][i] = CalculateDeterminant(pMinor.get(), __row - 1) / determinant; + if ((i + j + 2) % 2 == 1) + { + pInverseMatrix->__pMatrix[j][i] = -pInverseMatrix->__pMatrix[j][i]; + } + } + } + + for ( int i = 0 ; i < __row -1 ; i++ ) + { + delete[] pMinor[i]; + } + + return pInverseMatrix.release(); +} + +void +FloatMatrix::GetMinor(float** pSrc, float** pDest, int rowIndex, int columnIndex, int order) const +{ + SysTryReturn(NID_BASE, pSrc != null, , E_INVALID_ARG, "[%s] Invalid argument is used. pSrc is null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_BASE, pDest != null, , E_INVALID_ARG, "[%s] Invalid argument is used. pDest is null.", GetErrorMessage(E_INVALID_ARG)); + + int rowCount = 0; + int columnCount = 0; + + for (int i = 0; i < order; i++) + { + if (i != rowIndex) + { + columnCount = 0; + + for (int j = 0; j < order; j++) + { + if (j != columnIndex) + { + pDest[rowCount][columnCount] = pSrc[i][j]; + columnCount++; + } + } + rowCount++; + } + } +} + +int +FloatMatrix::GetRowCount(void) const +{ + return __row; +} + +float* +FloatMatrix::GetRowN(int rowIndex) const +{ + SysTryReturn(NID_BASE, rowIndex <= __row, null, E_INVALID_ARG, + "[%s] Invalid argument is used. The rowIndex is larger than the row count of the current instance.", + GetErrorMessage(E_INVALID_ARG)); + + std::unique_ptr pRow(new (std::nothrow) float [__column]); + SysTryReturn(NID_BASE, pRow != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __column; i++) + { + pRow[i] = __pMatrix[rowIndex][i]; + } + + return pRow.release(); +} + +result +FloatMatrix::GetTrace(float& value) const +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + value = 0.0f; + + for (int i = 0; i < __row; i++) + { + value += __pMatrix[i][i]; + } + + return E_SUCCESS; +} + +FloatMatrix* +FloatMatrix::GetTransposeN(void) const +{ + SysTryReturn(NID_BASE, __row == __column, null, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + std::unique_ptr pTransposeMatrix(new (std::nothrow) FloatMatrix(*this)); + SysTryReturn(NID_BASE, pTransposeMatrix != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + int columnIndex = 1; + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < columnIndex; j++) + { + float temp = pTransposeMatrix->__pMatrix[i][j]; + pTransposeMatrix->__pMatrix[i][j] = pTransposeMatrix->__pMatrix[j][i]; + pTransposeMatrix->__pMatrix[j][i] = temp; + } + + columnIndex++; + } + + return pTransposeMatrix.release(); +} + +bool +FloatMatrix::IsIdentity(void) const +{ + if (__row != __column) + { + return false; + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + if (i == j) + { + if (Tizen::Base::Float::Compare(__pMatrix[i][j],1.0f) != 0) + { + return false; + } + } + else + { + if (Tizen::Base::Float::Compare(__pMatrix[i][j],0.0f) != 0) + { + return false; + } + } + + + } + } + return true; +} + +bool +FloatMatrix::IsInvertible(void) const +{ + int ret = Tizen::Base::Float::Compare(GetDeterminant(),0.0f); + + if (ret == 0) + { + return false; + } + else + { + return true; + } +} + +result +FloatMatrix::Multiply(const FloatMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, __column == matrix.__row, E_INVALID_ARG, + "The column count of the current instance is not same with the row count of the specified instance."); + + std::unique_ptr pResult(new (std::nothrow) float* [__row]); + SysTryReturnResult(NID_BASE, pResult != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + for ( int i = 0 ; i < __row ; i++ ) + { + pResult[i] = new (std::nothrow) float[matrix.__column]; + if (pResult[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pResult[j]; + } + return E_OUT_OF_MEMORY; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < matrix.__column; j++) + { + pResult[i][j] = 0.0f; + + for (int k = 0; k < __column; k++) + { + pResult[i][j] += __pMatrix[i][k] * matrix.__pMatrix[k][j]; + } + } + } + + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + delete[] __pMatrix; + + __pMatrix = pResult.release(); + + return E_SUCCESS; +} + +void +FloatMatrix::Multiply(float value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] * value; + } + } +} + +void +FloatMatrix::Negate(void) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = -__pMatrix[i][j]; + } + } +} + +result +FloatMatrix::SetAsIdentity(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + for (int i = 0; i < __row; i ++) + { + for (int j = 0; j < __column; j++) + { + if (i == j) + { + __pMatrix[i][j] = 1.0f; + } + else + { + __pMatrix[i][j] = 0.0f; + } + } + } + + return E_SUCCESS; +} + +result +FloatMatrix::Invert(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + float determinant = CalculateDeterminant(__pMatrix, __row); + SysTryReturnResult(NID_BASE, Tizen::Base::Float::Compare(determinant, 0.0f) != 0, E_INVALID_OPERATION, + "The current instance is not invertible."); + + std::unique_ptr pInverse(new (std::nothrow) float* [__row]); + SysTryReturn(NID_BASE, pInverse != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row; i++) + { + pInverse[i] = new (std::nothrow) float[__row]; + if (pInverse[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pInverse[j]; + } + return E_OUT_OF_MEMORY; + } + } + + std::unique_ptr pMinor(new (std::nothrow) float* [__row - 1]); + if (pMinor == null) + { + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] pInverse[i]; + } + return E_OUT_OF_MEMORY; + } + + for (int i = 0; i < __row - 1; i++) + { + pMinor[i] = new (std::nothrow) float[__row - 1]; + if (pMinor[i] == null) + { + for (int i = 0 ; i < __row ; i++) + { + delete[] pInverse[i]; + } + + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + + return E_OUT_OF_MEMORY; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __row; j++) + { + GetMinor(__pMatrix, pMinor.get(), i, j, __row); + pInverse[j][i] = CalculateDeterminant(pMinor.get(), __row - 1) / determinant; + if ((i +j +2) % 2 == 1) + { + pInverse[j][i] = -pInverse[j][i]; + } + } + } + + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + delete[] __pMatrix; + + __pMatrix = pInverse.release(); + + for ( int i = 0 ; i < __row -1; i++ ) + { + delete[] pMinor[i]; + } + + return E_SUCCESS; +} + +result +FloatMatrix::Transpose(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + int columnIndex = 1; + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < columnIndex; j++) + { + float temp = __pMatrix[i][j]; + __pMatrix[i][j] = __pMatrix[j][i]; + __pMatrix[j][i] = temp; + } + + columnIndex++; + } + + return E_SUCCESS; +} + +result +FloatMatrix::SetColumn(int columnIndex, const float* pArray) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null."); + SysTryReturnResult(NID_BASE, columnIndex <= __column, E_INVALID_ARG, + "columnIndex is larger than the column count of the current instance."); + + for (int i = 0; i < __row; i++) + { + __pMatrix[i][columnIndex] = pArray[i]; + } + + return E_SUCCESS; +} + +result +FloatMatrix::SetRow(int rowIndex, const float* pArray) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null."); + SysTryReturnResult(NID_BASE, rowIndex <= __row, E_INVALID_ARG, + "rowIndex is larger than the row count of the current instance."); + + for (int i = 0; i < __column; i++) + { + __pMatrix[rowIndex][i] = pArray[i]; + } + + return E_SUCCESS; +} + +result +FloatMatrix::SetElement(int rowIndex, int columnIndex, float value) +{ + SysTryReturnResult(NID_BASE, columnIndex <= __column, E_INVALID_ARG, + "columnIndex is larger than the column count of the current instance."); + SysTryReturnResult(NID_BASE, rowIndex <= __row, E_INVALID_ARG, + "rowIndex is larger than the row count of the current instance."); + + __pMatrix[rowIndex][columnIndex] = value; + + return E_SUCCESS; +} + +result +FloatMatrix::SetValue(const float* pArray, bool rowMajor) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null."); + + if (rowMajor == true) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i * __row + j]; + } + } + } + else + { + for (int i = 0; i < __column; i++) + { + for (int j = 0; j < __row; j++) + { + __pMatrix[j][i] = pArray[i * __column + j]; + } + } + } + + return E_SUCCESS; +} + +void +FloatMatrix::SetAsNull(void) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = 0.0f; + } + } +} + +result +FloatMatrix::Subtract(const FloatMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, (__row == matrix.__row) && (__column == matrix.__column), E_INVALID_ARG, + "Either row or column count of the current instance is not same with that of the specified instance."); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] - matrix.__pMatrix[i][j]; + } + } + + return E_SUCCESS; +} + +void +FloatMatrix::SubtractToEachElement(float value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] - value; + } + } +} + +}} // Tizen::Base diff --git a/src/base/FBaseFloatMatrix3.cpp b/src/base/FBaseFloatMatrix3.cpp new file mode 100644 index 0000000..2a9d188 --- /dev/null +++ b/src/base/FBaseFloatMatrix3.cpp @@ -0,0 +1,492 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloatMatrix3.cpp + * @brief This is the implementation for FloatMatrix class. + */ + +#include +#include + +namespace Tizen { namespace Base +{ + +static const int MATRIX_SIZE = sizeof(float) * 9; +#define SWAP_VALUES(a, b, tmp) \ + tmp = a; \ + a = b; \ + b = tmp; + +FloatMatrix3::FloatMatrix3(void) + : __pImpl(null) +{ + SetAsNull(); +} + +FloatMatrix3::FloatMatrix3(const FloatMatrix3& rhs) + : __pImpl(null) +{ + memcpy(matrix, rhs.matrix, MATRIX_SIZE); +} + +FloatMatrix3::FloatMatrix3(const float matrix[3][3]) + : __pImpl(null) +{ + memcpy(this->matrix, matrix, MATRIX_SIZE); +} + +FloatMatrix3::~FloatMatrix3(void) +{ +} + +bool +FloatMatrix3::operator ==(const FloatMatrix3& rhs) const +{ + if (this == &rhs) + { + return true; + } + + return (matrix[0][0] == rhs.matrix[0][0] && + matrix[0][1] == rhs.matrix[0][1] && + matrix[0][2] == rhs.matrix[0][2] && + matrix[1][0] == rhs.matrix[1][0] && + matrix[1][1] == rhs.matrix[1][1] && + matrix[1][2] == rhs.matrix[1][2] && + matrix[2][0] == rhs.matrix[2][0] && + matrix[2][1] == rhs.matrix[2][1] && + matrix[2][2] == rhs.matrix[2][2]); +} + +bool +FloatMatrix3::operator !=(const FloatMatrix3& rhs) const +{ + return !(*this == rhs); +} + +FloatMatrix3& +FloatMatrix3::operator =(const FloatMatrix3& rhs) +{ + if (this != &rhs) + { + memcpy(matrix, rhs.matrix, MATRIX_SIZE); + } + + return *this; +} + +FloatMatrix3& +FloatMatrix3::operator =(float value) +{ + matrix[0][0] = value; + matrix[1][0] = value; + matrix[2][0] = value; + + matrix[0][1] = value; + matrix[1][1] = value; + matrix[2][1] = value; + + matrix[0][2] = value; + matrix[1][2] = value; + matrix[2][2] = value; + + return *this; +} + +FloatMatrix3 +FloatMatrix3::operator *(const FloatMatrix3& rhs) const // need to check performance +{ + FloatMatrix3 resultMatrix; + + resultMatrix.matrix[0][0] = matrix[0][0] * rhs.matrix[0][0] + matrix[0][1] * rhs.matrix[1][0] + matrix[0][2] * rhs.matrix[2][0]; + resultMatrix.matrix[0][1] = matrix[0][0] * rhs.matrix[0][1] + matrix[0][1] * rhs.matrix[1][1] + matrix[0][2] * rhs.matrix[2][1]; + resultMatrix.matrix[0][2] = matrix[0][0] * rhs.matrix[0][2] + matrix[0][1] * rhs.matrix[1][2] + matrix[0][2] * rhs.matrix[2][2]; + + resultMatrix.matrix[1][0] = matrix[1][0] * rhs.matrix[0][0] + matrix[1][1] * rhs.matrix[1][0] + matrix[1][2] * rhs.matrix[2][0]; + resultMatrix.matrix[1][1] = matrix[1][0] * rhs.matrix[0][1] + matrix[1][1] * rhs.matrix[1][1] + matrix[1][2] * rhs.matrix[2][1]; + resultMatrix.matrix[1][2] = matrix[1][0] * rhs.matrix[0][2] + matrix[1][1] * rhs.matrix[1][2] + matrix[1][2] * rhs.matrix[2][2]; + + resultMatrix.matrix[2][0] = matrix[2][0] * rhs.matrix[0][0] + matrix[2][1] * rhs.matrix[1][0] + matrix[2][2] * rhs.matrix[2][0]; + resultMatrix.matrix[2][1] = matrix[2][0] * rhs.matrix[0][1] + matrix[2][1] * rhs.matrix[1][1] + matrix[2][2] * rhs.matrix[2][1]; + resultMatrix.matrix[2][2] = matrix[2][0] * rhs.matrix[0][2] + matrix[2][1] * rhs.matrix[1][2] + matrix[2][2] * rhs.matrix[2][2]; + + return resultMatrix; +} + +FloatMatrix3 +FloatMatrix3::operator *(float value) const +{ + FloatMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] *= value; + resultMatrix.matrix[0][1] *= value; + resultMatrix.matrix[0][2] *= value; + + resultMatrix.matrix[1][0] *= value; + resultMatrix.matrix[1][1] *= value; + resultMatrix.matrix[1][2] *= value; + + resultMatrix.matrix[2][0] *= value; + resultMatrix.matrix[2][1] *= value; + resultMatrix.matrix[2][2] *= value; + + return resultMatrix; +} + +FloatMatrix3 +FloatMatrix3::operator +(const FloatMatrix3& rhs) const +{ + FloatMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] += rhs.matrix[0][0]; + resultMatrix.matrix[0][1] += rhs.matrix[0][1]; + resultMatrix.matrix[0][2] += rhs.matrix[0][2]; + + resultMatrix.matrix[1][0] += rhs.matrix[1][0]; + resultMatrix.matrix[1][1] += rhs.matrix[1][1]; + resultMatrix.matrix[1][2] += rhs.matrix[1][2]; + + resultMatrix.matrix[2][0] += rhs.matrix[2][0]; + resultMatrix.matrix[2][1] += rhs.matrix[2][1]; + resultMatrix.matrix[2][2] += rhs.matrix[2][2]; + + return resultMatrix; +} + +FloatMatrix3 +FloatMatrix3::operator +(float value) const +{ + FloatMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] += value; + resultMatrix.matrix[0][1] += value; + resultMatrix.matrix[0][2] += value; + + resultMatrix.matrix[1][0] += value; + resultMatrix.matrix[1][1] += value; + resultMatrix.matrix[1][2] += value; + + resultMatrix.matrix[2][0] += value; + resultMatrix.matrix[2][1] += value; + resultMatrix.matrix[2][2] += value; + + return resultMatrix; +} + +FloatMatrix3 +FloatMatrix3::operator -(const FloatMatrix3& rhs) const +{ + FloatMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] -= rhs.matrix[0][0]; + resultMatrix.matrix[0][1] -= rhs.matrix[0][1]; + resultMatrix.matrix[0][2] -= rhs.matrix[0][2]; + + resultMatrix.matrix[1][0] -= rhs.matrix[1][0]; + resultMatrix.matrix[1][1] -= rhs.matrix[1][1]; + resultMatrix.matrix[1][2] -= rhs.matrix[1][2]; + + resultMatrix.matrix[2][0] -= rhs.matrix[2][0]; + resultMatrix.matrix[2][1] -= rhs.matrix[2][1]; + resultMatrix.matrix[2][2] -= rhs.matrix[2][2]; + + return resultMatrix; +} + +FloatMatrix3 +FloatMatrix3::operator -(float value) const +{ + FloatMatrix3 resultMatrix(matrix); + + resultMatrix.matrix[0][0] -= value; + resultMatrix.matrix[0][1] -= value; + resultMatrix.matrix[0][2] -= value; + + resultMatrix.matrix[1][0] -= value; + resultMatrix.matrix[1][1] -= value; + resultMatrix.matrix[1][2] -= value; + + resultMatrix.matrix[2][0] -= value; + resultMatrix.matrix[2][1] -= value; + resultMatrix.matrix[2][2] -= value; + + return resultMatrix; +} + +FloatMatrix3& +FloatMatrix3::operator *=(const FloatMatrix3& rhs) +{ + *this = *this * rhs; + return *this; +} + +FloatMatrix3& +FloatMatrix3::operator *=(float value) +{ + *this = *this * value; + return *this; +} + +FloatMatrix3& +FloatMatrix3::operator +=(const FloatMatrix3& rhs) +{ + *this = *this + rhs; + return *this; +} + +FloatMatrix3& +FloatMatrix3::operator +=(float value) +{ + *this = *this + value; + return *this; +} + +FloatMatrix3& +FloatMatrix3::operator -=(const FloatMatrix3& rhs) +{ + *this = *this - rhs; + return *this; +} + +FloatMatrix3& +FloatMatrix3::operator -=(float value) +{ + *this = *this - value; + return *this; +} + +FloatMatrix3 +operator +(const float& value, const FloatMatrix3& rhs) +{ + return rhs + value; +} + +FloatMatrix3 +operator *(const float& value, const FloatMatrix3& rhs) +{ + return rhs * value; +} + +FloatMatrix3 +operator -(const float& value, const FloatMatrix3& rhs) +{ + FloatMatrix3 returnMatrix(rhs); + returnMatrix.Negate(); + returnMatrix += value; + return returnMatrix; +} + +bool +FloatMatrix3::Equals(const Tizen::Base::Object& obj) const +{ + const FloatMatrix3* pMatrix = dynamic_cast (&obj); + + if (pMatrix == null) + { + return false; + } + + return (*this == *pMatrix); +} + +int +FloatMatrix3::GetHashCode(void) const +{ + return (Tizen::Base::Float::GetHashCode(this->matrix[0][0]) + Tizen::Base::Float::GetHashCode(this->matrix[1][0]) + + Tizen::Base::Float::GetHashCode(this->matrix[2][0]) + Tizen::Base::Float::GetHashCode(this->matrix[0][1]) + + Tizen::Base::Float::GetHashCode(this->matrix[1][1]) + Tizen::Base::Float::GetHashCode(this->matrix[2][1]) + + Tizen::Base::Float::GetHashCode(this->matrix[0][2]) + Tizen::Base::Float::GetHashCode(this->matrix[1][2]) + + Tizen::Base::Float::GetHashCode(this->matrix[2][2])); +} + +float +FloatMatrix3::GetDeterminant(void) const +{ + float a0 = matrix[1][1] * matrix[2][2] - matrix[2][1] * matrix[1][2]; + float a1 = matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]; + float a2 = matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]; + + return matrix[0][0] * a0 - matrix[0][1] * a1 + matrix[0][2] * a2; +} + +FloatMatrix3 +FloatMatrix3::GetInverse(void) const +{ + float a0 = matrix[1][1] * matrix[2][2] - matrix[2][1] * matrix[1][2]; + float a1 = matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]; + float a2 = matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]; + + float determinant = matrix[0][0] * a0 - matrix[0][1] * a1 + matrix[0][2] * a2; + + if (Tizen::Base::Float::Compare(determinant, 0.0f) == 0) + { + return *this; + } + + float inverseMatrix[3][3]; + + inverseMatrix[0][0] = (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1]) / determinant; + inverseMatrix[1][0] = (-matrix[1][0] * matrix[2][2] + matrix[1][2] * matrix[2][0]) / determinant; + inverseMatrix[2][0] = (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]) / determinant; + + inverseMatrix[0][1] = (-matrix[0][1] * matrix[2][2] + matrix[0][2] * matrix[2][1]) / determinant; + inverseMatrix[1][1] = (matrix[0][0] * matrix[2][2] - matrix[0][2] * matrix[2][0]) / determinant; + inverseMatrix[2][1] = (-matrix[0][0] * matrix[2][1] + matrix[0][1] * matrix[2][0]) / determinant; + + inverseMatrix[0][2] = (matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]) / determinant; + inverseMatrix[1][2] = (-matrix[0][0] * matrix[1][2] + matrix[0][2] * matrix[1][0]) / determinant; + inverseMatrix[2][2] = (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]) / determinant; + + return FloatMatrix3(inverseMatrix); +} + +float +FloatMatrix3::GetTrace(void) const +{ + return matrix[0][0] + matrix[1][1] + matrix[2][2]; +} + +FloatMatrix3 +FloatMatrix3::GetTranspose(void) const +{ + FloatMatrix3 transposeMatrix(matrix); + transposeMatrix.Transpose(); + + return transposeMatrix; +} + +bool +FloatMatrix3::IsIdentity(void) const +{ + if ((Tizen::Base::Float::Compare(matrix[0][0], 1.0f) != 0) || (Tizen::Base::Float::Compare(matrix[1][1], 1.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[2][2], 1.0f) != 0)) + { + return false; + } + + if ((Tizen::Base::Float::Compare(matrix[0][1], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[0][2], 0.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[1][0], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[1][2], 0.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[2][0], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[2][1], 0.0f) != 0)) + { + return false; + } + + return true; +} + +bool +FloatMatrix3::IsInvertible(void) const +{ + if (Tizen::Base::Float::Compare(GetDeterminant(), 0.0f) == 0) + { + return false; + } + + return true; +} + +void +FloatMatrix3::Negate(void) +{ + matrix[0][0] = -matrix[0][0]; + matrix[0][1] = -matrix[0][1]; + matrix[0][2] = -matrix[0][2]; + + matrix[1][0] = -matrix[1][0]; + matrix[1][1] = -matrix[1][1]; + matrix[1][2] = -matrix[1][2]; + + matrix[2][0] = -matrix[2][0]; + matrix[2][1] = -matrix[2][1]; + matrix[2][2] = -matrix[2][2]; +} + +void +FloatMatrix3::SetAsIdentity(void) +{ + matrix[0][0] = 1.0f; + matrix[0][1] = 0.0f; + matrix[0][2] = 0.0f; + + matrix[1][0] = 0.0f; + matrix[1][1] = 1.0f; + matrix[1][2] = 0.0f; + + matrix[2][0] = 0.0f; + matrix[2][1] = 0.0f; + matrix[2][2] = 1.0f; +} + +result +FloatMatrix3::Invert(void) +{ + float a0 = matrix[1][1] * matrix[2][2] - matrix[2][1] * matrix[1][2]; + float a1 = matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0]; + float a2 = matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]; + + float determinant = matrix[0][0] * a0 - matrix[0][1] * a1 + matrix[0][2] * a2; + + SysTryReturnResult(NID_BASE, Tizen::Base::Float::Compare(determinant, 0.0f) != 0, E_INVALID_OPERATION, + "The current instance is not invertible."); + + float inverseMatrix[3][3]; + + inverseMatrix[0][0] = (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1]) / determinant; + inverseMatrix[1][0] = (-matrix[1][0] * matrix[2][2] + matrix[1][2] * matrix[2][0]) / determinant; + inverseMatrix[2][0] = (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]) / determinant; + + inverseMatrix[0][1] = (-matrix[0][1] * matrix[2][2] + matrix[0][2] * matrix[2][1]) / determinant; + inverseMatrix[1][1] = (matrix[0][0] * matrix[2][2] - matrix[0][2] * matrix[2][0]) / determinant; + inverseMatrix[2][1] = (-matrix[0][0] * matrix[2][1] + matrix[0][1] * matrix[2][0]) / determinant; + + inverseMatrix[0][2] = (matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]) / determinant; + inverseMatrix[1][2] = (-matrix[0][0] * matrix[1][2] + matrix[0][2] * matrix[1][0]) / determinant; + inverseMatrix[2][2] = (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]) / determinant; + + memcpy(matrix, inverseMatrix, MATRIX_SIZE); + + return E_SUCCESS; +} + +void +FloatMatrix3::Transpose(void) +{ + float tmp = 0.0f; + SWAP_VALUES(matrix[0][1], matrix[1][0], tmp); + SWAP_VALUES(matrix[0][2], matrix[2][0], tmp); + + SWAP_VALUES(matrix[1][2], matrix[2][1], tmp); +} + +void +FloatMatrix3::SetAsNull(void) +{ + matrix[0][0] = 0.0f; + matrix[0][1] = 0.0f; + matrix[0][2] = 0.0f; + + matrix[1][0] = 0.0f; + matrix[1][1] = 0.0f; + matrix[1][2] = 0.0f; + + matrix[2][0] = 0.0f; + matrix[2][1] = 0.0f; + matrix[2][2] = 0.0f; +} + +}} // Tizen::Base diff --git a/src/base/FBaseFloatMatrix4.cpp b/src/base/FBaseFloatMatrix4.cpp new file mode 100644 index 0000000..f9a1f6b --- /dev/null +++ b/src/base/FBaseFloatMatrix4.cpp @@ -0,0 +1,634 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseFloatMatrix4.cpp + * @brief This is the implementation for FloatMatrix class. + */ + +#include +#include + +namespace Tizen { namespace Base +{ + +static const int MATRIX_SIZE = sizeof(float) * 16; +#define SWAP_VALUES(a, b, tmp) \ + tmp = a; \ + a = b; \ + b = tmp; + +FloatMatrix4::FloatMatrix4(void) + : __pImpl(null) +{ + SetAsNull(); +} + +FloatMatrix4::FloatMatrix4(const FloatMatrix4& rhs) + : __pImpl(null) +{ + memcpy(matrix, rhs.matrix, MATRIX_SIZE); +} + +FloatMatrix4::FloatMatrix4(const float matrix[4][4]) + : __pImpl(null) +{ + memcpy(this->matrix, matrix, MATRIX_SIZE); +} + +FloatMatrix4::~FloatMatrix4(void) +{ +} + +bool +FloatMatrix4::operator ==(const FloatMatrix4& rhs) const +{ + if (this == &rhs) + { + return true; + } + + return (matrix[0][0] == rhs.matrix[0][0] && + matrix[0][1] == rhs.matrix[0][1] && + matrix[0][2] == rhs.matrix[0][2] && + matrix[0][3] == rhs.matrix[0][3] && + matrix[1][0] == rhs.matrix[1][0] && + matrix[1][1] == rhs.matrix[1][1] && + matrix[1][2] == rhs.matrix[1][2] && + matrix[1][3] == rhs.matrix[1][3] && + matrix[2][0] == rhs.matrix[2][0] && + matrix[2][1] == rhs.matrix[2][1] && + matrix[2][2] == rhs.matrix[2][2] && + matrix[2][3] == rhs.matrix[2][3] && + matrix[3][0] == rhs.matrix[3][0] && + matrix[3][1] == rhs.matrix[3][1] && + matrix[3][2] == rhs.matrix[3][2] && + matrix[3][3] == rhs.matrix[3][3]); +} + +bool +FloatMatrix4::operator !=(const FloatMatrix4& rhs) const +{ + return !(*this == rhs); +} + +FloatMatrix4& +FloatMatrix4::operator =(const FloatMatrix4& rhs) +{ + if (this != &rhs) + { + memcpy(matrix, rhs.matrix, MATRIX_SIZE); + } + + return *this; +} + +FloatMatrix4& +FloatMatrix4::operator =(float value) +{ + matrix[0][0] = value; + matrix[1][0] = value; + matrix[2][0] = value; + matrix[3][0] = value; + + matrix[0][1] = value; + matrix[1][1] = value; + matrix[2][1] = value; + matrix[3][1] = value; + + matrix[0][2] = value; + matrix[1][2] = value; + matrix[2][2] = value; + matrix[3][2] = value; + + matrix[0][3] = value; + matrix[1][3] = value; + matrix[2][3] = value; + matrix[3][3] = value; + + return *this; +} + +FloatMatrix4 +FloatMatrix4::operator *(const FloatMatrix4& rhs) const // need to check performance +{ + FloatMatrix4 resultMatrix; + + resultMatrix.matrix[0][0] = matrix[0][0] * rhs.matrix[0][0] + matrix[0][1] * rhs.matrix[1][0] + matrix[0][2] * rhs.matrix[2][0] + matrix[0][3] * rhs.matrix[3][0]; + resultMatrix.matrix[0][1] = matrix[0][0] * rhs.matrix[0][1] + matrix[0][1] * rhs.matrix[1][1] + matrix[0][2] * rhs.matrix[2][1] + matrix[0][3] * rhs.matrix[3][1]; + resultMatrix.matrix[0][2] = matrix[0][0] * rhs.matrix[0][2] + matrix[0][1] * rhs.matrix[1][2] + matrix[0][2] * rhs.matrix[2][2] + matrix[0][3] * rhs.matrix[3][2]; + resultMatrix.matrix[0][3] = matrix[0][0] * rhs.matrix[0][3] + matrix[0][1] * rhs.matrix[1][3] + matrix[0][2] * rhs.matrix[2][3] + matrix[0][3] * rhs.matrix[3][3]; + + resultMatrix.matrix[1][0] = matrix[1][0] * rhs.matrix[0][0] + matrix[1][1] * rhs.matrix[1][0] + matrix[1][2] * rhs.matrix[2][0] + matrix[1][3] * rhs.matrix[3][0]; + resultMatrix.matrix[1][1] = matrix[1][0] * rhs.matrix[0][1] + matrix[1][1] * rhs.matrix[1][1] + matrix[1][2] * rhs.matrix[2][1] + matrix[1][3] * rhs.matrix[3][1]; + resultMatrix.matrix[1][2] = matrix[1][0] * rhs.matrix[0][2] + matrix[1][1] * rhs.matrix[1][2] + matrix[1][2] * rhs.matrix[2][2] + matrix[1][3] * rhs.matrix[3][2]; + resultMatrix.matrix[1][3] = matrix[1][0] * rhs.matrix[0][3] + matrix[1][1] * rhs.matrix[1][3] + matrix[1][2] * rhs.matrix[2][3] + matrix[1][3] * rhs.matrix[3][3]; + + resultMatrix.matrix[2][0] = matrix[2][0] * rhs.matrix[0][0] + matrix[2][1] * rhs.matrix[1][0] + matrix[2][2] * rhs.matrix[2][0] + matrix[2][3] * rhs.matrix[3][0]; + resultMatrix.matrix[2][1] = matrix[2][0] * rhs.matrix[0][1] + matrix[2][1] * rhs.matrix[1][1] + matrix[2][2] * rhs.matrix[2][1] + matrix[2][3] * rhs.matrix[3][1]; + resultMatrix.matrix[2][2] = matrix[2][0] * rhs.matrix[0][2] + matrix[2][1] * rhs.matrix[1][2] + matrix[2][2] * rhs.matrix[2][2] + matrix[2][3] * rhs.matrix[3][2]; + resultMatrix.matrix[2][3] = matrix[2][0] * rhs.matrix[0][3] + matrix[2][1] * rhs.matrix[1][3] + matrix[2][2] * rhs.matrix[2][3] + matrix[2][3] * rhs.matrix[3][3]; + + resultMatrix.matrix[3][0] = matrix[3][0] * rhs.matrix[0][0] + matrix[3][1] * rhs.matrix[1][0] + matrix[3][2] * rhs.matrix[2][0] + matrix[3][3] * rhs.matrix[3][0]; + resultMatrix.matrix[3][1] = matrix[3][0] * rhs.matrix[0][1] + matrix[3][1] * rhs.matrix[1][1] + matrix[3][2] * rhs.matrix[2][1] + matrix[3][3] * rhs.matrix[3][1]; + resultMatrix.matrix[3][2] = matrix[3][0] * rhs.matrix[0][2] + matrix[3][1] * rhs.matrix[1][2] + matrix[3][2] * rhs.matrix[2][2] + matrix[3][3] * rhs.matrix[3][2]; + resultMatrix.matrix[3][3] = matrix[3][0] * rhs.matrix[0][3] + matrix[3][1] * rhs.matrix[1][3] + matrix[3][2] * rhs.matrix[2][3] + matrix[3][3] * rhs.matrix[3][3]; + + return resultMatrix; +} + +FloatMatrix4 +FloatMatrix4::operator *(float value) const +{ + FloatMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] *= value; + resultMatrix.matrix[0][1] *= value; + resultMatrix.matrix[0][2] *= value; + resultMatrix.matrix[0][3] *= value; + + resultMatrix.matrix[1][0] *= value; + resultMatrix.matrix[1][1] *= value; + resultMatrix.matrix[1][2] *= value; + resultMatrix.matrix[1][3] *= value; + + resultMatrix.matrix[2][0] *= value; + resultMatrix.matrix[2][1] *= value; + resultMatrix.matrix[2][2] *= value; + resultMatrix.matrix[2][3] *= value; + + resultMatrix.matrix[3][0] *= value; + resultMatrix.matrix[3][1] *= value; + resultMatrix.matrix[3][2] *= value; + resultMatrix.matrix[3][3] *= value; + + return resultMatrix; +} + +FloatMatrix4 +FloatMatrix4::operator +(const FloatMatrix4& rhs) const +{ + FloatMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] += rhs.matrix[0][0]; + resultMatrix.matrix[0][1] += rhs.matrix[0][1]; + resultMatrix.matrix[0][2] += rhs.matrix[0][2]; + resultMatrix.matrix[0][3] += rhs.matrix[0][3]; + + resultMatrix.matrix[1][0] += rhs.matrix[1][0]; + resultMatrix.matrix[1][1] += rhs.matrix[1][1]; + resultMatrix.matrix[1][2] += rhs.matrix[1][2]; + resultMatrix.matrix[1][3] += rhs.matrix[1][3]; + + resultMatrix.matrix[2][0] += rhs.matrix[2][0]; + resultMatrix.matrix[2][1] += rhs.matrix[2][1]; + resultMatrix.matrix[2][2] += rhs.matrix[2][2]; + resultMatrix.matrix[2][3] += rhs.matrix[2][3]; + + resultMatrix.matrix[3][0] += rhs.matrix[3][0]; + resultMatrix.matrix[3][1] += rhs.matrix[3][1]; + resultMatrix.matrix[3][2] += rhs.matrix[3][2]; + resultMatrix.matrix[3][3] += rhs.matrix[3][3]; + + return resultMatrix; +} + +FloatMatrix4 +FloatMatrix4::operator +(float value) const +{ + FloatMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] += value; + resultMatrix.matrix[0][1] += value; + resultMatrix.matrix[0][2] += value; + resultMatrix.matrix[0][3] += value; + + resultMatrix.matrix[1][0] += value; + resultMatrix.matrix[1][1] += value; + resultMatrix.matrix[1][2] += value; + resultMatrix.matrix[1][3] += value; + + resultMatrix.matrix[2][0] += value; + resultMatrix.matrix[2][1] += value; + resultMatrix.matrix[2][2] += value; + resultMatrix.matrix[2][3] += value; + + resultMatrix.matrix[3][0] += value; + resultMatrix.matrix[3][1] += value; + resultMatrix.matrix[3][2] += value; + resultMatrix.matrix[3][3] += value; + + return resultMatrix; +} + +FloatMatrix4 +FloatMatrix4::operator -(const FloatMatrix4& rhs) const +{ + FloatMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] -= rhs.matrix[0][0]; + resultMatrix.matrix[0][1] -= rhs.matrix[0][1]; + resultMatrix.matrix[0][2] -= rhs.matrix[0][2]; + resultMatrix.matrix[0][3] -= rhs.matrix[0][3]; + + resultMatrix.matrix[1][0] -= rhs.matrix[1][0]; + resultMatrix.matrix[1][1] -= rhs.matrix[1][1]; + resultMatrix.matrix[1][2] -= rhs.matrix[1][2]; + resultMatrix.matrix[1][3] -= rhs.matrix[1][3]; + + resultMatrix.matrix[2][0] -= rhs.matrix[2][0]; + resultMatrix.matrix[2][1] -= rhs.matrix[2][1]; + resultMatrix.matrix[2][2] -= rhs.matrix[2][2]; + resultMatrix.matrix[2][3] -= rhs.matrix[2][3]; + + resultMatrix.matrix[3][0] -= rhs.matrix[3][0]; + resultMatrix.matrix[3][1] -= rhs.matrix[3][1]; + resultMatrix.matrix[3][2] -= rhs.matrix[3][2]; + resultMatrix.matrix[3][3] -= rhs.matrix[3][3]; + + return resultMatrix; +} + +FloatMatrix4 +FloatMatrix4::operator -(float value) const +{ + FloatMatrix4 resultMatrix(matrix); + + resultMatrix.matrix[0][0] -= value; + resultMatrix.matrix[0][1] -= value; + resultMatrix.matrix[0][2] -= value; + resultMatrix.matrix[0][3] -= value; + + resultMatrix.matrix[1][0] -= value; + resultMatrix.matrix[1][1] -= value; + resultMatrix.matrix[1][2] -= value; + resultMatrix.matrix[1][3] -= value; + + resultMatrix.matrix[2][0] -= value; + resultMatrix.matrix[2][1] -= value; + resultMatrix.matrix[2][2] -= value; + resultMatrix.matrix[2][3] -= value; + + resultMatrix.matrix[3][0] -= value; + resultMatrix.matrix[3][1] -= value; + resultMatrix.matrix[3][2] -= value; + resultMatrix.matrix[3][3] -= value; + + return resultMatrix; +} + +FloatMatrix4& +FloatMatrix4::operator *=(const FloatMatrix4& rhs) +{ + *this = *this * rhs; + return *this; +} + +FloatMatrix4& +FloatMatrix4::operator *=(float value) +{ + *this = *this * value; + return *this; +} + +FloatMatrix4& +FloatMatrix4::operator +=(const FloatMatrix4& rhs) +{ + *this = *this + rhs; + return *this; +} + +FloatMatrix4& +FloatMatrix4::operator +=(float value) +{ + *this = *this + value; + return *this; +} + +FloatMatrix4& +FloatMatrix4::operator -=(const FloatMatrix4& rhs) +{ + *this = *this - rhs; + return *this; +} + +FloatMatrix4& +FloatMatrix4::operator -=(float value) +{ + *this = *this - value; + return *this; +} + +FloatMatrix4 +operator +(const float& value, const FloatMatrix4& rhs) +{ + return rhs + value; +} + +FloatMatrix4 +operator *(const float& value, const FloatMatrix4& rhs) +{ + return rhs * value; +} + +FloatMatrix4 +operator -(const float& value, const FloatMatrix4& rhs) +{ + FloatMatrix4 returnMatrix(rhs); + returnMatrix.Negate(); + returnMatrix += value; + return returnMatrix; +} + +bool +FloatMatrix4::Equals(const Tizen::Base::Object& obj) const +{ + const FloatMatrix4* pMatrix = dynamic_cast (&obj); + + if (pMatrix == null) + { + return false; + } + + return (*this == *pMatrix); +} + +int +FloatMatrix4::GetHashCode(void) const +{ + return (Tizen::Base::Float::GetHashCode(matrix[0][0]) + Tizen::Base::Float::GetHashCode(matrix[1][0]) + + Tizen::Base::Float::GetHashCode(matrix[2][0]) + Tizen::Base::Float::GetHashCode(matrix[3][0]) + + Tizen::Base::Float::GetHashCode(matrix[0][1]) + Tizen::Base::Float::GetHashCode(matrix[1][1]) + + Tizen::Base::Float::GetHashCode(matrix[2][1]) + Tizen::Base::Float::GetHashCode(matrix[3][1]) + + Tizen::Base::Float::GetHashCode(matrix[0][2]) + Tizen::Base::Float::GetHashCode(matrix[1][2]) + + Tizen::Base::Float::GetHashCode(matrix[2][2]) + Tizen::Base::Float::GetHashCode(matrix[3][2]) + + Tizen::Base::Float::GetHashCode(matrix[0][3]) + Tizen::Base::Float::GetHashCode(matrix[1][3]) + + Tizen::Base::Float::GetHashCode(matrix[2][3]) + Tizen::Base::Float::GetHashCode(matrix[3][3])); +} + +float +FloatMatrix4::GetDeterminant(void) const +{ + float a0 = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; + float a1 = matrix[0][0] * matrix[1][2] - matrix[0][2] * matrix[1][0]; + float a2 = matrix[0][0] * matrix[1][3] - matrix[0][3] * matrix[1][0]; + float a3 = matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]; + float a4 = matrix[0][1] * matrix[1][3] - matrix[0][3] * matrix[1][1]; + float a5 = matrix[0][2] * matrix[1][3] - matrix[0][3] * matrix[1][2]; + + float b0 = matrix[2][0] * matrix[3][1] - matrix[2][1] * matrix[3][0]; + float b1 = matrix[2][0] * matrix[3][2] - matrix[2][2] * matrix[3][0]; + float b2 = matrix[2][0] * matrix[3][3] - matrix[2][3] * matrix[3][0]; + float b3 = matrix[2][1] * matrix[3][2] - matrix[2][2] * matrix[3][1]; + float b4 = matrix[2][1] * matrix[3][3] - matrix[2][3] * matrix[3][1]; + float b5 = matrix[2][2] * matrix[3][3] - matrix[2][3] * matrix[3][2]; + + return a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; +} + +FloatMatrix4 +FloatMatrix4::GetInverse(void) const +{ + float a0 = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; + float a1 = matrix[0][0] * matrix[1][2] - matrix[0][2] * matrix[1][0]; + float a2 = matrix[0][0] * matrix[1][3] - matrix[0][3] * matrix[1][0]; + float a3 = matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]; + float a4 = matrix[0][1] * matrix[1][3] - matrix[0][3] * matrix[1][1]; + float a5 = matrix[0][2] * matrix[1][3] - matrix[0][3] * matrix[1][2]; + + float b0 = matrix[2][0] * matrix[3][1] - matrix[2][1] * matrix[3][0]; + float b1 = matrix[2][0] * matrix[3][2] - matrix[2][2] * matrix[3][0]; + float b2 = matrix[2][0] * matrix[3][3] - matrix[2][3] * matrix[3][0]; + float b3 = matrix[2][1] * matrix[3][2] - matrix[2][2] * matrix[3][1]; + float b4 = matrix[2][1] * matrix[3][3] - matrix[2][3] * matrix[3][1]; + float b5 = matrix[2][2] * matrix[3][3] - matrix[2][3] * matrix[3][2]; + + float determinant = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; + + if (Tizen::Base::Float::Compare(determinant, 0.0f) == 0) + { + return *this; + } + + float inverseMatrix[4][4]; + + inverseMatrix[0][0] = (matrix[1][1] * b5 - matrix[1][2] * b4 + matrix[1][3] * b3) / determinant; + inverseMatrix[1][0] = (-matrix[1][0] * b5 + matrix[1][2] * b2 - matrix[1][3] * b1) / determinant; + inverseMatrix[2][0] = (matrix[1][0] * b4 - matrix[1][1] * b2 + matrix[1][3] * b0) / determinant; + inverseMatrix[3][0] = (-matrix[1][0] * b3 + matrix[1][1] * b1 - matrix[1][2] * b0) / determinant; + + inverseMatrix[0][1] = (-matrix[0][1] * b5 + matrix[0][2] * b4 - matrix[0][3] * b3) / determinant; + inverseMatrix[1][1] = (matrix[0][0] * b5 - matrix[0][2] * b2 + matrix[0][3] * b1) / determinant; + inverseMatrix[2][1] = (-matrix[0][0] * b4 + matrix[0][1] * b2 - matrix[0][3] * b0) / determinant; + inverseMatrix[3][1] = (matrix[0][0] * b3 - matrix[0][1] * b1 + matrix[0][2] * b0) / determinant; + + inverseMatrix[0][2] = (matrix[3][1] * a5 - matrix[3][2] * a4 + matrix[3][3] * a3) / determinant; + inverseMatrix[1][2] = (-matrix[3][0] * a5 + matrix[3][2] * a2 - matrix[3][3] * a1) / determinant; + inverseMatrix[2][2] = (matrix[3][0] * a4 - matrix[3][1] * a2 + matrix[3][3] * a0) / determinant; + inverseMatrix[3][2] = (-matrix[3][0] * a3 + matrix[3][1] * a1 - matrix[3][2] * a0) / determinant; + + inverseMatrix[0][3] = (-matrix[2][1] * a5 + matrix[2][2] * a4 - matrix[2][3] * a3) / determinant; + inverseMatrix[1][3] = (matrix[2][0] * a5 - matrix[2][2] * a2 + matrix[2][3] * a1) / determinant; + inverseMatrix[2][3] = (-matrix[2][0] * a4 + matrix[2][1] * a2 - matrix[2][3] * a0) / determinant; + inverseMatrix[3][3] = (matrix[2][0] * a3 - matrix[2][1] * a1 + matrix[2][2] * a0) / determinant; + + return FloatMatrix4(inverseMatrix); +} + +float +FloatMatrix4::GetTrace(void) const +{ + return matrix[0][0] + matrix[1][1] + matrix[2][2] + matrix[3][3]; +} + +FloatMatrix4 +FloatMatrix4::GetTranspose(void) const +{ + FloatMatrix4 transposeMatrix(matrix); + transposeMatrix.Transpose(); + + return transposeMatrix; +} + +bool +FloatMatrix4::IsIdentity(void) const +{ + if ((Tizen::Base::Float::Compare(matrix[0][0], 1.0f) != 0) || (Tizen::Base::Float::Compare(matrix[1][1], 1.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[2][2], 1.0f) != 0) || (Tizen::Base::Float::Compare(matrix[3][3], 1.0f) != 0)) + { + return false; + } + + if ((Tizen::Base::Float::Compare(matrix[0][1], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[0][2], 0.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[0][3], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[1][0], 0.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[1][2], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[1][3], 0.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[2][0], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[2][1], 0.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[2][3], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[3][0], 0.0f) != 0) || + (Tizen::Base::Float::Compare(matrix[3][1], 0.0f) != 0) || (Tizen::Base::Float::Compare(matrix[3][2], 0.0f) != 0)) + { + return false; + } + + return true; +} + +bool +FloatMatrix4::IsInvertible(void) const +{ + if (Tizen::Base::Float::Compare(GetDeterminant(), 0.0f) == 0) + { + return false; + } + + return true; +} + +void +FloatMatrix4::Negate(void) +{ + matrix[0][0] = -matrix[0][0]; + matrix[0][1] = -matrix[0][1]; + matrix[0][2] = -matrix[0][2]; + matrix[0][3] = -matrix[0][3]; + + matrix[1][0] = -matrix[1][0]; + matrix[1][1] = -matrix[1][1]; + matrix[1][2] = -matrix[1][2]; + matrix[1][3] = -matrix[1][3]; + + matrix[2][0] = -matrix[2][0]; + matrix[2][1] = -matrix[2][1]; + matrix[2][2] = -matrix[2][2]; + matrix[2][3] = -matrix[2][3]; + + matrix[3][0] = -matrix[3][0]; + matrix[3][1] = -matrix[3][1]; + matrix[3][2] = -matrix[3][2]; + matrix[3][3] = -matrix[3][3]; +} + +void +FloatMatrix4::SetAsIdentity(void) +{ + matrix[0][0] = 1.0f; + matrix[0][1] = 0.0f; + matrix[0][2] = 0.0f; + matrix[0][3] = 0.0f; + + matrix[1][0] = 0.0f; + matrix[1][1] = 1.0f; + matrix[1][2] = 0.0f; + matrix[1][3] = 0.0f; + + matrix[2][0] = 0.0f; + matrix[2][1] = 0.0f; + matrix[2][2] = 1.0f; + matrix[2][3] = 0.0f; + + matrix[3][0] = 0.0f; + matrix[3][1] = 0.0f; + matrix[3][2] = 0.0f; + matrix[3][3] = 1.0f; +} + +result +FloatMatrix4::Invert(void) +{ + float a0 = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; + float a1 = matrix[0][0] * matrix[1][2] - matrix[0][2] * matrix[1][0]; + float a2 = matrix[0][0] * matrix[1][3] - matrix[0][3] * matrix[1][0]; + float a3 = matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1]; + float a4 = matrix[0][1] * matrix[1][3] - matrix[0][3] * matrix[1][1]; + float a5 = matrix[0][2] * matrix[1][3] - matrix[0][3] * matrix[1][2]; + + float b0 = matrix[2][0] * matrix[3][1] - matrix[2][1] * matrix[3][0]; + float b1 = matrix[2][0] * matrix[3][2] - matrix[2][2] * matrix[3][0]; + float b2 = matrix[2][0] * matrix[3][3] - matrix[2][3] * matrix[3][0]; + float b3 = matrix[2][1] * matrix[3][2] - matrix[2][2] * matrix[3][1]; + float b4 = matrix[2][1] * matrix[3][3] - matrix[2][3] * matrix[3][1]; + float b5 = matrix[2][2] * matrix[3][3] - matrix[2][3] * matrix[3][2]; + + float determinant = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; + + SysTryReturnResult(NID_BASE, Tizen::Base::Float::Compare(determinant, 0.0f) != 0, E_INVALID_OPERATION, "The current instance is not invertible."); + + float inverseMatrix[4][4]; + + inverseMatrix[0][0] = (matrix[1][1] * b5 - matrix[1][2] * b4 + matrix[1][3] * b3) / determinant; + inverseMatrix[1][0] = (-matrix[1][0] * b5 + matrix[1][2] * b2 - matrix[1][3] * b1) / determinant; + inverseMatrix[2][0] = (matrix[1][0] * b4 - matrix[1][1] * b2 + matrix[1][3] * b0) / determinant; + inverseMatrix[3][0] = (-matrix[1][0] * b3 + matrix[1][1] * b1 - matrix[1][2] * b0) / determinant; + + inverseMatrix[0][1] = (-matrix[0][1] * b5 + matrix[0][2] * b4 - matrix[0][3] * b3) / determinant; + inverseMatrix[1][1] = (matrix[0][0] * b5 - matrix[0][2] * b2 + matrix[0][3] * b1) / determinant; + inverseMatrix[2][1] = (-matrix[0][0] * b4 + matrix[0][1] * b2 - matrix[0][3] * b0) / determinant; + inverseMatrix[3][1] = (matrix[0][0] * b3 - matrix[0][1] * b1 + matrix[0][2] * b0) / determinant; + + inverseMatrix[0][2] = (matrix[3][1] * a5 - matrix[3][2] * a4 + matrix[3][3] * a3) / determinant; + inverseMatrix[1][2] = (-matrix[3][0] * a5 + matrix[3][2] * a2 - matrix[3][3] * a1) / determinant; + inverseMatrix[2][2] = (matrix[3][0] * a4 - matrix[3][1] * a2 + matrix[3][3] * a0) / determinant; + inverseMatrix[3][2] = (-matrix[3][0] * a3 + matrix[3][1] * a1 - matrix[3][2] * a0) / determinant; + + inverseMatrix[0][3] = (-matrix[2][1] * a5 + matrix[2][2] * a4 - matrix[2][3] * a3) / determinant; + inverseMatrix[1][3] = (matrix[2][0] * a5 - matrix[2][2] * a2 + matrix[2][3] * a1) / determinant; + inverseMatrix[2][3] = (-matrix[2][0] * a4 + matrix[2][1] * a2 - matrix[2][3] * a0) / determinant; + inverseMatrix[3][3] = (matrix[2][0] * a3 - matrix[2][1] * a1 + matrix[2][2] * a0) / determinant; + + memcpy(matrix, inverseMatrix, MATRIX_SIZE); + + return E_SUCCESS; +} + +void +FloatMatrix4::Transpose(void) +{ + float tmp = 0.0f; + SWAP_VALUES(matrix[0][1], matrix[1][0], tmp); + SWAP_VALUES(matrix[0][2], matrix[2][0], tmp); + SWAP_VALUES(matrix[0][3], matrix[3][0], tmp); + + SWAP_VALUES(matrix[1][2], matrix[2][1], tmp); + SWAP_VALUES(matrix[1][3], matrix[3][1], tmp); + + SWAP_VALUES(matrix[2][3], matrix[3][2], tmp); +} + +void +FloatMatrix4::SetAsNull(void) +{ + matrix[0][0] = 0.0f; + matrix[0][1] = 0.0f; + matrix[0][2] = 0.0f; + matrix[0][3] = 0.0f; + + matrix[1][0] = 0.0f; + matrix[1][1] = 0.0f; + matrix[1][2] = 0.0f; + matrix[1][3] = 0.0f; + + matrix[2][0] = 0.0f; + matrix[2][1] = 0.0f; + matrix[2][2] = 0.0f; + matrix[2][3] = 0.0f; + + matrix[3][0] = 0.0f; + matrix[3][1] = 0.0f; + matrix[3][2] = 0.0f; + matrix[3][3] = 0.0f; +} + +}} // Tizen::Base diff --git a/src/base/FBaseInit.cpp b/src/base/FBaseInit.cpp new file mode 100644 index 0000000..527d1aa --- /dev/null +++ b/src/base/FBaseInit.cpp @@ -0,0 +1,61 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseInit.cpp + */ + +#include "FBaseRt_ThreadManager.h" + +//#include "FBaseResourceTracker.h" + +//Tizen::Base::__ResourceTracker* __gpResourceTracker = null; + + +void +BaseInit(void) +{ +// __gpResourceTracker = new Tizen::Base::__ResourceTracker(); +// __gpResourceTracker->Construct(); +} + +void +BaseFinalize(void) +{ +// if (__gpResourceTracker) +// delete __gpResourceTracker; +} + +extern "C" +{ + + +void +FBase_Initialize(void) +{ + Tizen::Base::Runtime::_ThreadManager::Initialize(); +} + + +void +FBase_Finalize(void) +{ + Tizen::Base::Runtime::_ThreadManager::Finalize(); +} + + +} diff --git a/src/base/FBaseInt8.cpp b/src/base/FBaseInt8.cpp new file mode 100644 index 0000000..0d60f01 --- /dev/null +++ b/src/base/FBaseInt8.cpp @@ -0,0 +1,269 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseInt8.cpp + * @brief This is the implementation file for Int8 class. + * @see Number class + */ + +#include +#include +#include +#include +#include +#include +#include + + + +namespace Tizen { namespace Base +{ + +Int8::Int8(char value) + : value((signed char)value) + , __pInt8Impl(null) +{ +} + +Int8::Int8(const Int8& value) + : value(value.value) + , __pInt8Impl(null) +{ +} + +Int8::~Int8(void) +{ +} + +Int8& +Int8::operator =(const Int8& rhs) +{ + if (&rhs != this) + { + value = rhs.value; + } + return (*this); +} + +int +Int8::Compare(char ch1, char ch2) +{ + return ((signed char) ch1 < (signed char) ch2 ? -1 : (ch1 == ch2 ? 0 : 1)); +} + +int +Int8::CompareTo(const Int8& value) const +{ + return (Int8::Compare(this->value, value.value)); +} + +bool +Int8::Equals(const Object& obj) const +{ + const Int8* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return (false); + } + + return (value == (*pOther).value); +} + +int +Int8::GetHashCode(void) const +{ + return static_cast (value); +} + +int +Int8::GetHashCode(char val) +{ + return static_cast (val); +} + +result +Int8::Decode(const String& s, char& ret) +{ + SysTryReturn(NID_BASE, s.GetLength() >= 1, E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of string s MUST be greater than 0.", GetErrorMessage(E_NUM_FORMAT)); + + long value = 0; + int radix = 0; + wchar_t* pEnd = null; + String str(s); + + // Find radix + if (s[0] == L'#') + { + radix = Character::RADIX_HEXADECIMAL; + + // Remove '#' + str.Remove(0, 1); + } + else if (s[0] == L'0' && (s.GetLength() >= 2)) + { + if (s[1] == L'x' || s[1] == L'X') + { + radix = Character::RADIX_HEXADECIMAL; + } + else + { + radix = Character::RADIX_OCTAL; + } + } + else + { + radix = Character::RADIX_DECIMAL; + } + + result r = E_SUCCESS; + + errno = 0; + value = wcstol(str.GetPointer(), &pEnd, radix); + SysTryCatch(NID_BASE, (pEnd[0] == 0), r = E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Int8 decode failed. Scan stopped at (%ls).", GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryCatch(NID_BASE, !((value == LONG_MAX || value == LONG_MIN) && (errno != 0)), r = E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Decoded value cannot fit into an Int8.", GetErrorMessage(E_NUM_FORMAT)); + +CATCH: + if (value > Int8::VALUE_MAX) + { + ret = Int8::VALUE_MAX; + } + else if (value < (signed char) Int8::VALUE_MIN) + { + ret = (signed char) Int8::VALUE_MIN; + } + else + { + ret = (char) value; + } + + return r; +} + +result +Int8::Parse(const String& s, char& ret) +{ + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0 && len < 5), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of s(%ls) MUST be greater than 0 and less than 5.", GetErrorMessage(E_NUM_FORMAT), s.GetPointer()); + + return Parse(s, Character::RADIX_DECIMAL, ret); +} + +result +Int8::Parse(const String& s, int radix, char& ret) +{ + SysTryReturn(NID_BASE, ((radix == Character::RADIX_BINARY) || (radix == Character::RADIX_OCTAL) || + (radix == Character::RADIX_DECIMAL) || (radix == Character::RADIX_HEXADECIMAL)), E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The radix(%d) MUST be one of 2, 8, 10 and 16.", GetErrorMessage(E_OUT_OF_RANGE), radix); + + wchar_t* pEnd = null; + long value = 0; + + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0), E_NUM_FORMAT, E_NUM_FORMAT, "[%s] The length of s MUST be greater than 0.", + GetErrorMessage(E_NUM_FORMAT)); + + result r = E_SUCCESS; + + errno = 0; + value = wcstol(s.GetPointer(), &pEnd, radix); + SysTryCatch(NID_BASE, (pEnd[0] == 0), r = E_NUM_FORMAT, E_NUM_FORMAT, "[%s] Int8 parse failed. Scan stopped at (%ls).", + GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryCatch(NID_BASE, !((value == LONG_MAX || value == LONG_MIN) && (errno != 0)), r = E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Parsed value cannot fit into an Int8.", GetErrorMessage(E_NUM_FORMAT)); + +CATCH: + if (value > Int8::VALUE_MAX) + { + ret = Int8::VALUE_MAX; + } + else if (value < (signed char) Int8::VALUE_MIN) + { + ret = (signed char) Int8::VALUE_MIN; + } + else + { + ret = (char) value; + } + + return r; +} + +char +Int8::ToChar(void) const +{ + return static_cast (value); +} + +short +Int8::ToShort(void) const +{ + return static_cast (value); +} + +int +Int8::ToInt(void) const +{ + return static_cast (value); +} + +long +Int8::ToLong(void) const +{ + return static_cast (value); +} + +long long +Int8::ToLongLong(void) const +{ + return static_cast (value); +} + +float +Int8::ToFloat(void) const +{ + return static_cast (value); +} + +double +Int8::ToDouble(void) const +{ + return static_cast (value); +} + +String +Int8::ToString(void) const +{ + return (Int8::ToString(value)); +} + +String +Int8::ToString(char value) +{ + const static unsigned int INT8_LENGTH_MAX = 4; + + wchar_t sValue[INT8_LENGTH_MAX + 1] = {0, }; + swprintf(sValue, (sizeof(sValue) / sizeof(sValue[0])), L"%d", value); + + return String(sValue); +} + +}} //Tizen::Base diff --git a/src/base/FBaseInt8Comparer.cpp b/src/base/FBaseInt8Comparer.cpp new file mode 100644 index 0000000..34e7993 --- /dev/null +++ b/src/base/FBaseInt8Comparer.cpp @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseInt8Comparer.cpp + * @brief This is the implementation file for Int8Comparer class. + * @see Int8 and Tizen::Base::Collection::IComparer + */ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +Int8Comparer::Int8Comparer(void) + : __pInt8ComparerImpl(null) +{ +} + +Int8Comparer::~Int8Comparer(void) +{ +} + +result +Int8Comparer::Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const +{ + const Int8* pInteger1 = dynamic_cast (&obj1); + const Int8* pInteger2 = dynamic_cast (&obj2); + + SysTryReturn(NID_BASE, (pInteger1 != null && pInteger2 != null), E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used. Both of the obj1 and obj2 MUST be Integer.", GetErrorMessage(E_INVALID_ARG)); + + cmp = Int8::Compare(pInteger1->ToChar(), pInteger2->ToChar()); + + return E_SUCCESS; +} + +}} //Tizen::Base diff --git a/src/base/FBaseIntMatrix.cpp b/src/base/FBaseIntMatrix.cpp new file mode 100644 index 0000000..681f957 --- /dev/null +++ b/src/base/FBaseIntMatrix.cpp @@ -0,0 +1,873 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseIntMatrix.cpp + * @brief This is the implementation for IntMatrix class. + */ + +#include +#include +#include + +namespace Tizen { namespace Base +{ + +IntMatrix::IntMatrix(void) + : __pImpl(null) + , __pMatrix(null) + , __row(0) + , __column(0) +{ +} + +IntMatrix::IntMatrix(const IntMatrix& rhs) + : __pImpl(null) + , __row(rhs.__row) + , __column(rhs.__column) +{ + AllocateCapacity(__row, __column); + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = rhs.__pMatrix[i][j]; + } + } +} + +IntMatrix::IntMatrix(int rowCount, int columnCount) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + SetAsNull(); +} + +IntMatrix::IntMatrix(int rowCount, int columnCount, const int* pArray, bool rowMajor) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + if (pArray != null) + { + if (rowMajor == true) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i * __row + j]; + } + } + } + else + { + for (int i = 0; i < __column; i++) + { + for (int j = 0; j < __row; j++) + { + __pMatrix[j][i] = pArray[i * __column + j]; + } + } + } + } + else + { + SetAsNull(); + } +} + +IntMatrix::IntMatrix(int rowCount, int columnCount, const int* pArray[]) + : __pImpl(null) + , __row(rowCount) + , __column(columnCount) +{ + AllocateCapacity(__row, __column); + if (pArray != null) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i][j]; + } + } + } + else + { + SetAsIdentity(); + } +} + +IntMatrix::~IntMatrix(void) +{ + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + + delete[] __pMatrix; +} + +bool +IntMatrix::operator ==(const IntMatrix& rhs) const +{ + if (this == &rhs) + { + return true; + } + + if ((__row != rhs.__row) || (__column != rhs.__column)) + { + return false; + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + if (__pMatrix[i][j] != rhs.__pMatrix[i][j]) + { + return false; + } + } + } + + return true; +} + +bool +IntMatrix::operator !=(const IntMatrix& rhs) const +{ + return !(*this == rhs); +} + +IntMatrix& +IntMatrix::operator =(const IntMatrix& rhs) +{ + if (this == &rhs) + { + return *this; + } + + SysTryReturn(NID_BASE, (__row == rhs.__row) && (__column == rhs.__column), *this, E_INVALID_ARG, + "[%s] Invalid argument is used. Either row or column count of the current instance is not same with that of the specified instance.", + GetErrorMessage(E_INVALID_ARG)); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = rhs.__pMatrix[i][j]; + } + } + + return *this; +} + +bool +IntMatrix::Equals(const Tizen::Base::Object& obj) const +{ + const IntMatrix* pOther = dynamic_cast (&obj); + + if (pOther == null) + { + return false; + } + + return (*this == *pOther); +} + +int +IntMatrix::GetHashCode(void) const +{ + int hash = 0; + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + hash = hash + Tizen::Base::Integer(__pMatrix[i][j]).GetHashCode(); + } + } + + return hash; +} + +result +IntMatrix::Add(const IntMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, (__row == matrix.__row) && (__column == matrix.__column), E_INVALID_ARG, + "Either row or column count of the current instance is not same with that of the specified instance."); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] + matrix.__pMatrix[i][j]; + } + } + + return E_SUCCESS; +} + +void +IntMatrix::AddToEachElement(int value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] + value; + } + } +} + +bool +IntMatrix::AllocateCapacity(int rowCount, int columnCount) +{ + std::unique_ptr pMatrix(new (std::nothrow) int* [rowCount]); + SysTryReturn(NID_BASE, pMatrix != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for ( int i = 0 ; i < rowCount ; i++ ) + { + pMatrix[i] = new (std::nothrow) int[columnCount]; + if (pMatrix[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMatrix[j]; + } + return false; + } + } + + __pMatrix = pMatrix.release(); + + return true; +} + +int +IntMatrix::CalculateDeterminant(int** pMatrix, int order) const // For perfomance, we have to change the logic of recursive to LU decomposition. +{ + SysTryReturn(NID_BASE, pMatrix != null, 0, E_INVALID_ARG, "[%s] Invalid argument is used. pMatrix is null.", + GetErrorMessage(E_INVALID_ARG)); + + if (order == 1) + { + return pMatrix[0][0]; + } + + int determinant = 0; + std::unique_ptr pMinor(new (std::nothrow) int* [order - 1]); + SysTryReturn(NID_BASE, pMinor != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + for (int i = 0; i < order -1; i++) + { + pMinor[i] = new (std::nothrow) int[order - 1]; + if (pMinor[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + return determinant; + } + } + + bool signFlag = true; + for (int i = 0; i < order; i++) + { + GetMinor(pMatrix, pMinor.get(), 0, i, order); + + if (signFlag == true) + { + determinant += pMatrix[0][i] * CalculateDeterminant(pMinor.get(), order -1); + signFlag = false; + } + else + { + determinant += -pMatrix[0][i] * CalculateDeterminant(pMinor.get(), order -1); + signFlag = true; + } + } + + for (int i = 0; i < order -1; i++) + { + delete[] pMinor[i]; + } + + return determinant; +} + +int +IntMatrix::GetColumnCount(void) const +{ + return __column; +} + +int* +IntMatrix::GetColumnN(int columnIndex) const +{ + SysTryReturn(NID_BASE, columnIndex <= __column, null, E_INVALID_ARG, + "[%s] Invalid argument is used. The columnIndex is larger than the column count of the current instance.", + GetErrorMessage(E_INVALID_ARG)); + + std::unique_ptr pColumn(new (std::nothrow) int [__row]); + SysTryReturn(NID_BASE, pColumn != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row; i++) + { + pColumn[i] = __pMatrix[i][columnIndex]; + } + + return pColumn.release(); +} + +int +IntMatrix::GetDeterminant(void) const +{ + SysTryReturn(NID_BASE, __row == __column, 0, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + return CalculateDeterminant(__pMatrix, __row); +} + +int +IntMatrix::GetElement(int rowIndex, int columnIndex) const +{ + SysTryReturn(NID_BASE, (rowIndex <= __row) && (columnIndex <= __column), 0, E_INVALID_ARG, + "[%s] Invalid argument is used. The current instance is not a square matrix.", GetErrorMessage(E_INVALID_ARG)); + + return __pMatrix[rowIndex][columnIndex]; +} + +IntMatrix* +IntMatrix::GetInverseN(void) const +{ + SysTryReturn(NID_BASE, __row == __column, null, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + std::unique_ptr pInverseMatrix(new (std::nothrow) IntMatrix(__row, __column)); + SysTryReturn(NID_BASE, pInverseMatrix != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + int determinant = CalculateDeterminant(__pMatrix, __row); + + if (determinant == 0) + { + return null; + } + + std::unique_ptr pMinor(new (std::nothrow) int* [__row - 1]); + SysTryReturn(NID_BASE, pMinor != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row - 1; i++) + { + pMinor[i] = new (std::nothrow) int[__row - 1]; + if (pMinor[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + return null; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __row; j++) + { + GetMinor(__pMatrix, pMinor.get(), i, j, __row); + pInverseMatrix->__pMatrix[j][i] = CalculateDeterminant(pMinor.get(), __row - 1) / determinant; + if ((i + j + 2) % 2 == 1) + { + pInverseMatrix->__pMatrix[j][i] = -pInverseMatrix->__pMatrix[j][i]; + } + } + } + + for ( int i = 0 ; i < __row - 1 ; i++) + { + delete[] pMinor[i]; + } + + return pInverseMatrix.release(); +} + +void +IntMatrix::GetMinor(int** pSrc, int** pDest, int rowIndex, int columnIndex, int order) const +{ + SysTryReturn(NID_BASE, pSrc != null, , E_INVALID_ARG, "[%s] Invalid argument is used. pSrc is null.", + GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_BASE, pDest != null, , E_INVALID_ARG, "[%s] Invalid argument is used. pDest is null.", + GetErrorMessage(E_INVALID_ARG)); + + int rowCount = 0; + int columnCount = 0; + + for (int i = 0; i < order; i++) + { + if (i != rowIndex) + { + columnCount = 0; + + for (int j = 0; j < order; j++) + { + if (j != columnIndex) + { + pDest[rowCount][columnCount] = pSrc[i][j]; + columnCount++; + } + } + rowCount++; + } + } +} + +int +IntMatrix::GetRowCount(void) const +{ + return __row; +} + +int* +IntMatrix::GetRowN(int rowIndex) const +{ + SysTryReturn(NID_BASE, rowIndex <= __row, null, E_INVALID_ARG, + "[%s] Invalid argument is used. The rowIndex is larger than the row count of the current instance.", + GetErrorMessage(E_INVALID_ARG)); + + std::unique_ptr pRow(new (std::nothrow) int [__column]); + SysTryReturn(NID_BASE, pRow != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __column; i++) + { + pRow[i] = __pMatrix[rowIndex][i]; + } + + return pRow.release(); +} + +result +IntMatrix::GetTrace(int& value) const +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + value = 0; + + for (int i = 0; i < __row; i++) + { + value += __pMatrix[i][i]; + } + + return E_SUCCESS; +} + +IntMatrix* +IntMatrix::GetTransposeN(void) const +{ + SysTryReturn(NID_BASE, __row == __column, null, E_INVALID_OPERATION, + "[%s] The current instance is not a square matrix.", GetErrorMessage(E_INVALID_OPERATION)); + + std::unique_ptr pTransposeMatrix(new (std::nothrow) IntMatrix(*this)); + SysTryReturn(NID_BASE, pTransposeMatrix != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + int columnIndex = 1; + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < columnIndex; j++) + { + int temp = pTransposeMatrix->__pMatrix[i][j]; + pTransposeMatrix->__pMatrix[i][j] = pTransposeMatrix->__pMatrix[j][i]; + pTransposeMatrix->__pMatrix[j][i] = temp; + } + + columnIndex++; + } + + return pTransposeMatrix.release(); +} + +bool +IntMatrix::IsIdentity(void) const +{ + if (__row != __column) + { + return false; + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + if (i == j) + { + if (__pMatrix[i][j] != 1) + { + return false; + } + } + else + { + if (__pMatrix[i][j] != 0) + { + return false; + } + } + } + } + return true; +} + +bool +IntMatrix::IsInvertible(void) const +{ + int ret = GetDeterminant(); + + if (ret == 0) + { + return false; + } + else + { + return true; + } +} + +result +IntMatrix::Multiply(const IntMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, __column == matrix.__row, E_INVALID_ARG, + "The column count of the current instance is not same with the row count of the specified instance."); + + std::unique_ptr pResult(new (std::nothrow) int* [__row]); + SysTryReturnResult(NID_BASE, pResult != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + for ( int i = 0 ; i < __row ; i++ ) + { + pResult[i] = new int[matrix.__column]; + if (pResult[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pResult[j]; + } + return E_OUT_OF_MEMORY; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < matrix.__column; j++) + { + pResult[i][j] = 0; + + for (int k = 0; k < __column; k++) + { + pResult[i][j] += __pMatrix[i][k] * matrix.__pMatrix[k][j]; + } + } + } + + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + + delete[] __pMatrix; + + __pMatrix = pResult.release(); + + return E_SUCCESS; +} + +void +IntMatrix::Multiply(int value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] * value; + } + } +} + +void +IntMatrix::Negate(void) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = -__pMatrix[i][j]; + } + } +} + +result +IntMatrix::SetAsIdentity(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + if (i == j) + { + __pMatrix[i][j] = 1; + } + else + { + __pMatrix[i][j] = 0; + } + } + } + + return E_SUCCESS; +} + +result +IntMatrix::Invert(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + int determinant = CalculateDeterminant(__pMatrix, __row); + SysTryReturnResult(NID_BASE, determinant != 0, E_INVALID_OPERATION, "The current instance is not invertible."); + + std::unique_ptr pInverse(new (std::nothrow) int* [__row]); + SysTryReturn(NID_BASE, pInverse != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < __row; i++) + { + pInverse[i] = new (std::nothrow) int[__row]; + if (pInverse[i] == null) + { + for (int j = 0; j < i; j++) + { + delete[] pInverse[j]; + } + return E_OUT_OF_MEMORY; + } + } + + std::unique_ptr pMinor(new (std::nothrow) int* [__row - 1]); + if (pMinor == null) + { + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] pInverse[i]; + } + return E_OUT_OF_MEMORY; + } + + for (int i = 0; i < __row - 1; i++) + { + pMinor[i] = new int[__row - 1]; + if (pMinor[i] == null) + { + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] pInverse[i]; + } + + for (int j = 0; j < i; j++) + { + delete[] pMinor[j]; + } + + return E_OUT_OF_MEMORY; + } + } + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __row; j++) + { + GetMinor(__pMatrix, pMinor.get(), i, j, __row); + pInverse[j][i] = CalculateDeterminant(pMinor.get(), __row - 1) / determinant; + if ((i +j +2) % 2 == 1) + { + pInverse[j][i] = -pInverse[j][i]; + } + } + } + + for ( int i = 0 ; i < __row ; i++ ) + { + delete[] __pMatrix[i]; + } + delete[] __pMatrix; + + __pMatrix = pInverse.release(); + + for ( int i = 0 ; i < __row - 1; i++ ) + { + delete[] pMinor[i]; + } + + return E_SUCCESS; +} + +result +IntMatrix::Transpose(void) +{ + SysTryReturnResult(NID_BASE, __row == __column, E_INVALID_OPERATION, "The current instance is not a square matrix."); + + int columnIndex = 1; + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < columnIndex; j++) + { + int temp = __pMatrix[i][j]; + __pMatrix[i][j] = __pMatrix[j][i]; + __pMatrix[j][i] = temp; + } + + columnIndex++; + } + + return E_SUCCESS; +} + +result +IntMatrix::SetColumn(int columnIndex, const int* pArray) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null."); + SysTryReturnResult(NID_BASE, columnIndex <= __column, E_INVALID_ARG, + "columnIndex is larger than the column count of the current instance."); + + for (int i = 0; i < __row; i++) + { + __pMatrix[i][columnIndex] = pArray[i]; + } + + return E_SUCCESS; +} + +result +IntMatrix::SetRow(int rowIndex, const int* pArray) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null."); + SysTryReturnResult(NID_BASE, rowIndex <= __row, E_INVALID_ARG, + "rowIndex is larger than the row count of the current instance."); + + for (int i = 0; i < __column; i++) + { + __pMatrix[rowIndex][i] = pArray[i]; + } + + return E_SUCCESS; +} + +result +IntMatrix::SetElement(int rowIndex, int columnIndex, int value) +{ + SysTryReturnResult(NID_BASE, columnIndex <= __column, E_INVALID_ARG, + "columnIndex is larger than the column count of the current instance."); + SysTryReturnResult(NID_BASE, rowIndex <= __row, E_INVALID_ARG, + "rowIndex is larger than the row count of the current instance."); + + __pMatrix[rowIndex][columnIndex] = value; + + return E_SUCCESS; +} + +result +IntMatrix::SetValue(const int* pArray, bool rowMajor) +{ + SysTryReturnResult(NID_BASE, pArray != null, E_INVALID_ARG, "pArray is null."); + + if (rowMajor == true) + { + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = pArray[i * __row + j]; + } + } + } + else + { + for (int i = 0; i < __column; i++) + { + for (int j = 0; j < __row; j++) + { + __pMatrix[j][i] = pArray[i * __column + j]; + } + } + } + + return E_SUCCESS; +} + +void +IntMatrix::SetAsNull(void) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = 0; + } + } +} + +result +IntMatrix::Subtract(const IntMatrix& matrix) +{ + SysTryReturnResult(NID_BASE, (__row == matrix.__row) && (__column == matrix.__column), E_INVALID_ARG, + "Either row or column count of the current instance is not same with that of the specified instance."); + + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] - matrix.__pMatrix[i][j]; + } + } + + return E_SUCCESS; +} + +void +IntMatrix::SubtractToEachElement(int value) +{ + for (int i = 0; i < __row; i++) + { + for (int j = 0; j < __column; j++) + { + __pMatrix[i][j] = __pMatrix[i][j] - value; + } + } +} + +}} // Tizen::Base diff --git a/src/base/FBaseInteger.cpp b/src/base/FBaseInteger.cpp new file mode 100644 index 0000000..4db73f0 --- /dev/null +++ b/src/base/FBaseInteger.cpp @@ -0,0 +1,235 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseInteger.cpp + * @brief This is the implementation file for Integer class. + * @see Number + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +Integer::Integer(int value) + : value(value) + , __pIntegerImpl(null) +{ +} + +Integer::Integer(const Integer& value) + : value(value.value) + , __pIntegerImpl(null) +{ +} + +Integer::~Integer(void) +{ + +} + +Integer& +Integer::operator =(const Integer& rhs) +{ + if (&rhs != this) + { + value = rhs.value; + } + return *this; +} + +int +Integer::Compare(int i1, int i2) +{ + return(i1 < i2 ? -1 : (i1 == i2 ? 0 : 1)); +} + +int +Integer::CompareTo(const Integer& value) const +{ + return(Integer::Compare(this->value, value.value)); +} + +bool +Integer::Equals(const Object& obj) const +{ + const Integer* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + return value == (*pOther).value; +} + +result +Integer::Decode(const String& s, int& ret) +{ + SysTryReturn(NID_BASE, s.GetLength() >= 1, E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of s MUST be greater than 0.", GetErrorMessage(E_NUM_FORMAT)); + + int radix = 0; + wchar_t* pEnd = null; + String str(s); + + // Find radix + if (s[0] == L'#') + { + radix = Character::RADIX_HEXADECIMAL; + + // Remove '#' + str.Remove(0, 1); + } + else if (s[0] == L'0' && (s.GetLength() >= 2)) + { + if (s[1] == L'x' || s[1] == L'X') + { + radix = Character::RADIX_HEXADECIMAL; + } + else + { + radix = Character::RADIX_OCTAL; + } + } + else + { + radix = Character::RADIX_DECIMAL; + } + + errno = 0; + ret = wcstol(str.GetPointer(), &pEnd, radix); + SysTryReturn(NID_BASE, (pEnd[0] == 0), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Integer decode failed. Scan stopped at (%ls).", GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryReturn(NID_BASE, !((ret == LONG_MAX || ret == LONG_MIN) && (errno != 0)), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Decoded value cannot fit into an Integer.", GetErrorMessage(E_NUM_FORMAT)); + + return E_SUCCESS; +} + +int +Integer::GetHashCode(void) const +{ + return value; +} + +int +Integer::GetHashCode(int val) +{ + return val; +} + +result +Integer::Parse(const String& s, int& ret) +{ + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0 && len < 12), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of s(%ls) MUST be greater than 0 and less than 12.", + GetErrorMessage(E_NUM_FORMAT), s.GetPointer()); + + return Parse(s, Character::RADIX_DECIMAL, ret); +} + +result +Integer::Parse(const String& s, int radix, int& ret) +{ + SysTryReturn(NID_BASE, ((radix == Character::RADIX_BINARY) || (radix == Character::RADIX_OCTAL) || + (radix == Character::RADIX_DECIMAL) || (radix == Character::RADIX_HEXADECIMAL)), E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The radix(%d) MUST be one of 2, 8, 10 and 16.", GetErrorMessage(E_OUT_OF_RANGE), radix); + + wchar_t* pEnd = null; + + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0), E_NUM_FORMAT, E_NUM_FORMAT, "[%s] The length of s MUST be greater than 0.", + GetErrorMessage(E_NUM_FORMAT)); + + errno = 0; + ret = wcstol(s.GetPointer(), &pEnd, radix); + SysTryReturn(NID_BASE, (pEnd[0] == 0), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Integer parse failed. Scan stopped at (%ls).", GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryReturn(NID_BASE, !((ret == LONG_MAX || ret == LONG_MIN) && (errno != 0)), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Parsed value cannot fit into an Integer.", GetErrorMessage(E_NUM_FORMAT)); + + return E_SUCCESS; +} + +char +Integer::ToChar(void) const +{ + return static_cast (value); +} + +short +Integer::ToShort(void) const +{ + return static_cast (value); +} + +int +Integer::ToInt(void) const +{ + return value; +} + +long +Integer::ToLong(void) const +{ + return static_cast (value); +} + +long long +Integer::ToLongLong(void) const +{ + return static_cast (value); +} + +float +Integer::ToFloat(void) const +{ + return static_cast (value); +} + +double +Integer::ToDouble(void) const +{ + return static_cast (value); +} + +String +Integer::ToString(void) const +{ + return(Integer::ToString(value)); +} + +String +Integer::ToString(int value) +{ + const static unsigned int INTEGER_LENGTH_MAX = 11; + + wchar_t sValue[INTEGER_LENGTH_MAX + 1] = {0, }; + swprintf(sValue, (sizeof(sValue) / sizeof(sValue[0])), L"%d", value); + + return String(sValue); +} + +}} //Tizen::Base diff --git a/src/base/FBaseIntegerComparer.cpp b/src/base/FBaseIntegerComparer.cpp new file mode 100644 index 0000000..b687c73 --- /dev/null +++ b/src/base/FBaseIntegerComparer.cpp @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseIntegerComparer.cpp + * @brief This is the implementation file for IntegerComparer class. + * @see Integer and Tizen::Base::Collection::IComparer + */ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +IntegerComparer::IntegerComparer(void) + : __pIntegerComparerImpl(null) +{ +} + +IntegerComparer::~IntegerComparer(void) +{ +} + +result +IntegerComparer::Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const +{ + const Integer* pInteger1 = dynamic_cast (&obj1); + const Integer* pInteger2 = dynamic_cast (&obj2); + + SysTryReturn(NID_BASE, (pInteger1 != null && pInteger2 != null), E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used. Both of the obj1 and obj2 MUST be Integer.", GetErrorMessage(E_INVALID_ARG)); + + cmp = Integer::Compare(pInteger1->ToInt(), pInteger2->ToInt()); + + return E_SUCCESS; +} + +}} //Tizen::Base diff --git a/src/base/FBaseLong.cpp b/src/base/FBaseLong.cpp new file mode 100644 index 0000000..748bc81 --- /dev/null +++ b/src/base/FBaseLong.cpp @@ -0,0 +1,233 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLong.cpp + * @brief This is the implementation file for Long class. + * @see Number + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +Long::Long(long value) + : value(value) + , __pLongImpl(null) +{ +} + +Long::Long(const Long& value) + : value(value.value) + , __pLongImpl(null) +{ +} + +Long::~Long(void) +{ +} + +Long& +Long::operator =(const Long& rhs) +{ + if (&rhs != this) + { + value = rhs.value; + } + return *this; +} + +int +Long::Compare(long l1, long l2) +{ + return(l1 < l2 ? -1 : (l1 == l2 ? 0 : 1)); +} + +int +Long::CompareTo(const Long& value) const +{ + return(Long::Compare(this->value, value.value)); +} + +bool +Long::Equals(const Object& obj) const +{ + const Long* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + return value == (*pOther).value; +} + +int +Long::GetHashCode(void) const +{ + return static_cast (value); +} + +int +Long::GetHashCode(long val) +{ + return static_cast (val); +} + +result +Long::Decode(const String& s, long& ret) +{ + SysTryReturn(NID_BASE, s.GetLength() >= 1, E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of s MUST be greater than 0.", GetErrorMessage(E_NUM_FORMAT)); + + int radix = 0; + wchar_t* pEnd = null; + String str(s); + + // Find radix + if (s[0] == L'#') + { + radix = Character::RADIX_HEXADECIMAL; + + // Remove '#' + str.Remove(0, 1); + } + else if (s[0] == L'0' && (s.GetLength() >= 2)) + { + if (s[1] == L'x' || s[1] == L'X') + { + radix = Character::RADIX_HEXADECIMAL; + } + else + { + radix = Character::RADIX_OCTAL; + } + } + else + { + radix = Character::RADIX_DECIMAL; + } + + errno = 0; + ret = wcstol(str.GetPointer(), &pEnd, radix); + SysTryReturn(NID_BASE, (pEnd[0] == 0), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Long decode failed. Scan stopped at (%ls).", GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryReturn(NID_BASE, !((ret == LONG_MAX || ret == LONG_MIN) && (errno != 0)), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Decoded value cannot fit into a Long.", GetErrorMessage(E_NUM_FORMAT)); + + return E_SUCCESS; +} + +result +Long::Parse(const String& s, long& ret) +{ + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0 && len < 12), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of s(%ls) MUST be greater than 0 and less than 12.", GetErrorMessage(E_NUM_FORMAT), s.GetPointer()); + + return Parse(s, Character::RADIX_DECIMAL, ret); +} + +result +Long::Parse(const String& s, int radix, long& ret) +{ + SysTryReturn(NID_BASE, ((radix == Character::RADIX_BINARY) || (radix == Character::RADIX_OCTAL) || + (radix == Character::RADIX_DECIMAL) || (radix == Character::RADIX_HEXADECIMAL)), E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The radix(%d) MUST be one of 2, 8, 10 and 16.", GetErrorMessage(E_OUT_OF_RANGE), radix); + + wchar_t* pEnd = null; + + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0), E_NUM_FORMAT, E_NUM_FORMAT, "[%s] The length of s MUST be greater than 0.", + GetErrorMessage(E_NUM_FORMAT)); + + errno = 0; + ret = wcstol(s.GetPointer(), &pEnd, radix); + SysTryReturn(NID_BASE, (pEnd[0] == 0), E_NUM_FORMAT, E_NUM_FORMAT, "[%s] Long parse failed. Scan stopped at (%ls).", + GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryReturn(NID_BASE, !((ret == LONG_MAX || ret == LONG_MIN) && (errno != 0)), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Parsed value cannot fit into a Long.", GetErrorMessage(E_NUM_FORMAT)); + + return E_SUCCESS; +} + +char +Long::ToChar(void) const +{ + return static_cast (value); +} + +short +Long::ToShort(void) const +{ + return static_cast (value); +} + +int +Long::ToInt(void) const +{ + return static_cast (value); +} + +long +Long::ToLong(void) const +{ + return value; +} + +long long +Long::ToLongLong(void) const +{ + return static_cast (value); +} + +float +Long::ToFloat(void) const +{ + return static_cast (value); +} + +double +Long::ToDouble(void) const +{ + return static_cast (value); +} + +String +Long::ToString(void) const +{ + return(Long::ToString(value)); +} + +String +Long::ToString(long value) +{ + const static unsigned int LONG_LENGTH_MAX = 11; + + wchar_t sValue[LONG_LENGTH_MAX + 1] = {0, }; + swprintf(sValue, (sizeof(sValue) / sizeof(sValue[0])), L"%d", value); + + return String(sValue); +} + +}} //Tizen::Base diff --git a/src/base/FBaseLongComparer.cpp b/src/base/FBaseLongComparer.cpp new file mode 100644 index 0000000..9110118 --- /dev/null +++ b/src/base/FBaseLongComparer.cpp @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLongComparer.cpp + * @brief This is the implementation file for LongComparer class. + * @see Long and Tizen::Base::Collection::IComparer + */ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +LongComparer::LongComparer(void) + : __pLongComparerImpl(null) +{ +} + +LongComparer::~LongComparer(void) +{ +} + +result +LongComparer::Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const +{ + const Long* pLong1 = dynamic_cast (&obj1); + const Long* pLong2 = dynamic_cast (&obj2); + + SysTryReturn(NID_BASE, (pLong1 != null && pLong2 != null), E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used. Both of the obj1 and obj2 MUST be Long.", GetErrorMessage(E_INVALID_ARG)); + + cmp = Long::Compare(pLong1->ToLong(), pLong2->ToLong()); + + return E_SUCCESS; +} + +}} //Tizen::Base diff --git a/src/base/FBaseLongLong.cpp b/src/base/FBaseLongLong.cpp new file mode 100644 index 0000000..3851d48 --- /dev/null +++ b/src/base/FBaseLongLong.cpp @@ -0,0 +1,177 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLongLong.cpp + * @brief This is the implementation file for LongLong class. + * @see Number + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +LongLong::LongLong(long long value) + : value(value) + , __pLongLongImpl(null) +{ +} + +LongLong::LongLong(const LongLong& value) + : value(value.value) + , __pLongLongImpl(null) +{ +} + +LongLong::~LongLong(void) +{ +} + +LongLong& +LongLong::operator =(const LongLong& rhs) +{ + if (&rhs != this) + { + value = rhs.value; + } + return *this; +} + +int +LongLong::Compare(long long l1, long long l2) +{ + return (int) (l1 < l2 ? -1 : (l1 == l2 ? 0 : 1)); +} + +int +LongLong::CompareTo(const LongLong& value) const +{ + return(LongLong::Compare(this->value, value.value)); +} + +bool +LongLong::Equals(const Object& obj) const +{ + const LongLong* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + return value == (*pOther).value; +} + +int +LongLong::GetHashCode(void) const +{ + return static_cast (value); +} + +int +LongLong::GetHashCode(long long val) +{ + return static_cast (val); +} + +char +LongLong::ToChar(void) const +{ + return static_cast (value); +} + +short +LongLong::ToShort(void) const +{ + return static_cast (value); +} + +int +LongLong::ToInt(void) const +{ + return static_cast (value); +} + +long +LongLong::ToLong(void) const +{ + return static_cast (value); +} + +float +LongLong::ToFloat(void) const +{ + return static_cast (value); +} + +double +LongLong::ToDouble(void) const +{ + return static_cast (value); +} + +long long +LongLong::ToLongLong(void) const +{ + return value; +} + +String +LongLong::ToString(void) const +{ + return(LongLong::ToString(value)); +} + +String +LongLong::ToString(long long value) +{ + const static unsigned int LONG_LONG_LENGTH_MAX = 20; + + wchar_t sValue[LONG_LONG_LENGTH_MAX + 1]; + + wmemset(sValue, 0, sizeof(sValue) / sizeof(sValue[0])); + swprintf(sValue, (sizeof(sValue) / sizeof(sValue[0])), L"%lld", value); + + return String(sValue); +} + +result +LongLong::Parse(const String& s, long long& ret) +{ + wchar_t* pEnd = null; + + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0), E_NUM_FORMAT, E_NUM_FORMAT, "[E_NUM_FORMAT] The length of s MUST be greater than 0."); + + errno = 0; + ret = wcstoll(s.GetPointer(), &pEnd, 10); + SysTryReturn(NID_BASE, (!(ret == 0 && errno == EINVAL) && (pEnd[0] == 0)), E_NUM_FORMAT, E_NUM_FORMAT, + "[E_NUM_FORMAT] LongLong parse failed. Scan stopped at (%ls)", + pEnd); + SysTryReturn(NID_BASE, !(errno == ERANGE && (ret == LLONG_MAX || ret == LLONG_MIN)), E_NUM_FORMAT, E_NUM_FORMAT, + "[E_NUM_FORMAT] Parsed value cannot fit into a LongLong."); + + return E_SUCCESS; +} + +}} //Tizen::Base diff --git a/src/base/FBaseLongLongComparer.cpp b/src/base/FBaseLongLongComparer.cpp new file mode 100644 index 0000000..a331087 --- /dev/null +++ b/src/base/FBaseLongLongComparer.cpp @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseLongLongComparer.cpp + * @brief This is the implementation file for LongLongComparer class. + * @see LongLong and Tizen::Base::Collection::IComparer + */ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +LongLongComparer::LongLongComparer(void) + : __pLongLongComparerImpl(null) +{ +} + +LongLongComparer::~LongLongComparer(void) +{ +} + +result +LongLongComparer::Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const +{ + const LongLong* pLongLong1 = dynamic_cast (&obj1); + const LongLong* pLongLong2 = dynamic_cast (&obj2); + + SysTryReturn(NID_BASE, (pLongLong1 != null && pLongLong2 != null), E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] Both of the obj1 and obj2 MUST be LongLong."); + + cmp = LongLong::Compare(pLongLong1->ToLongLong(), pLongLong2->ToLongLong()); + + return E_SUCCESS; +} + +}} //Tizen::Base diff --git a/src/base/FBaseObject.cpp b/src/base/FBaseObject.cpp new file mode 100644 index 0000000..2bb9a5d --- /dev/null +++ b/src/base/FBaseObject.cpp @@ -0,0 +1,68 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseObject.cpp + * @brief This is the implementation file for Object class. + */ + +#include + + +namespace Tizen { namespace Base +{ + +Object::Object(void) +{ +} + +Object::~Object(void) +{ +} + +Object::Object(const Object& obj) +{ +} + +bool +Object::Equals(const Object& obj) const +{ + // return true if two instances have the same memory address. + if (this == &obj) + { + return true; + } + else + { + return false; + } +} + +int +Object::GetHashCode(void) const +{ + // return the address of the current instance. + return (int) this; +} + +Object& +Object::operator =(const Object& rhs) +{ + return *this; +} + +}} //Tizen::Base diff --git a/src/base/FBaseResult.cpp b/src/base/FBaseResult.cpp new file mode 100644 index 0000000..63eec30 --- /dev/null +++ b/src/base/FBaseResult.cpp @@ -0,0 +1,423 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseResult.cpp + * @brief This is the implementation file of Result class. + */ + +#include +#include +#include + +#define ARR_ITEM_COUNT(arr) (sizeof(arr) / sizeof(arr[0])) +#define ERR_TABLE_INITIALIZER(no) {(ERR_SRC_FRAMEWORK + SET_E_CAUSE(no)), \ + ((ERR_SRC_FRAMEWORK + SET_E_CAUSE(no)) + ARR_ITEM_COUNT(__errTable ## no) - 1), __errTable ## no} + +typedef struct +{ + result rbegin; + result rend; + const char** table; +}ErrTableType; + +static __thread result lastResult = E_SUCCESS; + +static const char* E_SUCCESS_STRING = "E_SUCCESS"; +static const char* E_FAILURE_STRING = "E_FAILURE"; + +const char* +__BinarySearchErrorTable(ErrTableType errTable[], result value, int low, int high) +{ + + while (low <= high) + { + int mid = low + (high - low) / 2; + result rbegin = errTable[mid].rbegin; + result rend = errTable[mid].rend; + + if (value < rbegin) + { + high = mid - 1; + } + else if (value > rend) + { + low = mid + 1; + } + else + { + return errTable[mid].table[value - rbegin]; + } + } + if (value == E_SUCCESS) + { + return E_SUCCESS_STRING; + } + else if (value == E_FAILURE) + { + return E_FAILURE_STRING; + } + + return "Unknown Error"; +} + +const char* __errTable1100[] = +{ + "E_ADDRESS_CHANGED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1100)) + "E_ALREADY_BOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1101)) + "E_ALREADY_CONNECTED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1102)) + "E_ALREADY_OPENED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1103)) + "E_AUTHENTICATION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1104)) + "E_APP_NOT_INSTALLED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1105)) + "E_ALREADY_SET", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1106)) + "E_ACCOUNT_ALREADY_EXIST", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1107)) + "E_ACCOUNT_NOT_FOUND" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1108)) +}; + +const char* __errTable1300[] = +{ + "E_CHUNKED_TRANSACTION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1300)) + "E_CONNECTION_BUSY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1301)) + "E_CONNECTION_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1302)) + "E_CONNECTION_RESET", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1303)) + "E_CREDENTIAL_EXPIRED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1304)) + "E_CERTIFICATE_VERIFICATION_FAILED" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1305)) +}; + +const char* __errTable1400[] = +{ + "E_DATA_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1400)) + "E_DATABASE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1401)) + "E_DECODING_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1402)) + "E_DEVICE_BUSY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1403)) + "E_DEVICE_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1404)) + "E_DEVICE_INCOMPATIBLE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1405)) + "E_DEVICE_UNAVAILABLE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1406)) + "E_DHCP", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1407)) + "E_DIMENSION_CHANGED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1408)) + "E_DNS", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1409)) + "E_DNS_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1410)) + "E_DATA_NOT_ENOUGH" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1411)) +}; + +const char* __errTable1500[] = +{ + "E_EFFECTS_DISABLED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1500)) + "E_EMPTY_BODY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1501)) + "E_ENCODING_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1502)) + "E_END_OF_FILE" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1503)) +}; + +const char* __errTable1600[] = +{ + "E_FDN_MODE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1600)) + "E_FILE_ALREADY_EXIST", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1601)) + "E_FILE_NOT_FOUND" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1602)) +}; + +const char* __errTable1700[] = +{ + "E_GROUP_NOT_FOUND" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1700)) +}; + +const char* __errTable1800[] = +{ + "E_HOST_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1800)) + "E_HOST_UNREACHABLE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1801)) + "E_HTTP_USER" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1802)) +}; + +const char* __errTable1900[] = +{ + "E_ILLEGAL_ACCESS", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1900)) + "E_IN_PROGRESS", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1901)) + "E_INACCESSIBLE_PATH", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1902)) + "E_INIT_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1903)) + "E_INSTANTIATION_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1904)) + "E_INSUFFICIENT_PRIORITY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1905)) + "E_INTERRUPTED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1906)) + "E_INVALID_ACCOUNT", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1907)) + "E_INVALID_ADDRESS", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1908)) + "E_INVALID_ARG", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1909)) + "E_INVALID_CONDITION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1910)) + "E_INVALID_CONNECTION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1911)) + "E_INVALID_CONTENT", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1912)) + "E_INVALID_CONTEXT", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1913)) + "E_INVALID_DATA", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1914)) + "E_INVALID_DOMAIN", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1915)) + "E_INVALID_ENCODING_RANGE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1916)) + "E_INVALID_FORMAT", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1917)) + "E_INVALID_HEADER", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1918)) + "E_INVALID_KEY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1919)) + "E_INVALID_OPERATION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1920)) + "E_INVALID_PROXY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1921)) + "E_INVALID_SIM_STATE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1922)) + "E_INVALID_SERVER", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1923)) + "E_INVALID_SESSION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1924)) + "E_INVALID_SOCKET", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1925)) + "E_INVALID_STATE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1926)) + "E_INVALID_TRANSACTION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1927)) + "E_IO", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1928)) + "E_NOT_JOINED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1929)) + "E_INVALID_CERTIFICATE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1930)) + "E_INVALID_URL", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1931)) + "E_INVALID_USER_ID", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1932)) + "E_INVALID_PASSWORD" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(1933)) + +}; + +const char* __errTable2100[] = +{ + "E_KEY_ALREADY_EXIST", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2100)) + "E_KEY_NOT_FOUND" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2101)) +}; + +const char* __errTable2200[] = +{ + "E_LANDMARK", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2200)) + "E_LIBRARY_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2201)) + "E_LIBRARY_NOT_LOADED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2202)) + "E_LINK", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2203)) + "E_LOCATION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2204)) + "E_LOCATION_SERVICE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2205)) + "E_LOCK_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2206)) + "E_LANGUAGE_NOT_SET", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2207)) + "E_LOCATION_UNAVAILABLE" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2208)) +}; + +const char* __errTable2300[] = +{ + "E_MAX_EXCEEDED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2300)) + "E_MISSING_INPUT", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2301)) + "E_MOBILE_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2302)) + "E_MODEL_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2303)) + "E_MEMBER_ALREADY_EXIST" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2304)) +}; + +const char* __errTable2400[] = +{ + "E_NETWORK_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2400)) + "E_NETWORK_UNAVAILABLE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2401)) + "E_NO_CERTIFICATE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2402)) + "E_NOT_A_MEMBER", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2403)) + "E_NOT_PAIRED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2404)) + "E_NOT_RESPONDING", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2405)) + "E_NUM_FORMAT" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2406)) +}; + +const char* __errTable2500[] = +{ + "E_OBJ_ALREADY_EXIST", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2500)) + "E_OBJ_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2501)) + "E_OBJECT_LOCKED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2502)) + "E_ON_INITIALIZING", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2503)) + "E_OPERATION_CANCELED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2504)) + "E_OPERATION_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2505)) + "E_OUT_OF_MEMORY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2506)) + "E_OUT_OF_RANGE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2507)) + "E_OVERFLOW", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2508)) + "E_OPENGL_ERROR" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2509)) +}; + +const char* __errTable2600[] = +{ + "E_PAIRING_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2600)) + "E_PARSING_FAILED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2601)) + "E_PRIVILEGE_DENIED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2602)) + "E_PKG_NOT_INSTALLED" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2603)) +}; + +const char* __errTable2800[] = +{ + "E_READ_ONLY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2800)) + "E_REJECTED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2801)) + "E_REMOTE_DEVICE_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2802)) + "E_REMOVE_SERVICE_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2803)) + "E_RESOURCE_UNAVAILABLE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2804)) + "E_RIGHT_EXPIRED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2805)) + "E_RIGHT_NO_LICENSE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2806)) + "E_RIGHT_FUTURE_USE" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2807)) +}; + +const char* __errTable2900[] = +{ + "E_SECTION_ALREADY_EXIST", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2900)) + "E_SECTION_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2901)) + "E_SERVER", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2902)) + "E_SERVICE_BUSY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2903)) + "E_SERVICE_LIMITED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2904)) + "E_SERVICE_LOCKED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2905)) + "E_SERVICE_UNAVAILABLE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2906)) + "E_SESSION_DEACTIVATED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2907)) + "E_SESSION_UNAVAILABLE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2908)) + "E_SIZE_MISMATCH", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2909)) + "E_SOCKET_USER", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2910)) + "E_STORAGE_FULL", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2911)) + "E_SYMBOL_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2912)) + "E_SYNTAX", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2913)) + "E_SYSTEM", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2914)) + "E_SERVICE_DEACTIVATED " //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(2915)) +}; + +const char* __errTable3000[] = +{ + "E_TABLE_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3000)) + "E_TIMEOUT", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3001)) + "E_TYPE_MISMATCH" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3002)) +}; + +const char* __errTable3100[] = +{ + "E_UNDERFLOW", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3100)) + "E_UNKNOWN", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3101)) + "E_UNSUPPORTED_ALGORITHM", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3102)) + "E_UNSUPPORTED_CODEC", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3103)) + "E_UNSUPPORTED_FAMILY", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3104)) + "E_UNSUPPORTED_FORMAT", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3105)) + "E_UNSUPPORTED_PROTOCOL", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3106)) + "E_UNSUPPORTED_OPERATION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3107)) + "E_UNSUPPORTED_OPTION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3108)) + "E_UNSUPPORTED_SERVICE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3109)) + "E_UNSUPPORTED_TYPE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3110)) + "E_URL_CHANGED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3111)) + "E_USER_AGENT_NOT_ALLOWED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3112)) + "E_USER_ALREADY_REGISTERED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3113)) + "E_USER_NOT_FOUND", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3114)) + "E_USER_NOT_REGISTERED", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3115)) + "E_UNSUPPORTED_LANGUAGE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3116)) + "E_UNSUPPORTED_VERSION", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3117)) + "E_UNSUPPORTED_LOCALE", //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3118)) + "E_USER_NOT_CONSENTED" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3119)) +}; + +const char* __errTable3300[] = +{ + "E_WOULD_BLOCK" //(ERR_SRC_FRAMEWORK + SET_E_CAUSE(3300)) +}; + +// Add the error tables in sorted order. Then we can use binary search. +// else we will have to use sequential search +ErrTableType __gErrTable[] = +{ + ERR_TABLE_INITIALIZER(1100), + ERR_TABLE_INITIALIZER(1300), + ERR_TABLE_INITIALIZER(1400), + ERR_TABLE_INITIALIZER(1500), + ERR_TABLE_INITIALIZER(1600), + ERR_TABLE_INITIALIZER(1700), + ERR_TABLE_INITIALIZER(1800), + ERR_TABLE_INITIALIZER(1900), + ERR_TABLE_INITIALIZER(2100), + ERR_TABLE_INITIALIZER(2200), + ERR_TABLE_INITIALIZER(2300), + ERR_TABLE_INITIALIZER(2400), + ERR_TABLE_INITIALIZER(2500), + ERR_TABLE_INITIALIZER(2600), + ERR_TABLE_INITIALIZER(2800), + ERR_TABLE_INITIALIZER(2900), + ERR_TABLE_INITIALIZER(3000), + ERR_TABLE_INITIALIZER(3100), + ERR_TABLE_INITIALIZER(3300) +}; + +result +GetLastResult(void) +{ + return lastResult; +} + +void +SetLastResult(result r) +{ + lastResult = r; +} + +void +ClearLastResult(void) +{ + lastResult = E_SUCCESS; +} + + +const char* +GetErrorMessage(result value) +{ + return __BinarySearchErrorTable(__gErrTable, value, 0, (ARR_ITEM_COUNT(__gErrTable) - 1)); +} + +#define MAX_CHECK_COUNT 100 +_OSP_EXPORT_ result TransExceptionsExclusiveInternal(result r, result e, int num,...); + +_OSP_EXPORT_ result TransExceptionsInclusiveInternal(result r, result e, int num,...); + +result +TransExceptionsExclusiveInternal(result r, result e, int num, ...) +{ + va_list ap; + bool ref = false; + int count = 0; + + if(r == E_SUCCESS) + return r; + + va_start(ap,num); + for(count; count < num; count++ ) + { + if (r == va_arg(ap, result)) + { + ref = true; + break; + } + } + va_end(ap); + if(ref) + return r; + + return e; + +} + +result +TransExceptionsInclusiveInternal(result r, result e, int num, ...) +{ + va_list ap; + bool ref = false; + int count = 0; + + if(r == E_SUCCESS) + return r; + + va_start(ap,num); + for(count; count < num ; count++ ) + { + if (r == va_arg(ap, result)) + { + ref = true; + break; + } + } + va_end(ap); + if(ref) + return e; + + return r; + +} + + + + diff --git a/src/base/FBaseShort.cpp b/src/base/FBaseShort.cpp new file mode 100644 index 0000000..7632bd3 --- /dev/null +++ b/src/base/FBaseShort.cpp @@ -0,0 +1,273 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseShort.cpp + * @brief This is the implementation file for Short class. + * @see Number + */ + +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +Short::Short(short value) + : value(value) + , __pShortImpl(null) +{ +} + +Short::Short(const Short& value) + : value(value.value) + , __pShortImpl(null) +{ +} + +Short::~Short(void) +{ +} + +Short& +Short::operator =(const Short& rhs) +{ + if (&rhs != this) + { + value = rhs.value; + } + return *this; +} + +int +Short::Compare(short s1, short s2) +{ + return(s1 < s2 ? -1 : (s1 == s2 ? 0 : 1)); +} + +int +Short::CompareTo(const Short& value) const +{ + return(Short::Compare(this->value, value.value)); +} + +bool +Short::Equals(const Object& obj) const +{ + const Short* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + return value == (*pOther).value; +} + +bool +Short::Equals(short value) const +{ + return this->value == value; +} + +int +Short::GetHashCode(void) const +{ + return static_cast (value); +} + +int +Short::GetHashCode(short val) +{ + return static_cast (val); +} + +result +Short::Decode(const String& s, short& ret) +{ + SysTryReturn(NID_BASE, s.GetLength() >= 1, E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of s MUST be greater than 0.", GetErrorMessage(E_NUM_FORMAT)); + + long value = 0; + int radix = 0; + wchar_t* pEnd = null; + String str(s); + + // Find radix + if (s[0] == L'#') + { + radix = Character::RADIX_HEXADECIMAL; + + // Remove '#' + str.Remove(0, 1); + } + else if (s[0] == L'0' && (s.GetLength() >= 2)) + { + if (s[1] == L'x' || s[1] == L'X') + { + radix = Character::RADIX_HEXADECIMAL; + } + else + { + radix = Character::RADIX_OCTAL; + } + } + else + { + radix = Character::RADIX_DECIMAL; + } + + result r = E_SUCCESS; + + errno = 0; + value = wcstol(str.GetPointer(), &pEnd, radix); + SysTryCatch(NID_BASE, (pEnd[0] == 0), r = E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Short decode failed. Scan stopped at (%ls).", GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryCatch(NID_BASE, !((value == LONG_MAX || value == LONG_MIN) && (errno != 0)), r = E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Decoded value cannot fit into Short.", GetErrorMessage(E_NUM_FORMAT)); + +CATCH: + if (value > Short::VALUE_MAX) + { + ret = Short::VALUE_MAX; + } + else if (value < Short::VALUE_MIN) + { + ret = Short::VALUE_MIN; + } + else + { + ret = (short) value; + } + + return r; +} + +result +Short::Parse(const String& s, short& ret) +{ + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0 && len < 7), E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] The length of s(%ls) MUST be greater than 0 and less than 7.", GetErrorMessage(E_NUM_FORMAT), s.GetPointer()); + + return Parse(s, Character::RADIX_DECIMAL, ret); +} + +result +Short::Parse(const String& s, int radix, short& ret) +{ + SysTryReturn(NID_BASE, ((radix == Character::RADIX_BINARY) || (radix == Character::RADIX_OCTAL) || + (radix == Character::RADIX_DECIMAL) || (radix == Character::RADIX_HEXADECIMAL)), E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The radix(%d) MUST be one of 2, 8, 10 and 16.", GetErrorMessage(E_OUT_OF_RANGE), radix); + + long value = 0; + wchar_t* pEnd = null; + + int len = s.GetLength(); + SysTryReturn(NID_BASE, (len > 0), E_NUM_FORMAT, E_NUM_FORMAT, "[%s] The length of s MUST be greater than 0.", + GetErrorMessage(E_NUM_FORMAT)); + + result r = E_SUCCESS; + + errno = 0; + value = wcstol(s.GetPointer(), &pEnd, radix); + SysTryCatch(NID_BASE, (pEnd[0] == 0), r = E_NUM_FORMAT, E_NUM_FORMAT, + "[%s] Short parse failed. Scan stopped at (%ls).", GetErrorMessage(E_NUM_FORMAT), pEnd); + SysTryCatch(NID_BASE, !(value > Short::VALUE_MAX || value < Short::VALUE_MIN) || (errno != 0), r = E_NUM_FORMAT, + E_NUM_FORMAT, "[%s] Parsed value cannot fit into Short.", GetErrorMessage(E_NUM_FORMAT)); + +CATCH: + if (value > Short::VALUE_MAX) + { + ret = Short::VALUE_MAX; + } + else if (value < Short::VALUE_MIN) + { + ret = Short::VALUE_MIN; + } + else + { + ret = (short) value; + } + + return r; +} + +char +Short::ToChar(void) const +{ + return static_cast (value); +} + +short +Short::ToShort(void) const +{ + return value; +} + +int +Short::ToInt(void) const +{ + return static_cast (value); +} + +long +Short::ToLong(void) const +{ + return static_cast (value); +} + +long long +Short::ToLongLong(void) const +{ + return static_cast (value); +} + +float +Short::ToFloat(void) const +{ + return static_cast (value); +} + +double +Short::ToDouble(void) const +{ + return static_cast (value); +} + +String +Short::ToString(void) const +{ + return(Short::ToString(value)); +} + +String +Short::ToString(short value) +{ + const static unsigned int SHORT_LENGTH_MAX = 6; + + wchar_t sValue[SHORT_LENGTH_MAX + 1] = {0, }; + swprintf(sValue, (sizeof(sValue) / sizeof(sValue[0])), L"%d", value); + + return String(sValue); +} + +}} //Tizen::Base diff --git a/src/base/FBaseShortComparer.cpp b/src/base/FBaseShortComparer.cpp new file mode 100644 index 0000000..7409bc7 --- /dev/null +++ b/src/base/FBaseShortComparer.cpp @@ -0,0 +1,54 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseShortComparer.cpp + * @brief This is the implementation file for ShortComparer class. + * @see Short class and Tizen::Base::Collection::IComparer + */ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +ShortComparer::ShortComparer(void) + : __pShortComparerImpl(null) +{ +} + +ShortComparer::~ShortComparer(void) +{ +} + +result +ShortComparer::Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const +{ + const Short* pShort1 = dynamic_cast (&obj1); + const Short* pShort2 = dynamic_cast (&obj2); + SysTryReturn(NID_BASE, (pShort1 != null && pShort2 != null), E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used. Both of the obj1 and obj2 MUST be Short.", GetErrorMessage(E_INVALID_ARG)); + + cmp = Short::Compare(pShort1->ToShort(), pShort2->ToShort()); + + return E_SUCCESS; +} + +}} //Tizen::Base diff --git a/src/base/FBaseString.cpp b/src/base/FBaseString.cpp new file mode 100644 index 0000000..dac9971 --- /dev/null +++ b/src/base/FBaseString.cpp @@ -0,0 +1,1554 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FBaseString.cpp +* @brief This is the implementation for String class. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base +{ + +const float String::GROWTH_FACTOR = 1.5; + +String::String(void) + : __capacity(0) + , __length(0) + , __hash(0) + , __pRefCount(null) + , __pValue(null) + , __pStringImpl(null) +{ + result r = InitializeToDefault(DEFAULT_CAPACITY); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); +} + +String::String(int capacity) + : __capacity(0) + , __length(0) + , __hash(0) + , __pRefCount(null) + , __pValue(null) + , __pStringImpl(null) +{ + if (capacity <= 0) + { + capacity = DEFAULT_CAPACITY; + } + + result r = InitializeToDefault(capacity); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); +} + +String::String(const wchar_t ch) + : __capacity(0) + , __length(0) + , __hash(0) + , __pRefCount(null) + , __pValue(null) + , __pStringImpl(null) +{ + result r = InitializeToDefault(DEFAULT_CAPACITY); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __pValue[0] = ch; + __pValue[1] = '\0'; + __length = 1; +} + +String::String(const wchar_t* pValue) + : __capacity(0) + , __length(0) + , __hash(0) + , __pRefCount(null) + , __pValue(null) + , __pStringImpl(null) +{ + int length = (pValue != null) ? wcslen(pValue) : 0; + + SysTryReturnVoidResult(NID_BASE, length >= 0, E_OUT_OF_RANGE, + "String has wrong length. The length has to be more bigger than 0."); + + if (pValue == null) + { + result r = InitializeToDefault(DEFAULT_CAPACITY); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + else + { + result r = InitializeToDefault(length + DEFAULT_CAPACITY); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + + wcsncpy(__pValue, pValue, length); + __pValue[length] = '\0'; + __length = length; + } +} + +String::String(const char* pValue) + : __capacity(0) + , __length(0) + , __hash(0) + , __pRefCount(null) + , __pValue(null) + , __pStringImpl(null) +{ + int len = (pValue != null) ? mbstowcs(null, pValue, 0) : 0; + + if (pValue == null) + { + result r = InitializeToDefault(DEFAULT_CAPACITY); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + else + { + result r = InitializeToDefault(len + DEFAULT_CAPACITY); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + + len = mbstowcs(__pValue, pValue, len); + if (len == -1) + { + SysLog(NID_BASE, "Invalid encoding range[%s].", pValue); + } + __pValue[len] = '\0'; + __length = len; + } +} + +String::String(const String& value) + : __capacity(value.__capacity) + , __length(value.__length) + , __hash(value.__hash) + , __pRefCount(null) + , __pValue(value.__pValue) + , __pStringImpl(null) +{ + SysTryReturnVoidResult(NID_BASE, value.__length >= 0, E_OUT_OF_RANGE, "The length has to be greater than 0."); + + ++(*value.__pRefCount); + __pRefCount = value.__pRefCount; +} + +String::~String(void) +{ + if (*__pRefCount == 1) + { + delete[] __pValue; + delete __pRefCount; + } + else + { + (*__pRefCount)--; + __pRefCount = null; + } +} + +const wchar_t& +String::operator [](int index) const +{ + static wchar_t ch = -1; + SysTryReturn(NID_BASE, (index < __length && index >= 0), ch, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __length); + return __pValue[index]; +} + +wchar_t& +String::operator [](int index) +{ + static wchar_t ch = -1; + SysTryReturn(NID_BASE, (index < __length && index >= 0), ch, E_OUT_OF_RANGE, + "[%s] The index(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + GetErrorMessage(E_OUT_OF_RANGE), index, __length); + + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturn(NID_BASE, r == E_SUCCESS, ch, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + __hash = 0; + return __pValue[index]; +} + +String& +String::operator =(const wchar_t* pRhs) +{ + if (pRhs == null) + { + return *this; + } + + String tStr(pRhs); + tStr.Swap(*this); + + return *this; +} + +String& +String::operator =(const String& rhs) +{ + if (&rhs == this) + { + return *this; + } + + String tStr(rhs); + tStr.Swap(*this); + + return *this; +} + +String& +String::operator +=(const wchar_t* pRhs) +{ + if (pRhs == null) + { + return *this; + } + + Append(pRhs); + + return *this; +} + +String& +String::operator +=(const String& rhs) +{ + if (rhs.IsEmpty()) + { + return *this; + } + + Append(rhs.__pValue); + + return *this; +} + +String +operator +(const String& lhs, const String& rhs) +{ + String str(lhs); + + str.Append(rhs.__pValue); + + return str; +} + +bool +String::operator ==(const String& rhs) const +{ + if (__length != rhs.__length) + { + return false; + } + + return(CompareTo(rhs) == 0); +} + +bool +String::operator !=(const String& rhs) const +{ + return(!(*this).operator ==(rhs)); +} + +bool +String::IsEmpty(void) const +{ + return(__length == 0); +} + +result +String::Append(wchar_t ch) +{ + result r = Append(Character::ToString(ch)); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Append(char ch) +{ + result r = Append((wchar_t) ch); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Append(int i) +{ + result r = Append(Integer::ToString(i)); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Append(short s) +{ + result r = Append(Short::ToString(s)); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Append(long l) +{ + result r = Append(Long::ToString(l)); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Append(long long ll) +{ + result r = Append(LongLong::ToString(ll)); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Append(float f) +{ + result r = Append(Float::ToString(f)); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Append(double d) +{ + result r = Append(Double::ToString(d)); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Append(const wchar_t* p) +{ + SysTryReturnResult(NID_BASE, p != null, E_INVALID_ARG, "p is null."); + + int length = (wcslen(p) + __length); + + if (*__pRefCount > 1) + { + wchar_t* pValue = __pValue; + SysTryReturnResult(NID_BASE, AllocateCapacity(length) != false, E_OUT_OF_MEMORY, "Memory allocation failed."); + std::unique_ptr pRefCntTemp(new (std::nothrow) int(1)); + SysTryReturnResult(NID_BASE, pRefCntTemp != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + wcsncpy(__pValue, pValue, __length); + (*__pRefCount)--; + __pRefCount = pRefCntTemp.release(); + } + + result r = EnsureCapacity(length); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + wcsncpy((__pValue + __length), p, wcslen(p)); + + __pValue[length] = '\0'; + __length = length; + __hash = 0; + + return E_SUCCESS; +} + +result +String::Append(const String& str) +{ + if (str.IsEmpty()) + { + return E_SUCCESS; + } + + result r = Append(str.__pValue); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +void +String::Clear(void) +{ + String tStr; + tStr.Swap(*this); +} + +int +String::Compare(const String& str0, const String& str1) +{ + if (str0.__pValue == str1.__pValue) + { + return 0; + } + + return(wcscmp(str0.__pValue, str1.__pValue)); +} + +int +String::CompareTo(const String& str) const +{ + if (__pValue == str.__pValue) + { + return 0; + } + + return(wcscmp(__pValue, str.__pValue)); +} + +result +String::EnsureCapacity(int minCapacity) +{ + SysTryReturnResult(NID_BASE, minCapacity >= 0, E_INVALID_ARG, "The minCapacity(%d) MUST be greater than or equal to 0.", + minCapacity); + + if (minCapacity > __capacity) + { + SysTryReturnResult(NID_BASE, ExpandCapacity(minCapacity), E_OUT_OF_MEMORY, "Memory allocation failed."); + } + return E_SUCCESS; +} + +bool +String::Equals(const Object& obj) const +{ + const String* pOther = dynamic_cast (&obj); + + if (pOther == null) + { + return false; + } + + return(*this == *pOther); +} + +bool +String::Equals(const String& str, bool caseSensitive) const +{ + if (caseSensitive) + { + return(*this == str); + } + else + { + if (__length != str.__length) + { + return false; + } + + if (__pValue == str.__pValue) + { + return true; + } + + if (wcscasecmp(__pValue, str.__pValue) == 0) + { + return true; + } + + return false; + } +} + +result +String::Format(int length, const wchar_t* pFormat, ...) +{ + int index = -1; + result r = E_SUCCESS; + + SysTryReturnResult(NID_BASE, pFormat != null, E_INVALID_ARG, "The pFormat is null."); + SysTryReturnResult(NID_BASE, length >= 0, E_INVALID_ARG, "The length(%d) MUST be greater than or equal to 0.", + length); + + String tempStr(pFormat); + if (tempStr.IsEmpty() || length == 0) + { + Clear(); + return E_SUCCESS; + } + + // Check "%n" and "%hn" + r = tempStr.IndexOf(L"%n", 0, index); + SysTryReturnResult(NID_BASE, r == E_OBJ_NOT_FOUND, E_INVALID_ARG, "(%ls) is not supported format.", pFormat); + + r = tempStr.IndexOf(L"%hn", 0, index); + SysTryReturnResult(NID_BASE, r == E_OBJ_NOT_FOUND, E_INVALID_ARG, "(%ls) is not supported format.", pFormat); + + Clear(); + + std::unique_ptr pStr(new (std::nothrow) wchar_t[length + 1]); + SysTryReturnResult(NID_BASE, pStr != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + pStr[length] = '\0'; + + va_list args; + va_start(args, pFormat); + + vswprintf(pStr.get(), length, tempStr.__pValue, args); + + va_end(args); + + *this = pStr.get(); + + int len = wcslen(this->__pValue); + if (length > len) + { + this->__pValue[len] = '\0'; + this->__length = len; + } + else + { + this->__pValue[length - 1] = '\0'; + this->__length = length - 1; + } + this->__hash = 0; + + return E_SUCCESS; +} + +int +String::GetHashCode(void) const +{ + int hash = 0; + + if (__hash == 0) + { + wchar_t* pStr = __pValue; + for (int i = 0; i < __length; ++i) + { + hash = (hash << 5) - hash + (int) *pStr++; + } + __hash = hash; + } + else + { + hash = __hash; + } + + return hash; +} + +result +String::GetCharAt(int indexAt, wchar_t& ret) const +{ + SysTryReturnResult(NID_BASE, (indexAt < __length), E_OUT_OF_RANGE, + "The indexAt(%d) MUST be less than the length of this string(%d).", indexAt, __length); + SysTryReturnResult(NID_BASE, (indexAt >= 0), E_OUT_OF_RANGE, + "The indexAt(%d) MUST be greater than or equal to 0.", indexAt); + + ret = __pValue[indexAt]; + + return E_SUCCESS; +} + +result +String::IndexOf(wchar_t ch, int startIndex, int& indexOf) const +{ + SysTryReturnResult(NID_BASE, startIndex < __length, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be less than the length of this string(%d).", startIndex, __length); + SysTryReturnResult(NID_BASE, startIndex >= 0, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be greater than or equal to 0.", startIndex); + + wchar_t* pBeg = __pValue + startIndex; + wchar_t* pFound = (wchar_t*) wcschr((const wchar_t*) pBeg, (wchar_t) ch); + + if (pFound == null) + { + indexOf = -1; + + return E_OBJ_NOT_FOUND; + } + + indexOf = int(pFound - __pValue); + + return E_SUCCESS; +} + +result +String::IndexOf(const String& str, int startIndex, int& indexOf) const +{ + SysTryReturnResult(NID_BASE, (startIndex < __length), E_OUT_OF_RANGE, + "The startIndex(%d) MUST be less than the length of this string(%d).", startIndex, __length); + SysTryReturnResult(NID_BASE, (startIndex >= 0), E_OUT_OF_RANGE, + "The startIndex(%d) MUST be greater than or equal to 0.", startIndex); + + if (str.IsEmpty()) + { + indexOf = startIndex; + return E_SUCCESS; + } + + if (__length < str.__length) + { + indexOf = -1; + return E_OBJ_NOT_FOUND; + } + + wchar_t* p = null; + + p = (wchar_t*) wcsstr((__pValue + startIndex), str.__pValue); + if (p == null) + { + indexOf = -1; + + return E_OBJ_NOT_FOUND; + } + + indexOf = int(p - __pValue); + + return E_SUCCESS; +} + +result +String::Insert(wchar_t ch, int indexAt) +{ + SysTryReturnResult(NID_BASE, + indexAt >= 0 && indexAt <= __length, E_OUT_OF_RANGE, + "The indexAt(%d) MUST be greater than or equal to 0, and less than or equal to the length of this string(%d).", + indexAt, __length); + + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + int length = (__length + 1); + + result r = EnsureCapacity(length); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + wmemmove((__pValue + indexAt + 1), (__pValue + indexAt), ((__length + 1) - indexAt)); + + __pValue[indexAt] = ch; + __length = length; + __hash = 0; + + return E_SUCCESS; +} + +result +String::Insert(char ch, int indexAt) +{ + wchar_t wideChar = (wchar_t) ch; + + result r = Insert(wideChar, indexAt); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Insert(short s, int indexAt) +{ + result r = Insert(Short::ToString(s), indexAt); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Insert(int i, int indexAt) +{ + result r = Insert(Integer::ToString(i), indexAt); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Insert(long l, int indexAt) +{ + result r = Insert(Long::ToString(l), indexAt); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Insert(long long ll, int indexAt) +{ + result r = Insert(LongLong::ToString(ll), indexAt); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Insert(float f, int indexAt) +{ + result r = Insert(Float::ToString(f), indexAt); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Insert(double d, int indexAt) +{ + result r = Insert(Double::ToString(d), indexAt); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + return r; +} + +result +String::Insert(const wchar_t* p, int indexAt) +{ + SysTryReturnResult(NID_BASE, p != null, E_INVALID_ARG, "The p is null."); + SysTryReturnResult(NID_BASE, + indexAt >= 0 && indexAt <= __length, E_OUT_OF_RANGE, + "The indexAt(%d) MUST be greater than or equal to 0, and less than or equal to the length of this string(%d).", + indexAt, __length); + + int length = wcslen(p); + if (length == 0) + { + return E_SUCCESS; + } + + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + result r = EnsureCapacity(__length + length); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + wmemmove((__pValue + indexAt + length), (__pValue + indexAt), ((__length + 1) - indexAt)); + wmemcpy((__pValue + indexAt), p, length); + + __length += length; + __hash = 0; + return E_SUCCESS; +} + +result +String::Insert(const String& str, int indexAt) +{ + result r = Insert(str.__pValue, indexAt); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::LastIndexOf(wchar_t ch, int startIndex, int& indexOf) const +{ + SysTryReturnResult(NID_BASE, + startIndex >= 0 && startIndex < __length, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + startIndex, __length); + + wchar_t* pBeg = __pValue + startIndex; + wchar_t* pEnd = __pValue; + while (pEnd <= pBeg) + { + if (*pBeg == ch) + { + indexOf = int(pBeg - __pValue); + + return E_SUCCESS; + } + --pBeg; + } + + indexOf = -1; + + return E_OBJ_NOT_FOUND; +} + +result +String::LastIndexOf(const String& str, int startIndex, int& indexOf) const +{ + SysTryReturnResult(NID_BASE, + startIndex >= 0 && startIndex < __length, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + startIndex, __length); + + if (str.IsEmpty()) + { + indexOf = startIndex; + return E_SUCCESS; + } + + if (__length < str.__length) + { + indexOf = -1; + + return E_OBJ_NOT_FOUND; + } + + const wchar_t* pStr = str.__pValue; + + int length = str.__length; + if (length > startIndex) + { + indexOf = -1; + + return E_OBJ_NOT_FOUND; + } + + indexOf = -1; + wchar_t* pBeg = __pValue + startIndex; + wchar_t* pEnd = __pValue; + + while (pBeg >= pEnd) + { + if (wcsncmp(pBeg, pStr, length) == 0) + { + indexOf = (pBeg - __pValue); + + return E_SUCCESS; + } + --pBeg; + } + + return E_OBJ_NOT_FOUND; +} + +result +String::Remove(int startIndex, int count) +{ + SysTryReturnResult(NID_BASE, + startIndex >= 0 && startIndex < __length, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + startIndex, __length); + int moveIndex = startIndex + count; + SysTryReturnResult(NID_BASE, moveIndex <= __length, E_OUT_OF_RANGE, + "The startIndex(%d) + count(%d) MUST be less than or equal to the length of this string(%d).", + startIndex, count, __length); + + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + wmemmove(__pValue + startIndex, __pValue + moveIndex, (__length - moveIndex) + 1); + __length -= count; + __pValue[__length] = '\0'; + __hash = 0; + + return E_SUCCESS; +} + +void +String::Replace(wchar_t original, wchar_t replace) +{ + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + for (int length = __length; length >= 0; --length) + { + if (__pValue[length] == original) + { + __pValue[length] = replace; + } + } + __hash = 0; +} + +result +String::Replace(const String& org, const String& rep) +{ + result r = Replace(org, rep, 0); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; +} + +result +String::Replace(const String& org, const String& rep, int startIndex) +{ + const int orgLen = org.__length; + SysTryReturnResult(NID_BASE, orgLen > 0, E_INVALID_ARG, "The length of org(%d) MUST be greater than 0.", orgLen); + + SysTryReturnResult(NID_BASE, + startIndex >= 0 && startIndex < __length, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + startIndex, __length); + + if (__length == 0) + { + return E_SUCCESS; + } + + if ((orgLen == __length) && (*this == org)) + { + const int newLength = rep.__length; + if (EnsureCapacity(newLength) != E_SUCCESS) + { + SetCapacity(newLength); + } + + wcsncpy(__pValue, rep.__pValue, rep.__length); + + __length = rep.__length; + __pValue[__length] = '\0'; + __hash = 0; + + return E_SUCCESS; + } + + int repLen = rep.__length; + + wchar_t* pOrg = org.__pValue; + wchar_t* pRep = rep.__pValue; + + int count = 0; + { + wchar_t* pBeg = (__pValue + startIndex); + wchar_t* pEnd = pBeg + __length; + while (pBeg < pEnd) + { + wchar_t* pTarget = null; + while ((pTarget = (wchar_t*) wcsstr(pBeg, pOrg)) != null) + { + ++count; + pBeg = pTarget + orgLen; + } + pBeg += wcslen(pBeg) + 1; + } + } + + if (count > 0) + { + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + const int newLength = (count * (repLen - orgLen)) + __length; + result r = EnsureCapacity(newLength); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + wchar_t* pBeg = (__pValue + startIndex); + wchar_t* pEnd = pBeg + __length; + while (pBeg < pEnd) + { + wchar_t* pTarget = null; + while ((pTarget = (wchar_t*) wcsstr(pBeg, pOrg)) != null) + { + int balance = __length - int(pTarget - (__pValue + startIndex) + orgLen); + wmemmove(pTarget + repLen, pTarget + orgLen, balance); + wmemcpy(pTarget, pRep, repLen); + pBeg = pTarget + repLen; + pTarget[repLen + balance] = 0; + __length += (repLen - orgLen); + } + pBeg += (wcslen(pBeg) + 1); + } + + __length = newLength; + __hash = 0; + } + + return E_SUCCESS; +} + +void +String::Reverse(void) +{ + if (*__pRefCount > 0) + { + result r = CopyOnWrite(__capacity); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + wchar_t* pBeg = __pValue; + wchar_t* pEnd = __pValue + __length - 1; + wchar_t ch = 0x00; + + for (; pBeg < pEnd; ++pBeg, --pEnd) + { + ch = *pBeg; + *pBeg = *pEnd; + *pEnd = ch; + } + __hash = 0; +} + +result +String::SetCapacity(int capacity) +{ + SysTryReturnResult(NID_BASE, capacity >= 0, E_INVALID_ARG, + "The capacity(%d) MUST be greater than or equal to 0.", capacity); + + std::unique_ptr pValue(new (std::nothrow) wchar_t[capacity + 1]); + SysTryReturnResult(NID_BASE, pValue != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + if (__pValue != null) + { + if (__length < capacity) + { + wmemcpy(pValue.get(), __pValue, (__length + 1)); + } + else + { + wmemcpy(pValue.get(), __pValue, capacity); + pValue[capacity] = '\0'; + __length = capacity; + __hash = 0; + } + + if (*__pRefCount == 1) + { + delete[] __pValue; + } + else + { + std::unique_ptr pRefCntTemp(new (std::nothrow) int(1)); + SysTryReturnResult(NID_BASE, pRefCntTemp != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + (*__pRefCount)--; + __pRefCount = pRefCntTemp.release(); + } + } + + __pValue = pValue.release(); + __capacity = capacity; + + return E_SUCCESS; +} + +result +String::SetCharAt(wchar_t ch, int indexAt) +{ + SysTryReturn(NID_BASE,indexAt >= 0 && indexAt < __length, E_OUT_OF_RANGE, E_OUT_OF_RANGE, + "[%s] The indexAt(%d) MUST be greater than or equal to 0, and less then the length of this string(%d).", + GetErrorMessage(E_OUT_OF_RANGE), indexAt, __length); + + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + __pValue[indexAt] = ch; + __hash = 0; + + return E_SUCCESS; +} + +result +String::SetLength(int newLength) +{ + SysTryReturnResult(NID_BASE, newLength >= 0, E_INVALID_ARG, "The newLength(%d) MUST be greater than or equal to 0.", + newLength); + + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + static const wchar_t SPACE = 0x0020; + + result r = EnsureCapacity(newLength); + SysTryReturn(NID_BASE, r == E_SUCCESS, r, r, "[%s] Propagating.", GetErrorMessage(r)); + + if (newLength > __length) + { + wmemset(__pValue + __length, SPACE, newLength - __length); + } + + __pValue[newLength] = '\0'; + __length = newLength; + __hash = 0; + + return E_SUCCESS; +} + +result +String::SubString(int startIndex, String& out) const +{ + SysTryReturnResult(NID_BASE, + startIndex >= 0 && startIndex < __length, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + startIndex, __length); + + out = __pValue + startIndex; + + return E_SUCCESS; +} + +result +String::SubString(int startIndex, int length, String& out) const +{ + SysTryReturnResult(NID_BASE, + startIndex >= 0 && startIndex < __length, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + startIndex, __length); + SysTryReturnResult(NID_BASE, length >= 0, E_OUT_OF_RANGE, "The length(%d) MUST be greater than 0.", length); + SysTryReturnResult(NID_BASE, startIndex + length <= __length, E_OUT_OF_RANGE, + "The startIndex(%d) + length(%d) MUST be less than or equal to the length of this string(%d).", + startIndex, length, __length); + + if (length > 0) + { + std::unique_ptr pTemp(new (std::nothrow) wchar_t[length + 1]); + SysTryReturnResult(NID_BASE, pTemp != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + wcsncpy(pTemp.get(), __pValue + startIndex, length); + pTemp[length] = '\0'; + + out = pTemp.get(); + } + else if (length == 0) + { + out.Clear(); + } + + return E_SUCCESS; +} + +bool +String::StartsWith(const String& str, int startIndex) const +{ + SysTryReturn(NID_BASE, startIndex >= 0 && startIndex < __length, false, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be greater than or equal to 0, and less than the length of this string(%d).", + GetErrorMessage(E_OUT_OF_RANGE), startIndex, __length); + SysTryReturn(NID_BASE, str.__length > 0, false, E_INVALID_ARG, + "[%s] Invalid argument is used. The length of str(%d) MUST be greater than 0.", + GetErrorMessage(E_INVALID_ARG), str.__length); + + if (str.__length > __length) + { + return false; + } + + if ((wcsncmp(__pValue + startIndex, str.__pValue, str.__length) == 0)) + { + return true; + } + + return false; +} + +bool +String::EndsWith(const String& str) const +{ + if (this == &str) + { + return true; + } + + int strLen = str.__length; + SysTryReturn(NID_BASE, strLen > 0, false, E_INVALID_ARG, + "[%s] Invalid argument is used. The length of str(%d) MUST be greater than 0.", GetErrorMessage(E_INVALID_ARG), strLen); + + int curLen = __length; + if (strLen > curLen || curLen == 0) + { + return false; + } + else if (wcscmp(__pValue + (curLen - strLen), str.__pValue) == 0) + { + return true; + } + + return false; +} + +result +String::ToLower(String& out) const +{ + String str(__length + 1); + + wchar_t* pDst = str.__pValue; + wchar_t* pSrc = __pValue; + + for (; *pSrc != 0; ++pSrc, ++pDst) + { + *pDst = Character::ToLower(*pSrc); + } + + *pDst = '\0'; + + str.__length = __length; + out = str; + + return E_SUCCESS; +} + +result +String::ToLowerCase(String& out) const +{ + String str(__length + 1); + + wchar_t* pDst = str.__pValue; + wchar_t* pSrc = __pValue; + + for (; *pSrc != 0; ++pSrc, ++pDst) + { + *pDst = Character::ToLowerCase(*pSrc); + } + + *pDst = '\0'; + + str.__length = __length; + out = str; + + return E_SUCCESS; +} + +result +String::ToUpper(String& out) const +{ + String str(__length + 1); + + wchar_t* pDst = str.__pValue; + wchar_t* pSrc = __pValue; + + for (; *pSrc != 0; ++pSrc, ++pDst) + { + *pDst = Character::ToUpper(*pSrc); + } + + *pDst = '\0'; + + str.__length = __length; + out = str; + + return E_SUCCESS; +} + +result +String::ToUpperCase(String& out) const +{ + String str(__length + 1); + + wchar_t* pDst = str.__pValue; + wchar_t* pSrc = __pValue; + for (; *pSrc != 0; ++pSrc, ++pDst) + { + *pDst = Character::ToUpperCase(*pSrc); + } + + *pDst = '\0'; + + str.__length = __length; + out = str; + + return E_SUCCESS; +} + +void +String::ToLower(void) +{ + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + String str(__length + 1); + + wchar_t* pDst = str.__pValue; + wchar_t* pSrc = __pValue; + + for (; *pSrc != 0; ++pSrc, ++pDst) + { + *pDst = Character::ToLower(*pSrc); + } + + wcsncpy(__pValue, str.__pValue, __length); + __pValue[__length] = '\0'; + __hash = 0; +} + +void +String::ToLowerCase(void) +{ + if (*__pRefCount > 0) + { + result r = CopyOnWrite(__capacity); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + String str(__length + 1); + + wchar_t* pDst = str.__pValue; + wchar_t* pSrc = __pValue; + + for (; *pSrc != 0; ++pSrc, ++pDst) + { + *pDst = Character::ToLowerCase(*pSrc); + } + + wcsncpy(__pValue, str.__pValue, __length); + __pValue[__length] = '\0'; + __hash = 0; +} + +void +String::ToUpper(void) +{ + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + String str(__length + 1); + + wchar_t* pDst = str.__pValue; + wchar_t* pSrc = __pValue; + + for (; *pSrc != 0; ++pSrc, ++pDst) + { + *pDst = Character::ToUpper(*pSrc); + } + + wcsncpy(__pValue, str.__pValue, __length); + __pValue[__length] = '\0'; + __hash = 0; +} + +void +String::ToUpperCase(void) +{ + if (*__pRefCount > 1) + { + result r = CopyOnWrite(__capacity); + SysTryReturnVoidResult(NID_BASE, r == E_SUCCESS, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + + String str(__length + 1); + + wchar_t* pDst = str.__pValue; + wchar_t* pSrc = __pValue; + + for (; *pSrc != 0; ++pSrc, ++pDst) + { + *pDst = Character::ToUpperCase(*pSrc); + } + + wcsncpy(__pValue, str.__pValue, __length); + __pValue[__length] = '\0'; + __hash = 0; + +} + +void +String::Trim(void) +{ + if (__length == 0) + { + return; + } + + int lastIndex = __length; + int startIndex = 0; + const wchar_t* pStr = __pValue; + + while ((startIndex < lastIndex) && (*(pStr + startIndex) <= L' ')) + { + ++startIndex; + } + + while ((startIndex < lastIndex) && (*(pStr + lastIndex - 1) <= L' ')) + { + --lastIndex; + } + + // trim right + if (lastIndex < __length) + { + Remove(lastIndex, __length - lastIndex); + } + + // trim left + if (startIndex > 0) + { + Remove(0, startIndex); + } +} + +int +String::GetCapacity(void) const +{ + return __capacity; // REMARK: the actual allocated size of buffer is __capacity + 1 +} + +int +String::GetLength(void) const +{ + return __length; +} + +const wchar_t* +String::GetPointer(void) const +{ + return __pValue; +} + + +bool +String::Contains(const String& str) const +{ + SysTryReturn(NID_BASE, str.__length > 0, false, E_INVALID_ARG, + "[%s] Invalid argument is used. The length of str(%d) MUST be greater than 0.", + GetErrorMessage(E_INVALID_ARG), str.__length); + + if (__length == 0) + { + return false; + } + else if ((__length == str.__length) && (*this == str)) + { + return true; + } + + wchar_t* pStart = __pValue; + wchar_t* pEnd = pStart + __length; + while (pStart < pEnd) + { + while (wcsstr(pStart, str.__pValue) != null) + { + return true; + } + ++pStart; + } + + return false; +} + +bool +String::AllocateCapacity(int capacity) +{ + __pValue = new (std::nothrow) wchar_t[capacity + 1]; // + 1 for null character + if (__pValue == null) + { + SysLogException(NID_BASE, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + return false; + } + + __pValue[0] = '\0'; + __pValue[capacity] = '\0'; + __capacity = capacity; + + return true; +} + +bool +String::ExpandCapacity(int minCapacity) +{ + int capacity = (__capacity ? (4 * (((int) (GROWTH_FACTOR * __capacity) - 1) / 4 + 1)) : 0); // nearest multiple of 4 + + if (minCapacity > capacity) + { + capacity = minCapacity; + } + + std::unique_ptr pNewValue(new (std::nothrow) wchar_t[capacity + 1]); // + 1 for null character + SysTryReturn(NID_BASE, pNewValue != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + if (__pValue != null) + { + wmemcpy(pNewValue.get(), __pValue, __length); + pNewValue[__length] = '\0'; + + if (*__pRefCount == 1) + { + delete[] __pValue; + } + else + { + std::unique_ptr pRefCntTemp(new (std::nothrow) int(1)); + SysTryReturn(NID_BASE, pRefCntTemp != null, false, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", + GetErrorMessage(E_OUT_OF_MEMORY)); + (*__pRefCount)--; + __pRefCount = pRefCntTemp.release(); + } + } + __pValue = pNewValue.release(); + __pValue[capacity] = '\0'; + __capacity = capacity; + + return true; +} + +result +String::InitializeToDefault(int capacity) +{ + std::unique_ptr pRefCntTemp(new (std::nothrow) int(1)); + SysTryReturnResult(NID_BASE, pRefCntTemp != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + SysTryReturnResult(NID_BASE, AllocateCapacity(capacity) != false, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __pRefCount = pRefCntTemp.release(); + return E_SUCCESS; +} + +result +String::CopyOnWrite(int capacity) +{ + wchar_t* pValue = __pValue; + std::unique_ptr pRefCntTemp(new (std::nothrow) int(1)); + SysTryReturnResult(NID_BASE, pRefCntTemp != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + SysTryReturnResult(NID_BASE, AllocateCapacity(capacity) != false, E_OUT_OF_MEMORY, "Memory allocation failed."); + + wcsncpy(__pValue, pValue, __length); + __pValue[__length] = '\0'; + --(*__pRefCount); + __pRefCount = pRefCntTemp.release(); + return E_SUCCESS; +} + +void +String::Swap(String& str) +{ + std::swap(__capacity, str.__capacity); + std::swap(__length, str.__length); + std::swap(__hash, str.__hash); + std::swap(__pRefCount, str.__pRefCount); + std::swap(__pValue, str.__pValue); + std::swap(__pStringImpl, str.__pStringImpl); +} + +}} //Tizen::Base diff --git a/src/base/FBaseStringComparer.cpp b/src/base/FBaseStringComparer.cpp new file mode 100644 index 0000000..63ce765 --- /dev/null +++ b/src/base/FBaseStringComparer.cpp @@ -0,0 +1,54 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseStringComparer.cpp + * @brief This is the implementation file for StringComparer class. + * @see String class and Tizen::Base::Collection::IComparer + */ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ + +StringComparer::StringComparer(void) + : __pStringComparerImpl(null) +{ +} + +StringComparer::~StringComparer(void) +{ +} + +result +StringComparer::Compare(const Tizen::Base::Object& obj1, const Tizen::Base::Object& obj2, int& cmp) const +{ + const String* pString1 = dynamic_cast (&obj1); + const String* pString2 = dynamic_cast (&obj2); + SysTryReturn(NID_BASE, (pString1 != null && pString2 != null), E_INVALID_ARG, E_INVALID_ARG, + "[%s] Invalid argument is used. Both of the obj1 and obj2 MUST be String.", GetErrorMessage(E_INVALID_ARG)); + + cmp = String::Compare(*pString1, *pString2); + + return E_SUCCESS; +} + +}} //Tizen::Base diff --git a/src/base/FBaseSys.cpp b/src/base/FBaseSys.cpp new file mode 100644 index 0000000..24375a5 --- /dev/null +++ b/src/base/FBaseSys.cpp @@ -0,0 +1,947 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseSys.cpp + * @brief This file defines the diagnostics types. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBase_Log.h" +#include "FBase_StringConverter.h" +#include "FApp_AppInfo.h" + +using namespace Tizen::Base; +using namespace Tizen::Io; +using namespace Tizen::Base::Collection; +using namespace Tizen::App; + +#ifdef LOG_TAG +#undef LOG_TAG +#define LOG_TAG "OSP_SLP" +#define LOG_TAG_NULL "" +#endif + +static const char LOG_TAG_ASSERT[] = "Assert"; + +bool iniLoaded = false; + +static bool appNameLoaded = false; +static char appName[LOG_MODULE_NAME_LEN_MAX]; + +#define APP_RESERVED(X) NID_APP+X +#define BASE_RESERVED(X) NID_BASE+X +#define CNT_RESERVED(X) NID_CNT+X +#define CTXT_RESERVED(X) NID_CTXT+X +#define GRP_RESERVED(X) NID_GRP+X + +#define IO_RESERVED(X) NID_IO+X +#define LCL_RESERVED(X) NID_LCL+X +#define LOC_RESERVED(X) NID_LOC+X +#define MEDIA_RESERVED(X) NID_MEDIA+X +#define MSG_RESERVED(X) NID_MSG+X + +#define NET_RESERVED(X) NID_NET+X +#define SEC_RESERVED(X) NID_SEC+X +#define SCL_RESERVED(X) NID_SCL+X +#define SYS_RESERVED(X) NID_SYS+X +#define TEL_RESERVED(X) NID_TEL+X + +#define TEXT_RESERVED(X) NID_TEXT+X +#define UI_RESERVED(X) NID_UI+X +#define UIX_RESERVED(X) NID_UIX+X +#define WEB_RESERVED(X) NID_WEB+X + +LogInfo logInfo = +{ + { + //OSP Namespace ID =============================================================== + {NID_APP, "NID_APP", "Tizen::App", true}, + {APP_RESERVED(1) , "RESERVED", "", false}, + {APP_RESERVED(2) , "RESERVED", "", false}, + {APP_RESERVED(3) , "RESERVED", "", false}, + {APP_RESERVED(4) , "RESERVED", "", false}, + {APP_RESERVED(5) , "RESERVED", "", false}, + {APP_RESERVED(6) , "RESERVED", "", false}, + {APP_RESERVED(7) , "RESERVED", "", false}, + {APP_RESERVED(8) , "RESERVED", "", false}, + {APP_RESERVED(9) , "RESERVED", "", false}, + + {NID_BASE, "NID_BASE", "Tizen::Base", true}, + {NID_BASE_COL, "NID_BASE_COL", "Tizen::Base::Collection", true}, + {NID_BASE_RT, "NID_BASE_RT", "Tizen::Base::Runtime", true}, + {NID_BASE_UTIL, "NID_BASE_UTIL", "Tizen::Base::Utility", true}, + {BASE_RESERVED(4) , "RESERVED", "", false}, + {BASE_RESERVED(5) , "RESERVED", "", false}, + {BASE_RESERVED(6) , "RESERVED", "", false}, + {BASE_RESERVED(7) , "RESERVED", "", false}, + {BASE_RESERVED(8) , "RESERVED", "", false}, + {BASE_RESERVED(9) , "RESERVED", "", false}, + + {NID_CNT, "NID_CNT", "Tizen::Content", true}, + {CNT_RESERVED(1) , "RESERVED", "", false}, + {CNT_RESERVED(2) , "RESERVED", "", false}, + {CNT_RESERVED(3) , "RESERVED", "", false}, + {CNT_RESERVED(4) , "RESERVED", "", false}, + {CNT_RESERVED(5) , "RESERVED", "", false}, + {CNT_RESERVED(6) , "RESERVED", "", false}, + {CNT_RESERVED(7) , "RESERVED", "", false}, + {CNT_RESERVED(8) , "RESERVED", "", false}, + {CNT_RESERVED(9) , "RESERVED", "", false}, + + {NID_CTXT, "NID_CTXT", "Tizen::Context", true}, + {CTXT_RESERVED(1) , "RESERVED", "", false}, + {CTXT_RESERVED(2) , "RESERVED", "", false}, + {CTXT_RESERVED(3) , "RESERVED", "", false}, + {CTXT_RESERVED(4) , "RESERVED", "", false}, + {CTXT_RESERVED(5) , "RESERVED", "", false}, + {CTXT_RESERVED(6) , "RESERVED", "", false}, + {CTXT_RESERVED(7) , "RESERVED", "", false}, + {CTXT_RESERVED(8) , "RESERVED", "", false}, + {CTXT_RESERVED(9) , "RESERVED", "", false}, + + {NID_GRP, "NID_GRP", "Tizen::Graphics", true}, + {GRP_RESERVED(1) , "RESERVED", "", false}, + {GRP_RESERVED(2) , "RESERVED", "", false}, + {GRP_RESERVED(3) , "RESERVED", "", false}, + {GRP_RESERVED(4) , "RESERVED", "", false}, + {GRP_RESERVED(5) , "RESERVED", "", false}, + {GRP_RESERVED(6) , "RESERVED", "", false}, + {GRP_RESERVED(7) , "RESERVED", "", false}, + {GRP_RESERVED(8) , "RESERVED", "", false}, + {GRP_RESERVED(9) , "RESERVED", "", false}, + + {NID_IO, "NID_IO", "Tizen::Io", true}, + {IO_RESERVED(1) , "RESERVED", "", false}, + {IO_RESERVED(2) , "RESERVED", "", false}, + {IO_RESERVED(3) , "RESERVED", "", false}, + {IO_RESERVED(4) , "RESERVED", "", false}, + {IO_RESERVED(5) , "RESERVED", "", false}, + {IO_RESERVED(6) , "RESERVED", "", false}, + {IO_RESERVED(7) , "RESERVED", "", false}, + {IO_RESERVED(8) , "RESERVED", "", false}, + {IO_RESERVED(9) , "RESERVED", "", false}, + + {NID_LCL, "NID_LCL", "Tizen::Locales", true}, + {LCL_RESERVED(1) , "RESERVED", "", false}, + {LCL_RESERVED(2) , "RESERVED", "", false}, + {LCL_RESERVED(3) , "RESERVED", "", false}, + {LCL_RESERVED(4) , "RESERVED", "", false}, + {LCL_RESERVED(5) , "RESERVED", "", false}, + {LCL_RESERVED(6) , "RESERVED", "", false}, + {LCL_RESERVED(7) , "RESERVED", "", false}, + {LCL_RESERVED(8) , "RESERVED", "", false}, + {LCL_RESERVED(9) , "RESERVED", "", false}, + + {NID_LOC, "NID_LOC", "Tizen::Locations", true}, + {NID_LOC_CTRL, "NID_LOC_CTRL", "Tizen::Locations::Controls", true}, + {NID_LOC_SVC, "NID_LOC_SVC", "Tizen::Locations::Services", true}, + {LOC_RESERVED(3) , "RESERVED", "", false}, + {LOC_RESERVED(4) , "RESERVED", "", false}, + {LOC_RESERVED(5) , "RESERVED", "", false}, + {LOC_RESERVED(6) , "RESERVED", "", false}, + {LOC_RESERVED(7) , "RESERVED", "", false}, + {LOC_RESERVED(8) , "RESERVED", "", false}, + {LOC_RESERVED(9) , "RESERVED", "", false}, + + {NID_MEDIA, "NID_MEDIA", "Tizen::Media", true}, + {MEDIA_RESERVED(1) , "RESERVED", "", false}, + {MEDIA_RESERVED(2) , "RESERVED", "", false}, + {MEDIA_RESERVED(3) , "RESERVED", "", false}, + {MEDIA_RESERVED(4) , "RESERVED", "", false}, + {MEDIA_RESERVED(5) , "RESERVED", "", false}, + {MEDIA_RESERVED(6) , "RESERVED", "", false}, + {MEDIA_RESERVED(7) , "RESERVED", "", false}, + {MEDIA_RESERVED(8) , "RESERVED", "", false}, + {MEDIA_RESERVED(9) , "RESERVED", "", false}, + + {NID_MSG, "NID_MSG", "Tizen::Messaging", true}, + {MSG_RESERVED(1) , "RESERVED", "", false}, + {MSG_RESERVED(2) , "RESERVED", "", false}, + {MSG_RESERVED(3) , "RESERVED", "", false}, + {MSG_RESERVED(4) , "RESERVED", "", false}, + {MSG_RESERVED(5) , "RESERVED", "", false}, + {MSG_RESERVED(6) , "RESERVED", "", false}, + {MSG_RESERVED(7) , "RESERVED", "", false}, + {MSG_RESERVED(8) , "RESERVED", "", false}, + {MSG_RESERVED(9) , "RESERVED", "", false}, + + {NID_NET, "NID_NET", "Tizen::Net", true}, + {NID_NET_BT, "NID_NET_BT", "Tizen::Net::Bluetooth", true}, + {NID_NET_HTTP, "NID_NET_HTTP", "Tizen::Net::Http", true}, + {NID_NET_NFC, "NID_NET_NFC", "Tizen::Net::Nfc", true}, + {NID_NET_SOCK, "NID_NET_SOCK", "Tizen::Net::Sockets", true}, + {NID_NET_WIFI, "NID_NET_WIFI", "Tizen::Net::Wifi", true}, + {NET_RESERVED(6) , "RESERVED", "", false}, + {NET_RESERVED(7) , "RESERVED", "", false}, + {NET_RESERVED(8) , "RESERVED", "", false}, + {NET_RESERVED(9) , "RESERVED", "", false}, + + {NID_SEC, "NID_SEC", "Tizen::Security", true}, + {NID_SEC_CERT, "NID_SEC_CERT", "Tizen::Security::Cert", true}, + {NID_SEC_CRYPTO, "NID_SEC_CRYPTO", "Tizen::Security::Crypto", true}, + {SEC_RESERVED(3) , "RESERVED", "", false}, + {SEC_RESERVED(4) , "RESERVED", "", false}, + {SEC_RESERVED(5) , "RESERVED", "", false}, + {SEC_RESERVED(6) , "RESERVED", "", false}, + {SEC_RESERVED(7) , "RESERVED", "", false}, + {SEC_RESERVED(8) , "RESERVED", "", false}, + {SEC_RESERVED(9) , "RESERVED", "", false}, + + {NID_SCL, "NID_SCL", "Tizen::Social", true}, + {SCL_RESERVED(1) , "RESERVED", "", false}, + {SCL_RESERVED(2) , "RESERVED", "", false}, + {SCL_RESERVED(3) , "RESERVED", "", false}, + {SCL_RESERVED(4) , "RESERVED", "", false}, + {SCL_RESERVED(5) , "RESERVED", "", false}, + {SCL_RESERVED(6) , "RESERVED", "", false}, + {SCL_RESERVED(7) , "RESERVED", "", false}, + {SCL_RESERVED(8) , "RESERVED", "", false}, + {SCL_RESERVED(9) , "RESERVED", "", false}, + + {NID_SYS, "NID_SYS", "Tizen::System", true}, + {SYS_RESERVED(1) , "RESERVED", "", false}, + {SYS_RESERVED(2) , "RESERVED", "", false}, + {SYS_RESERVED(3) , "RESERVED", "", false}, + {SYS_RESERVED(4) , "RESERVED", "", false}, + {SYS_RESERVED(5) , "RESERVED", "", false}, + {SYS_RESERVED(6) , "RESERVED", "", false}, + {SYS_RESERVED(7) , "RESERVED", "", false}, + {SYS_RESERVED(8) , "RESERVED", "", false}, + {SYS_RESERVED(9) , "RESERVED", "", false}, + + {NID_TEL, "NID_TEL", "Tizen::Telephony", true}, + {TEL_RESERVED(1) , "RESERVED", "", false}, + {TEL_RESERVED(2) , "RESERVED", "", false}, + {TEL_RESERVED(3) , "RESERVED", "", false}, + {TEL_RESERVED(4) , "RESERVED", "", false}, + {TEL_RESERVED(5) , "RESERVED", "", false}, + {TEL_RESERVED(6) , "RESERVED", "", false}, + {TEL_RESERVED(7) , "RESERVED", "", false}, + {TEL_RESERVED(8) , "RESERVED", "", false}, + {TEL_RESERVED(9) , "RESERVED", "", false}, + + {NID_TEXT, "NID_TEXT", "Tizen::Text", true}, + {TEXT_RESERVED(1) , "RESERVED", "", false}, + {TEXT_RESERVED(2) , "RESERVED", "", false}, + {TEXT_RESERVED(3) , "RESERVED", "", false}, + {TEXT_RESERVED(4) , "RESERVED", "", false}, + {TEXT_RESERVED(5) , "RESERVED", "", false}, + {TEXT_RESERVED(6) , "RESERVED", "", false}, + {TEXT_RESERVED(7) , "RESERVED", "", false}, + {TEXT_RESERVED(8) , "RESERVED", "", false}, + {TEXT_RESERVED(9) , "RESERVED", "", false}, + + {NID_UI, "NID_UI", "Tizen::Ui", true}, + {NID_UI_ANIM, "NID_UI_ANIM", "Tizen::Ui::Animations", true}, + {NID_UI_CTRL, "NID_UI_CTRL", "Tizen::Ui::Controls", true}, + {NID_UI_EFFECT, "NID_UI_EFFECT", "Tizen::Ui::Effects", true}, + {NID_UI_IME, "NID_UI_IME", "Tizen::Ui::Ime", true}, + {NID_UI_SCENES, "NID_UI_SCENES", "Tizen::Ui::Scenes", true}, + {UI_RESERVED(6) , "RESERVED", "", false}, + {UI_RESERVED(7) , "RESERVED", "", false}, + {UI_RESERVED(8) , "RESERVED", "", false}, + {UI_RESERVED(9) , "RESERVED", "", false}, + + {NID_UIX, "NID_UIX", "Tizen::Uix", true}, + {NID_UIX_SPEECH, "NID_UIX_SPEECH", "Tizen::Uix::Speech", true}, + {UIX_RESERVED(2) , "RESERVED", "", false}, + {UIX_RESERVED(3) , "RESERVED", "", false}, + {UIX_RESERVED(4) , "RESERVED", "", false}, + {UIX_RESERVED(5) , "RESERVED", "", false}, + {UIX_RESERVED(6) , "RESERVED", "", false}, + {UIX_RESERVED(7) , "RESERVED", "", false}, + {UIX_RESERVED(8) , "RESERVED", "", false}, + {UIX_RESERVED(9) , "RESERVED", "", false}, + + {NID_WEB, "NID_WEB", "Tizen::Web", true}, + {NID_WEB_CTRL, "NID_WEB_CTRL", "Tizen::Web::Controls", true}, + {NID_WEB_JSON, "NID_WEB_JSON", "Tizen::Web::Json", true}, + {WEB_RESERVED(3) , "RESERVED", "", false}, + {WEB_RESERVED(4) , "RESERVED", "", false}, + {WEB_RESERVED(5) , "RESERVED", "", false}, + {WEB_RESERVED(6) , "RESERVED", "", false}, + {WEB_RESERVED(7) , "RESERVED", "", false}, + {WEB_RESERVED(8) , "RESERVED", "", false}, + {WEB_RESERVED(9) , "RESERVED", "", false} + + }, + + // Other properties =========================================================== + false, // consoleOut + false, // fileOut + + true, //platformInfoEnabled; + true, //platformExceptionEnabled; + + true, // applicationInfoEnabled + true, // applicationDebugEnabled + true, // applicationExceptionEnabled + +}; + +void +AppLogInternal(const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + if (!logInfo.applicationInfoEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintLog(static_cast<_LogType>(LOG_INFO), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +AppLogTagInternal(const char* pTag, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + if (!logInfo.applicationInfoEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintLogTag(pTag, static_cast<_LogType>(LOG_INFO), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +AppLogDebugInternal(const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + if (!logInfo.applicationDebugEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintLog(static_cast<_LogType>(LOG_DEBUG), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +AppLogDebugTagInternal(const char* pTag, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + if (!logInfo.applicationDebugEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintLogTag(pTag, static_cast<_LogType>(LOG_DEBUG), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +AppLogExceptionInternal(const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + if (!logInfo.applicationExceptionEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintLog(static_cast<_LogType>(LOG_EXCEPTION), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +AppLogExceptionTagInternal(const char* pTag, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + if (!logInfo.applicationExceptionEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintLogTag(pTag, static_cast<_LogType>(LOG_EXCEPTION), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +AppassertInternal(const char* pFunction, int lineNumber) +{ + char logBody[LOG_LEN_MAX]; + bool platformDebug; + int appDebug; + char logTag[LOG_MODULE_NAME_LEN_MAX]; + + vconf_get_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, &appDebug); + platformDebug = File::IsFileExist( "/opt/etc/.debugmode"); + + snprintf(logTag, LOG_MODULE_NAME_LEN_MAX, "%s", appName); + logTag[LOG_MODULE_NAME_LEN_MAX - 1] = '\0'; + + if( (platformDebug == false) && (appDebug == 0) ) + { + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > App assertion passed due to debug mode off!", pFunction, lineNumber); + ALOG(LOG_ERROR, logTag, logBody); + return; + } + + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > AppAssert!", pFunction, lineNumber); + ALOG(LOG_ERROR, logTag, logBody); + + assert(false); +} + +void +AppassertfInternal(const char* expr, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + char logBody[LOG_LEN_MAX]; + bool platformDebug; + int appDebug; + va_list args; + va_start(args, pFormat); + + vconf_get_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, &appDebug); + platformDebug = File::IsFileExist( "/opt/etc/.debugmode"); + + if( (platformDebug == false) && (appDebug == 0) ) + { + snprintf(logBody, LOG_LEN_MAX, "App assertion passed due to debug mode off! : %s", pFormat); + __PrintLog(static_cast<_LogType>(LOG_USER), pFunction, lineNumber, logBody, args); + va_end(args); + return; + } + + __PrintLog(static_cast<_LogType>(LOG_USER), pFunction, lineNumber, pFormat, args); + + va_end(args); + + assert(false); +} + + +void +SysLogInternal(unsigned long nid, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + if (!logInfo.platformInfoEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintSysLog(static_cast<_LogType>(LOG_INFO), static_cast(nid), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +SysLogExceptionInternal(unsigned long nid, result r, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + SetLastResult(r); + + if (!logInfo.platformExceptionEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintSysLog(static_cast<_LogType>(LOG_EXCEPTION), static_cast(nid), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +SysLogTagInternal(unsigned long nid, const char* pTag, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + va_list args; + + if (!logInfo.platformInfoEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintSysLogTag(pTag, static_cast<_LogType>(LOG_INFO), static_cast(nid), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + +void +SysLogExceptionTagInternal(unsigned long nid, const char* pTag, result r, const char* pFunction, int lineNumber, + const char* pFormat, + ...) +{ + va_list args; + + SetLastResult(r); + + if (!logInfo.platformExceptionEnabled) + { + return; + } + + va_start(args, pFormat); + + __PrintSysLogTag(pTag, static_cast<_LogType>(LOG_EXCEPTION), static_cast(nid), pFunction, lineNumber, pFormat, args); + + va_end(args); +} + + +void +SysAssertInternal(const char* pFileName, int lineNumber, const char* pFunction) +{ + + bool platformDebug; + char logBody[LOG_LEN_MAX]; + + platformDebug = File::IsFileExist( "/opt/etc/.debugmode"); + + if(!platformDebug) + { + return; + } + + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > SysAssert!", pFunction, lineNumber); + + ALOG(LOG_ERROR, LOG_TAG_ASSERT, logBody); + + assert(false); +} + +void +SysAssertfInternal(const char* expr, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + char logBody[LOG_LEN_MAX]; + bool platformDebug; + va_list args; + + platformDebug = File::IsFileExist( "/opt/etc/.debugmode"); + + if(!platformDebug) + { + return; + } + + va_start(args, pFormat); + + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > %s", pFunction, lineNumber, pFormat); + logBody[LOG_LEN_MAX - 1] = '\0'; + + ALOG_VA(LOG_ERROR, LOG_TAG_ASSERT, logBody, args); + + va_end(args); + + assert(false); +} + +void +SysPropagateInternal(const char* pFunction, int lineNumber, unsigned long nid, result r) +{ + char logBody[PROPAGATION_LEN_MAX]; + snprintf(logBody, PROPAGATION_LEN_MAX, "%s (%d). > [%s] Propagating to caller...", pFunction, lineNumber, GetErrorMessage(r)); + + char logTag[LOG_MODULE_NAME_LEN_MAX]; + snprintf(logTag, LOG_MODULE_NAME_LEN_MAX, "%s", __GetModuleName(static_cast(nid))); + + ALOG(LOG_ERROR, logTag, logBody); +} + +void +SysTryReturnResultInternal(unsigned long id, result r, const char* pFunction, int lineNumber, const char* pFormat, ...) +{ + + va_list args; + + SetLastResult(r); + + if (!logInfo.platformExceptionEnabled) + { + return; + } + + if (!iniLoaded) + { + __InitializeLogInfo(); + } + + if (!__GetEnableInfo(static_cast(id))) + { + return; + } + + va_start(args, pFormat); + + char logBody[LOG_LEN_MAX]; + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > [%s] %s", pFunction, lineNumber, GetErrorMessage(r), pFormat); + logBody[LOG_LEN_MAX -1] = '\0'; + + char logTag[LOG_MODULE_NAME_LEN_MAX]; + + snprintf(logTag, LOG_MODULE_NAME_LEN_MAX, "%s", __GetModuleName(static_cast(id))); + logTag[LOG_MODULE_NAME_LEN_MAX - 1] = '\0'; + + ALOG_VA(LOG_ERROR, logTag, logBody, args); + + va_end(args); +} + + + +void +__PrintLog(_LogType type, const char* pFunction, int lineNumber, const char* pFormat, va_list args) +{ + if (!iniLoaded) + { + __InitializeLogInfo(); + } + + char logBody[LOG_LEN_MAX]; + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > %s", pFunction, lineNumber, pFormat); + logBody[LOG_LEN_MAX - 1] = '\0'; + + char logTag[LOG_MODULE_NAME_LEN_MAX]; + + if (!appNameLoaded) + { + appNameLoaded = true; + char* pAppName = _StringConverter::CopyToCharArrayN(_AppInfo::GetAppExecutableName()); + strncpy(appName, pAppName, LOG_MODULE_NAME_LEN_MAX); + delete [] pAppName; + } + snprintf(logTag, LOG_MODULE_NAME_LEN_MAX, "%s", appName); + + logTag[LOG_MODULE_NAME_LEN_MAX - 1] = '\0'; + + switch (type) + { + case static_cast<_LogType>(LOG_INFO): + ALOG_VA(LOG_INFO, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_DEBUG): + ALOG_VA(LOG_DEBUG, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_EXCEPTION): + ALOG_VA(LOG_ERROR, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_USER): + ALOG_VA(LOG_ERROR, logTag, logBody, args); + break; + + default: + ALOG_VA(LOG_DEBUG, LOG_TAG_NULL, logBody, args); + break; + } +} + +void +__PrintLogTag(const char* pTag, _LogType type, const char* pFunction, int lineNumber, const char* pFormat, va_list args) +{ + if (!iniLoaded) + { + __InitializeLogInfo(); + } + + char logBody[LOG_LEN_MAX]; + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > %s", pFunction, lineNumber, pFormat); + logBody[LOG_LEN_MAX -1] = '\0'; + + char logTag[LOG_TAG_LEN_MAX]; + + snprintf(logTag, LOG_TAG_LEN_MAX, "%s", pTag); + logTag[LOG_TAG_LEN_MAX - 1] = '\0'; + + switch (type) + { + case static_cast<_LogType>(LOG_INFO): + ALOG_VA(LOG_INFO, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_DEBUG): + ALOG_VA(LOG_DEBUG, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_EXCEPTION): + ALOG_VA(LOG_ERROR, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_USER): + ALOG_VA(LOG_ERROR, logTag, logBody, args); + break; + + default: + ALOG_VA(LOG_DEBUG, LOG_TAG_NULL, logBody, args); + break; + } +} + + +void +__PrintSysLog(_LogType type, LogID id, const char* pFunction, int lineNumber, const char* pFormat, va_list args) +{ + if (!iniLoaded) + { + __InitializeLogInfo(); + } + + if (!__GetEnableInfo(static_cast(id))) + { + return; + } + + char logBody[LOG_LEN_MAX]; + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > %s", pFunction, lineNumber, pFormat); + logBody[LOG_LEN_MAX -1] = '\0'; + + char logTag[LOG_MODULE_NAME_LEN_MAX]; + + snprintf(logTag, LOG_MODULE_NAME_LEN_MAX, "%s", __GetModuleName(static_cast(id))); + logTag[LOG_MODULE_NAME_LEN_MAX - 1] = '\0'; + + switch (type) + { + case static_cast<_LogType>(LOG_INFO): + LOG_VA(LOG_INFO, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_DEBUG): + LOG_VA(LOG_DEBUG, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_EXCEPTION): + ALOG_VA(LOG_ERROR, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_USER): + ALOG_VA(LOG_ERROR, logTag, logBody, args); + break; + + default: + LOG_VA(LOG_DEBUG, LOG_TAG_NULL, logBody, args); + break; + } +} + +void +__PrintSysLogTag(const char* pTag, _LogType type, LogID id, const char* pFunction, int lineNumber, const char* pFormat, va_list args) +{ + if (!iniLoaded) + { + __InitializeLogInfo(); + } + + if (!__GetEnableInfo(static_cast(id))) + { + return; + } + + char logBody[LOG_LEN_MAX]; + snprintf(logBody, LOG_LEN_MAX, "%s (%d). > %s", pFunction, lineNumber, pFormat); + logBody[LOG_LEN_MAX -1] = '\0'; + + char logTag[LOG_MODULE_NAME_LEN_MAX + LOG_TAG_LEN_MAX]; + + snprintf(logTag, LOG_MODULE_NAME_LEN_MAX + LOG_TAG_LEN_MAX, "%s | %s", __GetModuleName(static_cast(id)), pTag); + logTag[LOG_MODULE_NAME_LEN_MAX + LOG_TAG_LEN_MAX - 1] = '\0'; + + switch (type) + { + case static_cast<_LogType>(LOG_INFO): + LOG_VA(LOG_INFO, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_DEBUG): + LOG_VA(LOG_DEBUG, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_EXCEPTION): + ALOG_VA(LOG_ERROR, logTag, logBody, args); + break; + + case static_cast<_LogType>(LOG_USER): + ALOG_VA(LOG_ERROR, logTag, logBody, args); + break; + + default: + LOG_VA(LOG_DEBUG, LOG_TAG_NULL, logBody, args); + break; + } +} + +char* +__GetModuleName(LogID id) +{ + return logInfo.logTable[id].logModuleName; +} + +bool +__GetEnableInfo(LogID id) +{ + return logInfo.logTable[id].loggingEnabled; +} + +void +__InitializeLogInfo() +{ + iniLoaded = true; + + Registry reg; + + const String regPath(L"/opt/usr/etc/system-log.ini"); + + result r; + + r = reg.Construct(regPath, REG_OPEN_READ_ONLY, 0); + + if (IsFailed(r)) + { + ALOG(LOG_ERROR, LOG_TAG, "[EXCEPTION] opening ini file failed.\n"); + return; + } + + __InitializeLogLevel(reg); + __InitializePlatformModule(reg); +} + +void +__InitializeLogLevel(const Registry& reg) +{ + String sectApp(L"Application"); + String sectPlatform(L"Platform"); + + String entryInfo(L"INFO"); + String entryDebug(L"DEBUG"); + String entryException(L"EXCEPTION"); + + String strYes(L"YES"); + String retString; + + result r; + + r = reg.GetValue(sectApp, entryInfo, retString); + if (IsFailed(r)) + { + ALOG(LOG_ERROR, LOG_TAG, "[EXCEPTION] finding Application/INFO failed.\n"); + return; + } + logInfo.applicationInfoEnabled = retString.Equals(strYes); + retString.Clear(); + + r = reg.GetValue(sectApp, entryDebug, retString); + if (IsFailed(r)) + { + ALOG(LOG_ERROR, LOG_TAG, "[EXCEPTION] finding Application/DEBUG failed.\n"); + return; + } + logInfo.applicationDebugEnabled = retString.Equals(strYes); + retString.Clear(); + + r = reg.GetValue(sectApp, entryException, retString); + if (IsFailed(r)) + { + ALOG(LOG_ERROR, LOG_TAG, "[EXCEPTION] finding Application/EXCEPTION failed.\n"); + return; + } + logInfo.applicationExceptionEnabled = retString.Equals(strYes); + retString.Clear(); + + r = reg.GetValue(sectPlatform, entryInfo, retString); + if (IsFailed(r)) + { + ALOG(LOG_ERROR, LOG_TAG, "[EXCEPTION] finding Platform/INFO failed.\n"); + return; + } + logInfo.platformInfoEnabled = retString.Equals(strYes); + retString.Clear(); + + r = reg.GetValue(sectPlatform, entryException, retString); + if (IsFailed(r)) + { + ALOG(LOG_ERROR, LOG_TAG, "[EXCEPTION] finding Platform/EXCEPTION failed.\n"); + return; + } + logInfo.platformExceptionEnabled = retString.Equals(strYes); + retString.Clear(); +} + +void +__InitializePlatformModule(const Registry& reg) +{ + String strYes(L"YES"); + String retString; + + String sectModule(L"PlatformModules"); + + result r; + + for (int i = 0; i < NID_MAX; i++) + { + String strEntry(logInfo.logTable[i].logIDName); + r = reg.GetValue(sectModule, strEntry, retString); + if (IsFailed(r)) + { + ALOG(LOG_ERROR, LOG_TAG, "[EXCEPTION] finding PlatformModules/%ls failed.\n", strEntry.GetPointer()); + } + else + { + logInfo.logTable[i].loggingEnabled = retString.Equals(strYes); + } + + strEntry.Clear(); + retString.Clear(); + } +} + diff --git a/src/base/FBaseTimeSpan.cpp b/src/base/FBaseTimeSpan.cpp new file mode 100644 index 0000000..729407f --- /dev/null +++ b/src/base/FBaseTimeSpan.cpp @@ -0,0 +1,282 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseTimeSpan.cpp + * @brief This is the implementation file of TimeSpan class. + */ + +#include +#include + +namespace Tizen { namespace Base +{ + +TimeSpan::TimeSpan(const TimeSpan& value) + : __ticks(value.__ticks) + , __pTimeSpanImpl(null) +{ +} + +TimeSpan::TimeSpan(int hours, int minutes, int seconds) +{ + __pTimeSpanImpl = null; + __ticks = CalcTicks(0, hours, minutes, seconds, 0); +} + +TimeSpan::TimeSpan(int days, int hours, int minutes, int seconds) +{ + __pTimeSpanImpl = null; + __ticks = CalcTicks(days, hours, minutes, seconds, 0); +} + +TimeSpan::TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) +{ + __pTimeSpanImpl = null; + __ticks = CalcTicks(days, hours, minutes, seconds, milliseconds); +} + +TimeSpan::TimeSpan(long long ticks) + : __ticks(ticks) + , __pTimeSpanImpl(null) +{ +} + +TimeSpan::~TimeSpan(void) +{ +} + +TimeSpan +TimeSpan::operator +(const TimeSpan& rhs) const +{ + return TimeSpan(__ticks + rhs.__ticks); +} + +TimeSpan +TimeSpan::operator -(const TimeSpan& rhs) const +{ + return TimeSpan(__ticks - rhs.__ticks); +} + +TimeSpan& +TimeSpan::operator =(const TimeSpan& rhs) +{ + if (&rhs != this) + { + __ticks = rhs.__ticks; + } + return *this; +} + +bool +TimeSpan::operator ==(const TimeSpan& rhs) const +{ + return __ticks == rhs.__ticks; +} + +bool +TimeSpan::operator !=(const TimeSpan& rhs) const +{ + return __ticks != rhs.__ticks; +} + +bool +TimeSpan::operator <(const TimeSpan& rhs) const +{ + return __ticks < rhs.__ticks; +} + +bool +TimeSpan::operator >(const TimeSpan& rhs) const +{ + return __ticks > rhs.__ticks; +} + +bool +TimeSpan::operator <=(const TimeSpan& rhs) const +{ + return __ticks <= rhs.__ticks; +} + +bool +TimeSpan::operator >=(const TimeSpan& rhs) const +{ + return __ticks >= rhs.__ticks; +} + +int +TimeSpan::Compare(const TimeSpan& t1, const TimeSpan& t2) +{ + if ((t1.__ticks - t2.__ticks) > 0) + { + return 1; + } + else if ((t1.__ticks - t2.__ticks) < 0) + { + return -1; + } + + return 0; +} + +int +TimeSpan::CompareTo(const TimeSpan& value) const +{ + return TimeSpan::Compare(*this, value); +} + +bool +TimeSpan::Equals(const Object& obj) const +{ + const TimeSpan* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + return *this == *pOther; +} + +TimeSpan +TimeSpan::Duration(void) const +{ + return TimeSpan((__ticks >= 0 ? __ticks : -__ticks)); +} + +int +TimeSpan::GetHashCode(void) const +{ + return(int((__ticks >> 32) ^ ((__ticks >> 32) >> 16)) ^ int((__ticks & 0x0000FFFF))); +} + +TimeSpan +TimeSpan::Negate(void) const +{ + return TimeSpan(-__ticks); +} + +long long +TimeSpan::CalcTicks(int days, int hours, int minutes, int seconds, int milliseconds) +{ + if (days < 0) + { + days = 0; + } + if (hours < 0) + { + hours = 0; + } + if (minutes < 0) + { + minutes = 0; + } + if (seconds < 0) + { + seconds = 0; + } + if (milliseconds < 0) + { + milliseconds = 0; + } + + return (long long) ((NUM_OF_TICKS_IN_DAY * days) + (NUM_OF_TICKS_IN_HOUR * hours) + (NUM_OF_TICKS_IN_MINUTE * minutes) + + (NUM_OF_TICKS_IN_SECOND * seconds) + milliseconds); +} + +long long +TimeSpan::GetDays(void) const +{ + return (long long) (__ticks / NUM_OF_TICKS_IN_DAY); +} + +long long +TimeSpan::GetHours(void) const +{ + long long r = __ticks % NUM_OF_TICKS_IN_DAY; + if (r > 0) + { + return (long long) (r / NUM_OF_TICKS_IN_HOUR); + } + return 0; +} + +long long +TimeSpan::GetMinutes(void) const +{ + long long r = __ticks % NUM_OF_TICKS_IN_DAY; + if (r > 0) + { + r = r % NUM_OF_TICKS_IN_HOUR; + if (r > 0) + { + return (long long) (r / NUM_OF_TICKS_IN_MINUTE); + } + return 0; + } + return 0; +} + +long long +TimeSpan::GetSeconds(void) const +{ + long long r = __ticks % NUM_OF_TICKS_IN_DAY; + if (r > 0) + { + r = r % NUM_OF_TICKS_IN_HOUR; + if (r > 0) + { + r = r % NUM_OF_TICKS_IN_MINUTE; + if (r > 0) + { + return (long long) (r / NUM_OF_TICKS_IN_SECOND); + } + return 0; + } + return 0; + } + return 0; +} + +long long +TimeSpan::GetMilliseconds(void) const +{ + long long r = __ticks % NUM_OF_TICKS_IN_DAY; + if (r > 0) + { + r = r % NUM_OF_TICKS_IN_HOUR; + if (r > 0) + { + r = r % NUM_OF_TICKS_IN_MINUTE; + if (r > 0) + { + r = r % NUM_OF_TICKS_IN_SECOND; + return(r); + } + return 0; + } + return 0; + } + return 0; +} + +long long +TimeSpan::GetTicks(void) const +{ + return(__ticks); +} + +}} //Tizen::Base diff --git a/src/base/FBaseTypes.cpp b/src/base/FBaseTypes.cpp new file mode 100644 index 0000000..776cc56 --- /dev/null +++ b/src/base/FBaseTypes.cpp @@ -0,0 +1,25 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseTypes.cpp + * @brief This file defines the built-in types. + */ + +// Includes +#include + diff --git a/src/base/FBaseUuId.cpp b/src/base/FBaseUuId.cpp new file mode 100644 index 0000000..fc98411 --- /dev/null +++ b/src/base/FBaseUuId.cpp @@ -0,0 +1,380 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUuId.cpp + * @brief This is the implementation file for UuId class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBase_StringConverter.h" +#include + + +namespace Tizen { namespace Base +{ + +const static UUID __INVALID_UUID = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; + +UuId::UuId(void) + : __pUuIdImpl(null) +{ + uuid_clear(this->uuid); +} + +UuId::UuId(const UuId& uuid) + : __pUuIdImpl(null) +{ + uuid_copy(this->uuid, uuid.uuid); +} + +UuId::UuId(const UUID& uuid) + : __pUuIdImpl(null) +{ + memcpy(this->uuid, &uuid, sizeof(this->uuid)); + + ConvertToUuId(this->uuid); +} + +UuId::UuId(const byte uuid[16]) + : __pUuIdImpl(null) +{ + uuid_copy(this->uuid, uuid); +} + +UuId::~UuId(void) +{ +} + +bool +operator ==(const UUID& uuid1, const UuId& uuid2) +{ + byte uuid[16] = {0,}; + memcpy(uuid, &uuid1, sizeof(uuid)); + UuId::ConvertToUuId(uuid); + + int ret = uuid_compare(uuid, uuid2.uuid); + if (ret == 0) + { + return true; + } + else + { + return false; + } +} + +bool +UuId::operator ==(const UuId& uuid) const +{ + int ret = uuid_compare(this->uuid, uuid.uuid); + if (ret == 0) + { + return true; + } + + return false; +} + +bool +operator !=(const UUID& uuid1, const UuId& uuid2) +{ + if (uuid1 == uuid2) + { + return false; + } + else + { + return true; + } +} + +bool +UuId::operator !=(const UuId& uuid) const +{ + if (*this == uuid) + { + return false; + } + else + { + return true; + } +} + +UuId& +UuId::operator =(const UuId& uuid) +{ + if (&uuid != this) + { + uuid_copy(this->uuid, uuid.uuid); + } + return (*this); +} + +bool +UuId::Equals(const Object& obj) const +{ + const UuId* pOther = dynamic_cast(&obj); + + if (pOther == null) + { + return false; + } + + if (*this == *pOther) + { + return true; + } + else + { + return false; + } +} + +int +UuId::GetHashCode(void) const +{ + String str = ToString(); + + return str.GetHashCode(); +} + +String +UuId::ToString(void) const +{ + /* + char tmpuuid[sizeof(UUID)]; + unsigned int x = 0; + unsigned short s1 = 0; + unsigned short s2 = 0; + unsigned char c1[2]; + unsigned char c2[6]; + int pos = 0; + + char pChar[1 + 2 * (sizeof(unsigned long) + sizeof(unsigned short) * 2 + sizeof(unsigned char) * 8) + 4]; + + memcpy(tmpuuid, &(__uuid), sizeof(UUID)); + + memcpy(&x, tmpuuid, sizeof(unsigned long)); + pos += sizeof(unsigned long); + + memcpy(&s1, tmpuuid + pos, sizeof(unsigned short)); + pos += sizeof(unsigned short); + + memcpy(&s2, tmpuuid + pos, sizeof(unsigned short)); + pos += sizeof(unsigned short); + + memcpy(&c1, tmpuuid + pos, sizeof(unsigned char) * 2); + pos += sizeof(unsigned char) * 2; + + memcpy(&c2, tmpuuid + pos, sizeof(unsigned char) * 6); + + sprintf(pChar, "%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x", + x, s1, s2, c1[0], c1[1], c2[0], c2[1], c2[2], c2[3], c2[4], c2[5]); + + return String(pChar); + */ + + char uuid_str[36] = {0,}; + + uuid_unparse(this->uuid, uuid_str); + + return String(uuid_str); +} + +UUID +UuId::ToUUID(void) const +{ + UUID uuid; + byte uuidValue[16] = {0,}; + + uuid_copy(uuidValue, this->uuid); + ConvertToUuId(uuidValue); + + memcpy(&uuid, uuidValue, sizeof(UUID)); + + return uuid; +} + +result +UuId::Parse(const String& str, UuId& uuid) +{ + /* + char c[32] = {0}; + int length = str.GetLength(); + + SysTryReturn(NID_BASE, length == 36, E_INVALID_ARG, E_INVALID_ARG, ("[E_INVALID_ARG] The length of str(%d) MUST be 36."), length); + + SysTryReturn(NID_BASE, !(str[8] != L'-' || str[13] != L'-' || str[18] != L'-' || str[23] != L'-') + , E_INVALID_ARG, E_INVALID_ARG, ("[E_INVALID_ARG] The str(%ls) is not valid UuId type"), str.GetPointer()); + + // str[i] must be one of '0~9' or 'A~F' or 'a~f' + for (int i = 0; i < length; i++) + { + if (str[i] == L'-') + { + if (i == 8 || i == 13 || i == 18 || i == 23) + { + continue; + } + else + { + SysLogException(NID_BASE, E_INVALID_ARG, "[E_INVALID_ARG] The str(%ls) is not valid UuId type", str.GetPointer()); + return E_INVALID_ARG; + } + } + + SysTryReturn(NID_BASE, (str[i] >= '0' && str[i] <= '9') || (str[i] >= 'A' && str[i] <= 'F') || + (str[i] >= 'a' && str[i] <= 'f'), E_INVALID_ARG, E_INVALID_ARG, ("[E_INVALID_ARG] The str(%ls) MUST consist of only alphanumeric characters and '-'."), str.GetPointer()); + } + + char mbstring[length + 1]; + wchar_t wchar_tstring[length + 1]; + + wcsncpy(wchar_tstring, str.GetPointer(), length); + wchar_tstring[length] = 0; + + length = wcstombs(mbstring, wchar_tstring, length); + SysTryReturn(NID_BASE, length == 36, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The str(%ls) is not valid UuId type", str.GetPointer()); + + sscanf(mbstring, + "%c%c%c%c%c%c%c%c-%c%c%c%c-%c%c%c%c-%c%c%c%c-%c%c%c%c%c%c%c%c%c%c%c%c", + &c[0], &c[1], &c[2], &c[3], &c[4], &c[5], &c[6], &c[7], + &c[8], &c[9], &c[10], &c[11], + &c[12], &c[13], &c[14], &c[15], + &c[16], &c[17], &c[18], &c[19], + &c[20], &c[21], &c[22], &c[23], &c[24], &c[25], &c[26], &c[27], &c[28], &c[29], &c[30], &c[31]); + + for (int i = 0; i < 32; ++i) + { + if (c[i] >= 'a') + { + c[i] = (char) (c[i] - 'a' + (char) 10); + } + else if (c[i] >= 'A') + { + c[i] = (char) (c[i] - 'A' + (char) 10); + } + else + { + c[i] -= '0'; + } + } + + uuid.__uuid.x = c[0] * 0x10000000 + + c[1] * 0x1000000 + + c[2] * 0x100000 + + c[3] * 0x10000 + + c[4] * 0x1000 + + c[5] * 0x100 + + c[6] * 0x10 + + c[7]; + uuid.__uuid.s1 = c[8] * 0x1000 + + c[9] * 0x100 + + c[10] * 0x10 + + c[11]; + uuid.__uuid.s2 = c[12] * 0x1000 + + c[13] * 0x100 + + c[14] * 0x10 + + c[15]; + + uuid.__uuid.c[0] = c[16] * 0x10 + c[17]; + uuid.__uuid.c[1] = c[18] * 0x10 + c[19]; + uuid.__uuid.c[2] = c[20] * 0x10 + c[21]; + uuid.__uuid.c[3] = c[22] * 0x10 + c[23]; + uuid.__uuid.c[4] = c[24] * 0x10 + c[25]; + uuid.__uuid.c[5] = c[26] * 0x10 + c[27]; + uuid.__uuid.c[6] = c[28] * 0x10 + c[29]; + uuid.__uuid.c[7] = c[30] * 0x10 + c[31]; + + return E_SUCCESS; + */ + + int length = str.GetLength(); + + SysTryReturnResult(NID_BASE, length == 36, E_INVALID_ARG, "The length of str(%d) MUST be 36.", length); + + SysTryReturnResult(NID_BASE, !(str[8] != L'-' || str[13] != L'-' || str[18] != L'-' || str[23] != L'-') + ,E_INVALID_ARG, "The str(%ls) is not valid UuId type.", str.GetPointer()); + + uuid_t uuidValue; + std::unique_ptr pStr(_StringConverter::CopyToCharArrayN(str)); + SysTryReturnResult(NID_BASE, pStr != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + int ret = uuid_parse(pStr.get(), uuidValue); + + SysTryReturnResult(NID_BASE, ret == 0, E_INVALID_ARG, "The str(%ls) MUST consist of only alphanumeric characters and '-'.", str.GetPointer()); + + uuid_copy(uuid.uuid, uuidValue); + + return E_SUCCESS; +} + +UuId* +UuId::GenerateN(void) +{ + uuid_t out; + UuId* pUuid = new (std::nothrow) UuId(); + if (pUuid == null) + { + SysLogException(NID_BASE, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + return null; + } + + uuid_generate(out); + + uuid_copy(pUuid->uuid, out); + + return pUuid; +} + +UuId +UuId::GetInvalidUuId(void) +{ + UuId invalidUuId(__INVALID_UUID); + return invalidUuId; +} + +void +UuId::ConvertToUuId(byte uuid[16]) +{ + byte value = 0x00; + + for (int i=0; i<2; i++) + { + value = uuid[i]; + uuid[i] = uuid[3-i]; + uuid[3-i] = value; + } + + value = uuid[4]; + uuid[4] = uuid[5]; + uuid[5] = value; + + value = uuid[6]; + uuid[6] = uuid[7]; + uuid[7] = value; +} + +}} //Tizen::Base diff --git a/src/base/FBase_CharacterImpl.cpp b/src/base/FBase_CharacterImpl.cpp new file mode 100644 index 0000000..119bf37 --- /dev/null +++ b/src/base/FBase_CharacterImpl.cpp @@ -0,0 +1,331 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBase_CharacterImpl.cpp + * @brief This is the implementation file for _CharImpl class. + */ + +#include +#include +#include +#include "FBase_CharacterImpl.h" + + +namespace Tizen { namespace Base +{ + +_CharacterImpl::~_CharacterImpl(void) +{ +} + +wchar_t +_CharacterImpl::ToLowerCase(wchar_t ch) +{ + return u_tolower(ch); +} + +wchar_t +_CharacterImpl::ToUpperCase(wchar_t ch) +{ + return u_toupper(ch); +} + +UnicodeCategory +_CharacterImpl::GetUnicodeCategory(wchar_t ch) +{ + if (_CharacterImpl::IsSurrogate(ch)) + { + return UNICODE_SURROGATE; + } + else if (_CharacterImpl::IsModifier(ch)) + { + return UNICODE_MODIFIER; + } + else if (_CharacterImpl::IsArrow(ch)) + { + return UNICODE_ARROW; + } + else if (_CharacterImpl::IsWhitespace(ch)) + { + return UNICODE_SPACE; + } + else if (_CharacterImpl::IsPunctuation(ch)) + { + return UNICODE_PUNCTUATION; + } + else if (_CharacterImpl::IsControl(ch)) + { + return UNICODE_CONTROL; + } + else if (_CharacterImpl::IsMath(ch)) + { + return UNICODE_MATH; + } + else if (_CharacterImpl::IsDigit(ch)) + { + return UNICODE_DIGIT; + } + else if (_CharacterImpl::IsHangul(ch)) + { + return UNICODE_HANGUL; + } + else if (_CharacterImpl::IsCJK(ch)) + { + return UNICODE_HANJA; + } + else if (_CharacterImpl::IsCombining(ch)) + { + return UNICODE_COMBINING; + } + else if (_CharacterImpl::IsLanguage(ch)) + { + return UNICODE_LANGUAGE; + } + else + { + return UNICODE_OTHER; + } +} + +bool +_CharacterImpl::IsDigit(wchar_t ch) +{ + return(u_isdigit(ch) == TRUE); +} + +bool +_CharacterImpl::IsLetter(wchar_t ch) +{ + return(u_isalpha(ch) == TRUE); +} + +int +_CharacterImpl::ToDigit(wchar_t ch, int radix) +{ + return u_digit(ch, radix); +} + +wchar_t +_CharacterImpl::ForDigit(int digit, int radix) +{ + return u_forDigit(digit, radix); +} + +double +_CharacterImpl::GetNumericValue(wchar_t ch) +{ + return u_getNumericValue(ch); +} + +bool +_CharacterImpl::IsDefined(wchar_t ch) +{ + return(u_isdefined(ch) == TRUE); +} + +bool +_CharacterImpl::IsWhitespace(wchar_t ch) +{ + return(u_isWhitespace(ch) == TRUE); +} + +bool +_CharacterImpl::IsTitleCase(wchar_t ch) +{ + return(u_istitle(ch) == TRUE); +} + +wchar_t +_CharacterImpl::ToTitleCase(wchar_t ch) +{ + return(u_totitle(ch)); +} + +bool +_CharacterImpl::IsISOControl(wchar_t ch) +{ + return(u_isISOControl(ch) == TRUE); +} + +bool +_CharacterImpl::IsControl(wchar_t ch) +{ + return(u_iscntrl(ch) == TRUE); +} + +bool +_CharacterImpl::IsPunctuation(wchar_t ch) +{ + return(u_ispunct(ch) == TRUE); +} + +bool +_CharacterImpl::IsSurrogate(wchar_t ch) +{ + if (0xD800 <= ch && ch <= 0xDFFF) + { + return true; + } + else + { + return false; + } +} + +bool +_CharacterImpl::IsArrow(wchar_t ch) +{ + if ((0x2190 <= ch && ch <= 0x21FF) // Arrows + || (0x27F0 <= ch && ch <= 0x27FF) // Supplemental Arrows A + || (0x2900 <= ch && ch <= 0x297F) // Supplemental Arrows B + || (0x2B00 <= ch && ch <= 0x2B11) // white and black arrows + || (0x2B30 <= ch && ch <= 0x2B4C)) // math arrows + { + return true; + } + else + { + return false; + } +} + +bool +_CharacterImpl::IsMath(wchar_t ch) +{ + if (u_charType(ch) == U_MATH_SYMBOL) + { + return true; + } + else + { + return false; + } +} + +bool +_CharacterImpl::IsModifier(wchar_t ch) +{ + if (u_charType(ch) == U_MODIFIER_LETTER) + { + return true; + } + else if (u_charType(ch) == U_MODIFIER_SYMBOL) + { + return true; + } + else + { + return false; + } +} + +bool +_CharacterImpl::IsHangul(wchar_t ch) +{ + if ((0xAC00 <= ch && ch <= 0xD7AF) // Hangul Syllable + || (0x1100 <= ch && ch <= 0x11FF) // Hangul Jamo + || (0x3130 <= ch && ch <= 0x318F)) // Hangul Compatibility Jamo + { + return true; + } + else + { + return false; + } +} + +bool +_CharacterImpl::IsCJK(wchar_t ch) +{ + if ((0x4E00 <= ch && ch <= 0x9FFF) // CJK Unified Ideographs + || (0xF900 <= ch && ch <= 0xFAFF) // CJK Compatibility Ideographs + || (0x3400 <= ch && ch <= 0x4DBF)) // CJK Unified Ideographs, Extension A + { + return true; + } + else + { + return false; + } +} + +bool +_CharacterImpl::IsCombining(wchar_t ch) +{ + if ((0x0300 <= ch && ch <= 0x036F) || (0x20D0 <= ch && ch <= 0x20FF) + || (0x1DC0 <= ch && ch <= 0x1DFF) || (0xFE20 <= ch && ch <= 0xFE2F)) + { + return true; + } + else + { + return false; + } +} +bool +_CharacterImpl::IsLanguage(wchar_t ch) +{ + if ((0x0041 <= ch && ch <= 0x005A) || (0x0061 <= ch && ch <= 0x007A) || (0x0100 <= ch && ch <= 0x024F) + || (0x0250 <= ch && ch <= 0x02AF) // IPA Extensions + || (0x0370 <= ch && ch <= 0x03FF) // Greek + || (0x0400 <= ch && ch <= 0x04FF) // Cyrillic + || (0x0530 <= ch && ch <= 0x058F) // Armenian + || (0x0590 <= ch && ch <= 0x05FF) // Hebrew + || (0x0600 <= ch && ch <= 0x06FF) // Arabic + || (0x0700 <= ch && ch <= 0x074F) // Syriac + || (0x0780 <= ch && ch <= 0x07BF) // Thaana + || (0x0900 <= ch && ch <= 0x0D7F) // Devanagari ~ Malayalam + || (0x0D80 <= ch && ch <= 0x0DFF) // Sinhala + || (0x0E00 <= ch && ch <= 0x0FFF) // Thai, Lao, Tibetan + || (0x1000 <= ch && ch <= 0x109F) // Myanmar + || (0x10A0 <= ch && ch <= 0x10FF) // Georgian + || (0x1100 <= ch && ch <= 0x11FF) // Hangul Jamo + || (0x1200 <= ch && ch <= 0x137F) // Ethiopic + || (0x13A0 <= ch && ch <= 0x13FF) // Cherokee + || (0x1400 <= ch && ch <= 0x167F) // Unified Canadian Aboriginal Syllabics + || (0x1680 <= ch && ch <= 0x169F) // Ogham + || (0x16A0 <= ch && ch <= 0x16FF) // Runic + || (0x1780 <= ch && ch <= 0x17FF) // Khmer + || (0x1800 <= ch && ch <= 0x18AF) // Mongolian + || (0x1E00 <= ch && ch <= 0x1EFF) // Latin Extended Additional + || (0x1F00 <= ch && ch <= 0x1FFF) // Greek Extended + || (0x3040 <= ch && ch <= 0x30FF) // Hiragana, Katakana + || (0x3100 <= ch && ch <= 0x312F) // Bopomofo + || (0x3130 <= ch && ch <= 0x318F) // Hangul Compatibility Jamo + || (0x3190 <= ch && ch <= 0x319F) // Kanbun + || (0x31A0 <= ch && ch <= 0x31BF) // Bopomofo Extended + || (0x3400 <= ch && ch <= 0x4DB5) // CJK Unified Ideographs Extension A + || (0x4E00 <= ch && ch <= 0x9FFF) // CJK Unified Ideographs + || (0xA000 <= ch && ch <= 0xA4CF) // Yi Syllables, Radicals + || (0xAC00 <= ch && ch <= 0xD7A3) // Hangul Syllables + || (0xF900 <= ch && ch <= 0xFAFF) // CJK Compatibility Ideographs + || (0xFB00 <= ch && ch <= 0xFB4F) // Alphabetic Presentation Forms + || (0xFB50 <= ch && ch <= 0xFDFF) // Arabic Presentation Forms-A + || (0xFE70 <= ch && ch <= 0xFEFE) // Arabic Presentation Forms-B + || (0xFF00 <= ch && ch <= 0xFFEF) + ) + { + return true; + } + else + { + return false; + } +} + +}} // Tizen::Base diff --git a/src/base/FBase_CharacterImpl.h b/src/base/FBase_CharacterImpl.h new file mode 100644 index 0000000..7bb83b8 --- /dev/null +++ b/src/base/FBase_CharacterImpl.h @@ -0,0 +1,321 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBase_CharacterImpl.h + * @brief This is the header file for the _CharacterImpl class. + * + * This header file contains the declarations of the _CharacterImpl class. + */ + +#ifndef _FBASE_INTERNAL_CHARACTER_IMPL_H_ +#define _FBASE_INTERNAL_CHARACTER_IMPL_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base +{ + +class _CharacterImpl +{ +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_CharacterImpl(void); + + /** + * Categorizes a Unicode character into a group identified by @n + * one of the UnicodeCategory values. + * + * @since 2.0 + * + * @return A UnicodeCategory value that identifies the group that contains ch + * @param[in] ch The Unicode character to categorize + * + */ + static UnicodeCategory GetUnicodeCategory(wchar_t ch); + + /** + * Converts the input Unicode character to its equivalent lowercase.@n + * Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + * + * @return A lowercase equivalent of the input Unicode character + * @param[in] ch A Unicode character to convert + */ + static wchar_t ToLowerCase(wchar_t ch); + + /** + * Converts the input Unicode character to its equivalent uppercase.@n + * Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + * + * @return An uppercase equivalent of the input Unicode character + * @param[in] ch A Unicode character to convert + */ + static wchar_t ToUpperCase(wchar_t ch); + + /** + * Checks whether the input character is a digit or not. + * + * @since 2.0 + * @return @c true, if the input character is a digit @n + * @c false, otherwise + * @param[in] ch A Unicode character + */ + static bool IsDigit(wchar_t ch); + + /** + * Checks whether the input character is an alphabet or not. + * + * @since 2.0 + * @return @c true, if the input character is an alphabet @n + * @c false, otherwise + * @param[in] ch A Unicode character + */ + static bool IsLetter(wchar_t ch); + + /** + * Checks whether the input character is a lowercase alphabet or not.@n + * Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + * + * @return @c true, if the input character is a lowercase alphabet @n + * @c false, otherwise + * @param[in] ch A Unicode character + */ + static bool IsLowerCase(wchar_t ch); + + /** + * Checks whether the input character is an uppercase alphabet or not.@n + * Unicode characters other than English alphabets are also supported. + * + * @since 2.0 + * + * @return @c true, if the input character is an uppercase alphabet @n + * @c false, otherwise + * @param[in] ch A Unicode character + */ + static bool IsUpperCase(wchar_t ch); + + /** + * Returns the value of the input character in the supplied radix. The value of radix must be between RADIX_MIN and RADIX_MAX. + * + * @since 2.0 + * + * @return ch the character to determine the value + + * @param[in] radix the radix + */ + static int ToDigit(wchar_t ch, int radix); + + /** + * Returns the character which represents the input digit with specified radix. The value of radix must be between RADIX_MIN and RADIX_MAX. + * + * @since 2.0 + * + * @return A wide character value in radix if radix lies between RADIX_MIN and RADIX_MAX; null character (U+0000) otherwise + * @param[in] digit the digit to determine the value + * @param[in] radix the radix + */ + static wchar_t ForDigit(int digit, int radix); + + /** + * Returns the numeric value of the input unicode character. This is used when some numeric values are fractions, negative, or too large for int32_t. + * + * @since 2.0 + * + * @return A double value; -1 For characters without any numeric values in the Unicode Character + * @param[in] ch A Unicode character + */ + static double GetNumericValue(wchar_t ch); + + /** + * Checks whether the input character is defined, which usually means that it is assigned a character in the Unicode. + * + * @since 2.0 + * + * @return @c true, if the Unicode character is an assigned character @n + * @c false, otherwise + * @param[in] ch A Unicode character + */ + static bool IsDefined(wchar_t ch); + + /** + * Checks whether the input character is a whitespace character + * + * @since 2.0 + * + * @return @c true, if the Unicode character is a whitespace character @n + * @c false, otherwise + * @param[in] ch A Unicode character + */ + static bool IsWhitespace(wchar_t ch); + + /** + * Checks whether the input character is a title character + * + * @since 2.0 + * + * @return @c true, if the Unicode character is a title character @n + * @c false, otherwise + * @param[in] ch A Unicode character + */ + static bool IsTitleCase(wchar_t ch); + + /** + * Returns the title case equivalent for the input character if it exists. + * + * @since 2.0 + * + * @return A title case character equivalent for the input character. The character itself is returned if none is defined. + * @param[in] ch A Unicode character + */ + static wchar_t ToTitleCase(wchar_t ch); + + /** + * Checks whether the input character is an ISO control code or not. + * + * @since 2.0 + * + * @return @c true, if the Unicode character is an ISO control character @n + * @c false, otherwise + * @param[in] ch A Unicode character + */ + static bool IsISOControl(wchar_t ch); + + /** + * Checks whether the input character is a control code. + * + * @return @c true, if the input character is a control code @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsControl(wchar_t ch); + + /** + * Returns whether the input character is a punctuation mark or not. + * + * @return @c true, if the input character is a punctuation mark @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsPunctuation(wchar_t ch); + + /** + * Returns whether the input character is the value between + * (0xD800) and (0xF8FF) or not. + * + * @return @c true, if the input character is between (0xD800) and (0xF8FF) @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsSurrogate(wchar_t ch); + + /** + * Checks whether the input character is the arrow code. + * + * @return @c true, if the input character is the arrow code @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsArrow(wchar_t ch); + + /** + * Checks whether the input character is a math code. + * + * @return @c true, if the input character is a math code @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsMath(wchar_t ch); + + /** + * Checks whether the input character is the modifier code. + * + * @return @c true, if the input character is the modifier code @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsModifier(wchar_t ch); + + /** + * Checks whether the input character is an Hangul code. + * + * @return @c true, if the input character is an Hangul code @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsHangul(wchar_t ch); + + /** + * Checks whether the input character is a Chinese code. + * + * @return @c true, if the input character is a Chinese code @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsCJK(wchar_t ch); + + /** + * Checks whether the input character is a Combining code. + * + * @return @c true, if the input character is a Combining code @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsCombining(wchar_t ch); + + /** + * Checks whether the input character is a language code. + * + * @return @c true, if the input character is a language code @n + @c false, otherwise + * @param[in] ch A character code + */ + static bool IsLanguage(wchar_t ch); + +private: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _CharacterImpl(wchar_t value); + + /** + * The implementation of this copy assignment operator is intentionally blank and declared as private to prohibit copying of objects. + * + * @since 2.0 + * @param[in] rhs An instance of %_CharacterImpl + */ + _CharacterImpl& operator =(const _CharacterImpl& rhs); + +}; // _CharacterImpl + +} } // Tizen::Base + +#endif // _FBASE_INTERNAL_CHARACTER_IMPL_H_ diff --git a/src/base/FBase_Exception.cpp b/src/base/FBase_Exception.cpp new file mode 100644 index 0000000..228dd0c --- /dev/null +++ b/src/base/FBase_Exception.cpp @@ -0,0 +1,335 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseExceptionInternal.cpp + * @brief This is the implementation file for Exception. + */ + +#include "FBase_Exception.h" + +const char* ExceptionStrings[] = +{ + "Success", + "OutOfMemoryError", + "IndexOutOfBoundsException", + + "InstanceAlreadyExistsException", + + "IllegalArgumentException", + "IllegalAccessException", + "IllegalStateException", + + "NullPointerException", + + "UndefinedTypeException", + "NotImplementedException", + + "ParseException", + "DataFormatException", + "SystemException", + "IOException", + "NetworkConnectionException", + "ArithmeticException", + "TimeoutException", + "UnknownException", + "UnknownError", + "EndofGeneralExcpetion", + + // base exception + "CreateFailedException", + + "NoSuchInstanceException", + "ComponentNotFoundException", + "MethodNotFoundException", + "InterfaceNotFoundException", + "SectionNotFoundException", + "EntryNotFoundException", + "ValueNotAssignedException", + "InvalidDocumentException", + + "FileLongPathException", + "FileInvalidPathException", + "FileNotFoundException", + "FileAlreadyExistException", + "FileEndOfFileException", + "FilePermissionException", + "FileNotEmptyDirException", + "FileOpenLimitExceededException", + "FileCorruptedException", + "FileVolumeFullException", + "FileQuotaExceededException", + "FileDeviceFailureException", + "FileVolumeNotMountedException", + "FileMediaEjectedException", + "FilePanicException", + + "KeyNotFoundException", + "ActorNotFoundException", + "ContextModelNotFoundException", + "ListenerNotFoundException", + "ChannelNotFoundException", + + "IpcProxyMethodException", + "IpcStubMethodException", + "StubIsAlreadyRunning", + "NoStubFound", + "NoProxyFound", + "NoSuchProxyConnected", + "NoIpcListenerFound", + "NoIpcEventFound", + "IpcUserDataAlreadyExist", + "IpcStubNoUserDataFound", + "IpcAddListenerDenied", + "IpcEventNotFound", + "IpcInterfaceNotFound", + "IpcNoListenerFound", + "IPCAllIpcCallSlotIsUsing", + "IPCNoAvailabeID", + "IpcMsgQueueNotFound", + + "DatabaseErrorException", + "DatabaseTooBigException", + "DatabaseBusyException", + "DatabaseEndOfResultSet", + "DatabaseNotChangedException", + "AppIDAlreadyExist", + "AppIDIsNotExist", + + "EncodingFailedException", + "DecodingFailedException", + + "EndofBaseException", + + + + + // service exception + "ServiceAlreadyRegisteredException", + "XmlParsingException", + "ServiceNotRegisteredException", + "EventSourceNotRegisteredException", + "ServerException", + "InvalidPeerCredentialException", + "UnSupportedProtocolException", + "UnSupportedEncodingException", + "DomException", + "InvalidMessageTypeException", + "NetworkAbortException", + "NetworkAlreadyAbortedException", + "NetworkAbortFailedException", + "EndofServiceException", + + // group exception + "GroupNotFoundException", + "UserNotFoundException", + "ServiceNotFoundException", + "AttributeNotFoundException", + "DuplicateAttributeException", + "AlreadyJoinedGroupException", + "NotJoinedGroupException", + "AlreadyInvitedException", + "InvitationNotFoundException", + "MaxMemberExceededException", + "NotPermittedGenderException", + "CategoryNotFoundException", + "DuplicateJoinRequestException", + "JoinProhibitedException", + "DuplicateGroupNameException", + "EndofGroupException", + + + // security exception + "SignFailedException", + "InvalidSignatureException", + "VersionNotMatchException", + + "AmbiguousCredentialException", + "CredentialNotFoundException", + + "AlreadyUserRegisteredException", + "UserNotRegisteredException", + "AlreadyUserAuthenticatedException", + "UserNotAuthenticatedException", + "UserIDNotMatchedException", + + "EncryptFailedException", + "DecryptFailedException", + "HMACFailedException", + "RandomByteFailedException", + "HashFailedException", + "PasswordNotMatchedException", + + "PrivilegeDeniedException", + + "EndofSecurityException,", + + + // storage exception + "PathNotFoundException", + "PathAlreadyExistException", + + "EndofStorageException", + + // context exception + "ContextModelCountMaxException", + "DataNotFoundException", + "SQLException", + "InvalidSensorCIDException", + "ObjectDataNotFoundException", + "IllegalConditionObjectException", + "IllegalConditionChannelException", + "InvalidModelDefinitionException", + "NoSuchTableException", + "ServiceUnavailableException", + "ContextStorageNotFoundException", + "ContextStorageExistException", + "ContextTypeNotFoundException", + "ContextStorageNotOpenedException", + "ContextStorageNotClosedException", + "ContextElementNotFoundException", + "CursorNotDeletedException", + + "CanNotLaunchServerException", + "CanNotAllocResourceException", + "TooManyOnGoingSessionsException", + "CanNotDecodeException", + "InvalidEncodeTypeException", + "NeedCoProcessorException", + "CoProcessingException", + "CaughtBrokenInternalsException", + "CaughtIncompleteCodeException", + "NotCQPEnabledDeviceNameException", + "CanNotFindEntityException", + "ExceedMaximumBufferLimitException", + "RemoteExecuteQueryException", + + "InvalidHandleException", + "SessionAlreadyInProgressException", + "ExceedMaximumHandleCountException", + "TooManyOnGoingTasksException", + "InvalidCqlStatementException", + "TypeMissMatchingException", + "AlreadyRegisteredException", + "LoadingCsr256FailedException", + "EndofResultSetException", + "NotSupportedOperationException", + "HandleClosedByOtherThreadException", + "RequestCanceledByOtherThreadException", + "QueryExecutionNotCompletedException", + "InvalidCursorObjectException", + "TriggerFiredException", + "InvalidCursorPositionException", + "EmptyCursorObjectException", + "OpenedHandleExistException", + + // context importer exception + "DBConnectionFailedException", + "SQLExecutionFailedException", + + //Rfid exceptions + "TagNotFoundException", + "TagLoginFailedException", + "TagErrorException", + "NoDataOnTagException", + "IncompatibleTagException", + "TagLockedException", + + "EndofContextException", + + // Second life exceptions + "NotLoggedInException", + "BalanceNotReceivedException", + "NotEnoughBalanceException", + "OverflowException", + "OutOfBoundaryException", + "UnsupportedException", + "TeleportInProgressException", + "MovementInProgressException", + "RequestAlreadyInProgressException", + "NoChangeException", + "InventoryDataNotReceivedException", + "MaximumGroupJoinLimitException", + + "EndofSecondlifeException", + +// "CacheFullException", + + // location services exception + "LocationException", + "SecurityException", + "LandmarkException", + "LandmarkMaxNumberExceededException", + "LocationServiceException", + "LocationServiceInterruptedException", + + "EndofLocationException", + + "CacheFullException", + + "EndofEMSClientException", + + // Device Exception + "OSPSyncProfileNotExistException", + "InvalidDeviceInformationException", + "InvalidSequenceNumberException", + "NoLocalDeviceInformationException", + "NoLocalSequenceNumberException", + "NoSuchDeviceException", + "NoSuchOperationException", + "NoDeviceResponseListenerException", + "RequiredParameterMissing", + + // Device Synchronization + "DataSyncNetworkFailureException", + "NoActiveChangeLogException", + "NoActiveSyncSessionException", + "NoSuchAppDataFolderException", + "NoSuchSyncSessionException", + "SyncInProgressException", + "DeviceOperationFailureException", + "DBReadFailureException", + "NoSuchChangeObjectException", + + // Device Management Exception + "NoSuchApplicationIDException", + "NoSuchURIException", + "NoSuchScheduleException", + "NoSuchNodeException", + "NoSuchNodeDataException", + "InvalidParameterException", + + "EndofDeviceException", + + "UndefinedException" // for exception handling +}; + + +/** + * Returns a string representation of the specified exception. It is useful when printing out a caught exception. + * + * @param[in] e exception to query. + */ +const char* +ExceptionToString(Exception e) +{ + if (e < 0 || e > UNDEFINED_EXCEPTION) + { + e = UNDEFINED_EXCEPTION; + } + return ExceptionStrings[EXCEPTION_INDEX(e)]; +} diff --git a/src/base/FBase_NativeError.cpp b/src/base/FBase_NativeError.cpp new file mode 100644 index 0000000..9e97a31 --- /dev/null +++ b/src/base/FBase_NativeError.cpp @@ -0,0 +1,439 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseNativeError.cpp + * @brief This is the implementation file of functions for native error handling. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBase_NativeError.h" +#include +#include "device.h" +#include "sqlite3.h" + + + +using namespace Tizen::Base; + +static int nativeErrorToResultTable[] = +{ +E_SUCCESS, // SUCCESS 0 /* Success, No error */ +E_INVALID_OPERATION, // EPERM 1 /* Operation not permitted */ +E_FILE_NOT_FOUND, // ENOENT 2 /* No such file or directory */ +E_UNKNOWN, // ESRCH 3 /* No such process */ +E_INTERRUPTED, // EINTR 4 /* Interrupted system call */ +E_IO, // EIO 5 /* I/O error */ +E_OBJ_NOT_FOUND, // ENXIO 6 /* No such device or address */ +E_OVERFLOW, // E2BIG 7 /* Argument list too long */ +E_UNKNOWN, // ENOEXEC 8 /* Exec format error */ +E_FILE_NOT_FOUND, // EBADF 9 /* Bad file number */ +E_UNKNOWN, // ECHILD 10 /* No child processes */ +E_UNKNOWN, // EAGAIN 11 /* Try again */ +E_OUT_OF_MEMORY, // ENOMEM 12 /* Out of memory */ +E_ILLEGAL_ACCESS, // EACCES 13 /* Permission denied */ +E_UNKNOWN, // EFAULT 14 /* Bad address */ +E_UNKNOWN, // ENOTBLK 15 /* Block device required */ +E_DEVICE_BUSY, // EBUSY 16 /* Device or resource busy */ +E_FILE_ALREADY_EXIST, // EEXIST 17 /* File exists */ +E_UNKNOWN, // EXDEV 18 /* Cross-device link */ +E_UNKNOWN, // ENODEV 19 /* No such device */ +E_UNKNOWN, // ENOTDIR 20 /* Not a directory */ +E_UNKNOWN, // EISDIR 21 /* Is a directory */ +E_INVALID_ARG, // EINVAL 22 /* Invalid argument */ +E_OVERFLOW, // ENFILE 23 /* File table overflow */ +E_MAX_EXCEEDED, // EMFILE 24 /* Too many open files */ +E_UNKNOWN, // ENOTTY 25 /* Not a typewriter */ +E_UNKNOWN, // ETXTBSY 26 /* Text file busy */ +E_UNKNOWN, // EFBIG 27 /* File too large */ +E_STORAGE_FULL, // ENOSPC 28 /* No space left on device */ +E_ILLEGAL_ACCESS, // ESPIPE 29 /* Illegal seek */ +E_READ_ONLY, // EROFS 30 /* Read-only file system */ +E_UNKNOWN, // EMLINK 31 /* Too many links */ +E_UNKNOWN, // EPIPE 32 /* Broken pipe */ +E_INVALID_DOMAIN, // EDOM 33 /* Math argument out of domain of func */ +E_OUT_OF_RANGE, // ERANGE 34 /* Math result not representable ; +E_UNKNOWN, // EDEADLK 35 /* Resource deadlock would occur */ +E_UNKNOWN, // ENAMETOOLONG 36 /* File name too long */ +E_UNKNOWN, // ENOLCK 37 /* No record locks available */ +E_UNKNOWN, // ENOSYS 38 /* Function not implemented */ +E_UNKNOWN, // ENOTEMPTY 39 /* Directory not empty */ +E_UNKNOWN, // ELOOP 40 /* Too many symbolic links encountered */ +E_WOULD_BLOCK, // EWOULDBLOCK EAGAIN /* Operation would block */ +E_UNKNOWN, // ENOMSG 42 /* No message of desired type */ +E_UNKNOWN, // EIDRM 43 /* Identifier removed */ +E_UNKNOWN, // ECHRNG 44 /* Channel number out of range */ +E_UNKNOWN, // EL2NSYNC 45 /* Level 2 not synchronized */ +E_UNKNOWN, // EL3HLT 46 /* Level 3 halted */ +E_UNKNOWN, // EL3RST 47 /* Level 3 reset */ +E_UNKNOWN, // ELNRNG 48 /* Link number out of range */ +E_UNKNOWN, // EUNATCH 49 /* Protocol driver not attached */ +E_UNKNOWN, // ENOCSI 50 /* No CSI structure available */ +E_UNKNOWN, // EL2HLT 51 /* Level 2 halted */ +E_UNKNOWN, // EBADE 52 /* Invalid exchange */ +E_UNKNOWN, // EBADR 53 /* Invalid request descriptor */ +E_UNKNOWN, // EXFULL 54 /* Exchange full */ +E_UNKNOWN, // ENOANO 55 /* No anode */ +E_UNKNOWN, // EBADRQC 56 /* Invalid request code */ +E_UNKNOWN, // EBADSLT 57 /* Invalid slot */ + +E_UNKNOWN, // EDEADLOCK EDEADLK + +E_UNKNOWN, // EBFONT 59 /* Bad font file format */ +E_UNKNOWN, // ENOSTR 60 /* Device not a stream */ +E_UNKNOWN, // ENODATA 61 /* No data available */ +E_UNKNOWN, // ETIME 62 /* Timer expired */ +E_UNKNOWN, // ENOSR 63 /* Out of streams resources */ +E_UNKNOWN, // ENONET 64 /* Machine is not on the network */ +E_UNKNOWN, // ENOPKG 65 /* Package not installed */ +E_UNKNOWN, // EREMOTE 66 /* Object is remote */ +E_UNKNOWN, // ENOLINK 67 /* Link has been severed */ +E_UNKNOWN, // EADV 68 /* Advertise error */ +E_UNKNOWN, // ESRMNT 69 /* Srmount error */ +E_UNKNOWN, // ECOMM 70 /* Communication error on send */ +E_UNKNOWN, // EPROTO 71 /* Protocol error */ +E_UNKNOWN, // EMULTIHOP 72 /* Multihop attempted */ +E_UNKNOWN, // EDOTDOT 73 /* RFS specific error */ +E_UNKNOWN, // EBADMSG 74 /* Not a data message */ +E_OVERFLOW, // EOVERFLOW 75 /* Value too large for defined data type */ +E_UNKNOWN, // ENOTUNIQ 76 /* Name not unique on network */ +E_UNKNOWN, // EBADFD 77 /* File descriptor in bad state */ +E_UNKNOWN, // EREMCHG 78 /* Remote address changed */ +E_UNKNOWN, // ELIBACC 79 /* Can not access a needed shared library */ +E_UNKNOWN, // ELIBBAD 80 /* Accessing a corrupted shared library */ +E_UNKNOWN, // ELIBSCN 81 /* .lib section in a.out corrupted */ +E_UNKNOWN, // ELIBMAX 82 /* Attempting to link in too many shared libraries */ +E_UNKNOWN, // ELIBEXEC 83 /* Cannot exec a shared library directly */ +E_INVALID_ENCODING_RANGE, // EILSEQ 84 /* Illegal byte sequence */ +E_UNKNOWN, // ERESTART 85 /* Interrupted system call should be restarted */ +E_UNKNOWN, // ESTRPIPE 86 /* Streams pipe error */ +E_UNKNOWN, // EUSERS 87 /* Too many users */ +E_UNKNOWN, // ENOTSOCK 88 /* Socket operation on non-socket */ +E_UNKNOWN, // EDESTADDRREQ 89 /* Destination address required */ +E_UNKNOWN, // EMSGSIZE 90 /* Message too long */ +E_UNKNOWN, // EPROTOTYPE 91 /* Protocol wrong type for socket */ +E_UNKNOWN, // ENOPROTOOPT 92 /* Protocol not available */ +E_UNSUPPORTED_PROTOCOL, // EPROTONOSUPPORT 93 /* Protocol not supported */ +E_UNKNOWN, // ESOCKTNOSUPPORT 94 /* Socket type not supported */ +E_UNSUPPORTED_OPERATION, // EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +E_UNKNOWN, // EPFNOSUPPORT 96 /* Protocol family not supported */ +E_UNKNOWN, // EAFNOSUPPORT 97 /* Address family not supported by protocol */ +E_UNKNOWN, // EADDRINUSE 98 /* Address already in use */ +E_UNKNOWN, // EADDRNOTAVAIL 99 /* Cannot assign requested address */ +E_UNKNOWN, // ENETDOWN 100 /* Network is down */ +E_UNKNOWN, // ENETUNREACH 101 /* Network is unreachable */ +E_UNKNOWN, // ENETRESET 102 /* Network dropped connection because of reset */ +E_UNKNOWN, // ECONNABORTED 103 /* Software caused connection abort */ +E_UNKNOWN, // ECONNRESET 104 /* Connection reset by peer */ +E_UNKNOWN, // ENOBUFS 105 /* No buffer space available */ +E_UNKNOWN, // EISCONN 106 /* Transport endpoint is already connected */ +E_UNKNOWN, // ENOTCONN 107 /* Transport endpoint is not connected */ +E_UNKNOWN, // ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +E_UNKNOWN, // ETOOMANYREFS 109 /* Too many references: cannot splice */ +E_UNKNOWN, // ETIMEDOUT 110 /* Connection timed out */ +E_UNKNOWN, // ECONNREFUSED 111 /* Connection refused */ +E_UNKNOWN, // EHOSTDOWN 112 /* Host is down */ +E_HOST_UNREACHABLE, // EHOSTUNREACH 113 /* No route to host */ +E_UNKNOWN, // EALREADY 114 /* Operation already in progress */ +E_UNKNOWN, // EINPROGRESS 115 /* Operation now in progress */ +E_UNKNOWN, // ESTALE 116 /* Stale NFS file handle */ +E_UNKNOWN, // EUCLEAN 117 /* Structure needs cleaning */ +E_UNKNOWN, // ENOTNAM 118 /* Not a XENIX named type file */ +E_UNKNOWN, // ENAVAIL 119 /* No XENIX semaphores available */ +E_UNKNOWN, // EISNAM 120 /* Is a named type file */ +E_UNKNOWN, // EREMOTEIO 121 /* Remote I/O error */ +E_UNKNOWN, // EDQUOT 122 /* Quota exceeded */ + +E_UNKNOWN, // ENOMEDIUM 123 /* No medium found */ +E_UNKNOWN, // EMEDIUMTYPE 124 /* Wrong medium type */ +E_UNKNOWN, // ECANCELED 125 /* Operation Canceled */ +E_UNKNOWN, // ENOKEY 126 /* Required key not available */ +E_UNKNOWN, // EKEYEXPIRED 127 /* Key has expired */ +E_UNKNOWN, // EKEYREVOKED 128 /* Key has been revoked */ +E_UNKNOWN, // EKEYREJECTED 129 /* Key was rejected by service */ + +/* for robust mutexes */ +E_UNKNOWN, // EOWNERDEAD 130 /* Owner died */ +E_UNKNOWN, // ENOTRECOVERABLE 131 /* State not recoverable */ +}; + +static int sqlErrorToResultTable[] = +{ + E_SUCCESS, // SQLITE_OK 0 /* Successful result */ + E_DATABASE, // SQLITE_ERROR 1 /* SQL error or missing database */ + E_DATABASE, // SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ + E_DATABASE, // SQLITE_PERM 3 /* Access permission denied */ + E_DATABASE, // SQLITE_ABORT 4 /* Callback routine requested an abort */ + E_SERVICE_BUSY, // SQLITE_BUSY 5 /* The database file is locked */ + E_DATABASE, // SQLITE_LOCKED 6 /* A table in the database is locked */ + E_DATABASE, // SQLITE_NOMEM 7 /* A malloc() failed */ + E_DATABASE, // SQLITE_READONLY 8 /* Attempt to write a readonly database */ + E_DATABASE, // SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ + E_DATABASE, // SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ + E_DATABASE, // SQLITE_CORRUPT 11 /* The database disk image is malformed */ + E_DATABASE, // SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ + E_DATABASE, // SQLITE_FULL 13 /* Insertion failed because database is full */ + E_FILE_NOT_FOUND, // SQLITE_CANTOPEN 14 /* Unable to open the database file */ + E_DATABASE, // SQLITE_PROTOCOL 15 /* Database lock protocol error */ + E_DATABASE, // SQLITE_EMPTY 16 /* Database is empty */ + E_DATABASE, // SQLITE_SCHEMA 17 /* The database schema changed */ + E_INVALID_ARG, // SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ + E_DATABASE, // SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ + E_DATABASE, // SQLITE_MISMATCH 20 /* Data type mismatch */ + E_DATABASE, // SQLITE_MISUSE 21 /* Library used incorrectly */ + E_DATABASE, // SQLITE_NOLFS 22 /* Uses OS features not supported on host */ + E_DATABASE, // SQLITE_AUTH 23 /* Authorization denied */ + E_DATABASE, // SQLITE_FORMAT 24 /* Auxiliary database format error */ + E_INVALID_ARG, // SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ + E_DATABASE, // SQLITE_NOTADB 26 /* File opened that is not a database file */ +}; + +static int sqlErrorToDetailResultTable[] = +{ + E_SUCCESS, // SQLITE_OK 0 /* Successful result */ + E_INVALID_ARG, // SQLITE_ERROR 1 /* SQL error or missing database */ + E_SYSTEM, // SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ + E_ILLEGAL_ACCESS, // SQLITE_PERM 3 /* Access permission denied */ + E_UNKNOWN, // SQLITE_ABORT 4 /* Callback routine requested an abort */ + E_OBJECT_LOCKED, // SQLITE_BUSY 5 /* The database file is locked */ + E_OBJECT_LOCKED, // SQLITE_LOCKED 6 /* A table in the database is locked */ + E_OUT_OF_MEMORY, // SQLITE_NOMEM 7 /* A malloc() failed */ + E_ILLEGAL_ACCESS, // SQLITE_READONLY 8 /* Attempt to write a readonly database */ + E_UNKNOWN, // SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ + E_IO, // SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ + E_INVALID_FORMAT, // SQLITE_CORRUPT 11 /* The database disk image is malformed */ + E_SYSTEM, // SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ + E_STORAGE_FULL, // SQLITE_FULL 13 /* Insertion failed because database is full */ + E_FILE_NOT_FOUND, // SQLITE_CANTOPEN 14 /* Unable to open the database file */ + E_UNKNOWN, // SQLITE_PROTOCOL 15 /* Database lock protocol error */ + E_UNKNOWN, // SQLITE_EMPTY 16 /* Database is empty */ + E_INVALID_ARG, // SQLITE_SCHEMA 17 /* The database schema changed */ + E_INVALID_ARG, // SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ + E_INVALID_ARG, // SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ + E_INVALID_ARG, // SQLITE_MISMATCH 20 /* Data type mismatch */ + E_INVALID_OPERATION, // SQLITE_MISUSE 21 /* Library used incorrectly */ + E_SYSTEM, // SQLITE_NOLFS 22 /* Uses OS features not supported on host */ + E_ILLEGAL_ACCESS, // SQLITE_AUTH 23 /* Authorization denied */ + E_INVALID_FORMAT, // SQLITE_FORMAT 24 /* Auxiliary database format error */ + E_INVALID_ARG, // SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ + E_INVALID_FORMAT, // SQLITE_NOTADB 26 /* File opened that is not a database file */ +}; + +result +_NativeError::ConvertNativeErrorToResult(int errNo, const char* pFile, int line, const char* pFunction, bool logNativeErr) +{ + result r = E_UNKNOWN; + + if ((errNo >= 0) && (errNo < (int) (sizeof(nativeErrorToResultTable) / sizeof(nativeErrorToResultTable[0])))) + { + r = nativeErrorToResultTable[errNo]; + } + + if (logNativeErr) + { + SysLog(NID_BASE, "A native error (%d) occurred at (%s:%d).", errNo, pFile, line); + } + + if (E_UNKNOWN == r) + { + SysLogException(NID_BASE, E_UNKNOWN, "Failed to convert native error(%d-%s) to result.", errNo, strerror(errNo)); + } + + return r; +} + +result +_NativeError::ConvertNativeErrorToResult(int errNo, bool logNativeErr) +{ + result r = E_UNKNOWN; + + if ((errNo >= 0) && (errNo < (int) (sizeof(nativeErrorToResultTable) / sizeof(nativeErrorToResultTable[0])))) + { + r = nativeErrorToResultTable[errNo]; + } + + if (logNativeErr) + { + SysLog(NID_BASE, "A native error (%d) occurred.", errNo); + } + + if (E_UNKNOWN == r) + { + SysLogException(NID_BASE, E_UNKNOWN, "Failed to convert native error(%d-%s) to result.", errNo, strerror(errNo)); + } + + return r; +} + +const char* +_NativeError::ConvertNativeErrorToMessage(int errNo, const char* pFile, int line, const char* pFunction) +{ + return GetErrorMessage(ConvertNativeErrorToResult(errNo, pFile, line, pFunction)); +} + +const char* +_NativeError::ConvertNativeErrorToMessage(int errNo) +{ + return GetErrorMessage(__ConvertNativeErrorToResult(errNo)); +} + +result +_NativeError::ConvertNativeSystemErrorToResult(int err) +{ + switch (err) + { + case SYSTEM_INFO_ERROR_INVALID_PARAMETER: + return E_INVALID_ARG; + //case SYSTEM_INFO_ERROR_INTERNAL: return E_SYSTEM; + //case SYSTEM_INFO_ERROR_OUT_OF_MEMORY: return E_OUT_OF_MEMORY; + //case SYSTEM_INFO_ERROR_IO : return E_IO; + } + + return E_UNKNOWN; +} + +result +_NativeError::ConvertNativeDeviceErrorToResult(int err) +{ + switch (err) + { +// case DEVICE_ERROR_UNKNOWN: return E_SYSTEM; + case DEVICE_ERROR_INVALID_PARAMETER: + return E_INVALID_ARG; + } + + return E_UNKNOWN; +} + +result +_NativeError::ConvertNativePowerErrorToResult(int err) +{ + switch (err) + { +// case POWER_ERROR_UNKNOWN: return E_SYSTEM; + case POWER_ERROR_INVALID_PARAMETER: + return E_INVALID_ARG; + } + + return E_UNKNOWN; +} + +result +_NativeError::ConvertNativeAlarmErrorToResult(int err) +{ + switch (err) + { + case ERR_ALARM_INVALID_PARAM: + return E_INVALID_ARG; + + case ERR_ALARM_INVALID_ID: + return E_INVALID_ARG; + + case ERR_ALARM_INVALID_REPEAT: + return E_INVALID_ARG; + + case ERR_ALARM_INVALID_TIME: + return E_INVALID_ARG; + + case ERR_ALARM_INVALID_DATE: + return E_INVALID_ARG; + + case ERR_ALARM_NO_SERVICE_NAME: + return E_INVALID_ARG; + + case ERR_ALARM_SYSTEM_FAIL: + return E_SYSTEM; + } + + return E_UNKNOWN; +} + +result +_NativeError::ConvertNativeHapticErrorToResult(int err) +{ + switch (err) + { + //case HAPTIC_ERROR_UNKNOWN: return E_SYSTEM; + //case HAPTIC_ERROR_INVALID_PARAMETER: return E_INVALID_ARG; + //case HAPTIC_ERROR_OPENED_DEVICE: return E_INVALID_STATE; + } + + return E_UNKNOWN; +} + +result +_NativeError::ConvertNativeTelephonyErrorToResult(int err) +{ + switch (err) + { + /* deprecated on SLP SDK RC 11 */ +// case TELEPHONY_ERROR_INTERNAL: return E_SYSTEM; +// case TELEPHONY_ERROR_INVALID_PARAMETER: return E_INVALID_ARG; +// case TELEPHONY_ERROR_OUT_OF_SERVICE: return E_SERVICE_DEACTIVATED; +// case TELEPHONY_ERROR_OUT_OF_MEMORY: return E_OUT_OF_MEMORY; + } + + return E_UNKNOWN; +} + +result +_NativeError::ConvertNativeSoundManagerErrorToResult(int err) +{ + switch (err) + { +// case SOUND_MANAGER_NO_PLAYING_SOUND: return E_SYSTEM; +// case SOUND_MANAGER_INVALID_PARAMETER: return E_INVALID_ARG; +// case SOUND_MANAGER_INVALID_OPERATION: return E_INVALID_OPERATION; +// case SOUND_MANAGER_OUT_OF_MEMORY: return E_OUT_OF_MEMORY; + } + + return E_UNKNOWN; +} + +result +_NativeError::ConvertNativeSqliteErrorToResult(int err) +{ + result r = E_UNKNOWN; + + if ((err >= 0) && (err < (int) (sizeof(sqlErrorToResultTable) / sizeof(sqlErrorToResultTable[0])))) + { + r = sqlErrorToResultTable[err]; + } + + return r; +} + +result +_NativeError::ConvertNativeSqliteErrorToDetailResult(int err) +{ + result r = E_UNKNOWN; + + if ((err >= 0) && (err < (int) (sizeof(sqlErrorToDetailResultTable) / sizeof(sqlErrorToDetailResultTable[0])))) + { + r = sqlErrorToDetailResultTable[err]; + } + + return r; +} + diff --git a/src/base/FBase_StringConverter.cpp b/src/base/FBase_StringConverter.cpp new file mode 100644 index 0000000..05d8133 --- /dev/null +++ b/src/base/FBase_StringConverter.cpp @@ -0,0 +1,59 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FBase_StringConverter.cpp +* @brief This is the implementation for _StringConverter class. +*/ + +#include +#include +#include +#include "FBase_StringConverter.h" +#include + + + +namespace Tizen { namespace Base +{ + +char* +_StringConverter::CopyToCharArrayN(const String& str) +{ + return CopyToCharArrayN(str.GetPointer()); +} + +char* +_StringConverter::CopyToCharArrayN(const wchar_t* pValue) +{ + char* pRet = null; + + int len = wcstombs(0, pValue, 0); + SysTryReturn(NID_BASE, len != -1, null, E_INVALID_ARG, "[%s] Invalid argument is used. Invalid string.", + GetErrorMessage(E_INVALID_ARG)); + + pRet = new (std::nothrow) char[len + 1]; + SysTryReturn(NID_BASE, pRet != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", + GetErrorMessage(E_OUT_OF_MEMORY)); + + len = wcstombs(pRet, pValue, len); + pRet[len] = 0; + + return pRet; +} + +}} //Tizen::Base diff --git a/src/base/collection/FBaseColArrayList.cpp b/src/base/collection/FBaseColArrayList.cpp new file mode 100644 index 0000000..a523413 --- /dev/null +++ b/src/base/collection/FBaseColArrayList.cpp @@ -0,0 +1,733 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColArrayList.cpp + * @brief This is the implementation for ArrayList class. + */ + +#include +#include + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class _ArrayListEnumerator + * @brief This is an implementation of IEnumerator for ArrayList. + */ +class _ArrayListEnumerator + : public IBidirectionalEnumerator + , public Object +{ +public: + _ArrayListEnumerator(const ArrayList& list, int modCount); + virtual ~_ArrayListEnumerator(void); + + virtual Object* GetCurrent(void) const; + virtual result MoveNext(void); + virtual result Reset(void); + + virtual result MovePrevious(); + virtual result ResetLast(); + +private: + const ArrayList& __list; + int __modCount; + int __position; +}; + +_ArrayListEnumerator::_ArrayListEnumerator(const ArrayList& list, int modCount) + : __list(list) + , __modCount(modCount) + , __position(-1) +{ +} + +_ArrayListEnumerator::~_ArrayListEnumerator(void) +{ +} + +Object* +_ArrayListEnumerator::GetCurrent(void) const +{ + SysTryReturn(NID_BASE_COL, (__modCount == __list.__modCount), null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, ((__position >= 0) && (__position < __list.__count)), null, E_INVALID_OPERATION, "[%s] Current position(%d) is before the first element or past the last element.", GetErrorMessage(E_INVALID_OPERATION), __position); + + SetLastResult(E_SUCCESS); + + return __list.__pObjArray[__position]; +} + +result +_ArrayListEnumerator::MoveNext(void) +{ + SysTryReturnResult(NID_BASE_COL, (__modCount == __list.__modCount), E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + if ((__position + 1) >= static_cast< int >(__list.__count)) + { + return E_OUT_OF_RANGE; + } + else + { + __position++; + } + + return E_SUCCESS; +} + +result +_ArrayListEnumerator::Reset(void) +{ + SysTryReturnResult(NID_BASE_COL, (__modCount == __list.__modCount), E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + __position = -1; + return E_SUCCESS; +} + + +result +_ArrayListEnumerator::MovePrevious(void) +{ + SysTryReturnResult(NID_BASE_COL, (__modCount == __list.__modCount), E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + SysTryReturnResult(NID_BASE_COL, __position > 0, E_OUT_OF_RANGE, "Reached start of the list, no previous element."); + + __position--; + + return E_SUCCESS; +} + +result +_ArrayListEnumerator::ResetLast(void) +{ + SysTryReturnResult(NID_BASE_COL, (__modCount == __list.__modCount), E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + __position = __list.__count; + return E_SUCCESS; +} + +ArrayList::ArrayList(DeleterFunctionType deleter) + : __capacity(0) + , __count(0) + , __pObjArray(null) + , __modCount(0) + , __pComparer(null) + , __deleter(deleter) + , __pArrayListImpl(null) +{ +} + +result +ArrayList::Construct(int capacity) +{ + SysTryReturnResult(NID_BASE_COL, capacity >= 0, E_INVALID_ARG, "The capacity(%d) MUST be greater than or equal to 0.", capacity); + + result r = SetCapacity(capacity); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + return E_SUCCESS; +} + +result +ArrayList::Construct(const ICollection& collection) +{ + result r = AddItems(collection); + SysTryCatch(NID_BASE_COL, r == E_SUCCESS, , r, "[%s] Propagating.", GetErrorMessage(r)); + + return r; + +CATCH: + delete[] __pObjArray; + __pObjArray = null; + + return r; +} + +ArrayList::~ArrayList(void) +{ + RemoveAll(); + delete[] __pObjArray; +} + +result +ArrayList::Add(Object* pObj) +{ + SysTryReturnResult(NID_BASE_COL, pObj != null, E_INVALID_ARG, "Invalid argument used. The pObj is null"); + + if (__count >= __capacity) + { + result r = SetCapacity(__capacity + DEFAULT_CAPACITY); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + __pObjArray[__count++] = pObj; + + __modCount++; + + return E_SUCCESS; +} + +result +ArrayList::AddItems(const ICollection& collection) +{ + result r = E_SUCCESS; + + int insertingCount = collection.GetCount(); + if (insertingCount <= 0) + { + return E_SUCCESS; + } + + if (insertingCount > (__capacity - __count)) + { + r = SetCapacity(__count + insertingCount); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturnResult(NID_BASE_COL, pEnum != null, GetLastResult(), "Propagating."); + __modCount++; + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + Object* pItem = pEnum->GetCurrent(); + SysTryReturnResult(NID_BASE_COL, pItem != null, GetLastResult(), "Propagating."); + + __pObjArray[__count++] = pItem; + } + + return E_SUCCESS; +} + +IEnumerator* +ArrayList::GetEnumeratorN(void) const +{ + return GetBidirectionalEnumeratorN(); +} + +IBidirectionalEnumerator* +ArrayList::GetBidirectionalEnumeratorN(void) const +{ + std::unique_ptr< _ArrayListEnumerator > pEnum(new (std::nothrow) _ArrayListEnumerator(*this, __modCount)); + SysTryReturn(NID_BASE_COL, pEnum != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum.release(); +} + +const Object* +ArrayList::GetAt(int index) const +{ + SysTryReturn(NID_BASE_COL, index >= 0 && index < __count, null, E_OUT_OF_RANGE, "[%s] The index(%d) MUST be greater than or equal to 0 and less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + SetLastResult(E_SUCCESS); + return __pObjArray[index]; +} + +Object* +ArrayList::GetAt(int index) +{ + const Object* pObj = (static_cast< const ArrayList* >(this))->GetAt(index); + return const_cast< Object* >(pObj); +} + +IList* +ArrayList::GetItemsN(int startIndex, int count) const +{ + result r = E_SUCCESS; + SysTryReturn(NID_BASE_COL, startIndex >= 0 && count >= 0, null, E_OUT_OF_RANGE, "[%s] Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), startIndex, count); + SysTryReturn(NID_BASE_COL, startIndex < __count, null, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + SysTryReturn(NID_BASE_COL, count <= __count && (startIndex + count <= __count), null, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, count, __count); + + std::unique_ptr< ArrayList > pList(new (std::nothrow) ArrayList()); + SysTryReturn(NID_BASE_COL, pList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pList->Construct(count); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + memcpy(pList->__pObjArray, __pObjArray + startIndex, sizeof(Object*) * count); + pList->__count = count; + + SetLastResult(E_SUCCESS); + return pList.release(); +} + +result +ArrayList::IndexOf(const Object& obj, int& index) const +{ + return IndexOf(obj, 0, __count, index); +} + +result +ArrayList::IndexOf(const Object& obj, int startIndex, int& index) const +{ + SysTryReturnResult(NID_BASE_COL, startIndex >= 0 && startIndex < __count, E_OUT_OF_RANGE, "The startIndex(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", startIndex, __count); + + return IndexOf(obj, startIndex, (__count - startIndex), index); +} + +result +ArrayList::IndexOf(const Object& obj, int startIndex, int count, int& index) const +{ + SysTryReturnResult(NID_BASE_COL, startIndex >= 0 && count >= 0, E_OUT_OF_RANGE, "Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", startIndex, count); + SysTryReturnResult(NID_BASE_COL, startIndex < __count, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be less than the number of elements(%d).", startIndex, __count); + SysTryReturnResult(NID_BASE_COL, count <= __count && (startIndex + count <= __count), E_OUT_OF_RANGE, + "The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", startIndex, count, __count); + + int arrayListCount = startIndex + count; + for (int i = startIndex; i < arrayListCount; i++) + { + if (__pObjArray[i]->Equals(obj)) + { + index = i; + return E_SUCCESS; + } + } + + return E_OBJ_NOT_FOUND; +} + +result +ArrayList::LastIndexOf(const Object& obj, int& index) const +{ + for (int i = (__count - 1); i >= 0; i--) + { + if (__pObjArray[i]->Equals(obj)) + { + index = i; + return E_SUCCESS; + } + } + + return E_OBJ_NOT_FOUND; +} + +result +ArrayList::InsertAt(Object* pObj, int index) +{ + SysTryReturnResult(NID_BASE_COL, pObj != null, E_INVALID_ARG, "Invalid argument used. The pObj is null"); + SysTryReturnResult(NID_BASE_COL, index >= 0 && index <= __count, E_OUT_OF_RANGE, "The index(%d) MUST be greater than or equal to 0, and less than or equal to the number of elements(%d).", index, __count); + + if (__count >= __capacity) + { + result r = SetCapacity(__capacity + DEFAULT_CAPACITY); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + memmove(__pObjArray + index + 1, __pObjArray + index, sizeof(Object*) * (__count - index)); + + __count++; + __modCount++; + __pObjArray[index] = pObj; + + return E_SUCCESS; +} + +result +ArrayList::InsertItemsFrom(const ICollection& collection, int startIndex) +{ + SysTryReturnResult(NID_BASE_COL, startIndex >= 0 && startIndex <= __count, E_OUT_OF_RANGE, "The startIndex(%d) MUST be greater than or equal to 0, and less than or equal to the number of elements(%d).", startIndex, __count); + + result r = E_SUCCESS; + int insertingCount = collection.GetCount(); + + if (insertingCount <= 0) + { + return E_SUCCESS; + } + + if (insertingCount > (__capacity - __count)) + { + r = SetCapacity(__count + insertingCount); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + memmove(__pObjArray + startIndex + insertingCount, __pObjArray + startIndex, sizeof(Object*) * (__count - startIndex)); + __count += insertingCount; + + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturnResult(NID_BASE_COL, pEnum != null, GetLastResult(), "Propagating."); + + __modCount++; + + Object* pItem = null; + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + pItem = pEnum->GetCurrent(); + SysTryReturnResult(NID_BASE_COL, pItem != null, GetLastResult(), "Propagating."); + + __pObjArray[startIndex++] = pItem; + } + + return E_SUCCESS; +} + +result +ArrayList::Remove(const Object& obj) +{ + int index = 0; + result r = IndexOf(obj, index); + if (IsFailed(r)) + { + return E_OBJ_NOT_FOUND; + } + else + { + return RemoveAt(index); + } + +} + +result +ArrayList::RemoveAt(int index) +{ + SysTryReturnResult(NID_BASE_COL, index < __count && index >= 0, E_OUT_OF_RANGE, "The index MUST be greater than or equal to 0, and less than the number of elements(%d).", index, __count); + + __modCount++; + __count--; + + __deleter(__pObjArray[index]); + + memmove(__pObjArray + index, __pObjArray + index + 1, sizeof(Object*) * (__count - index)); + + return E_SUCCESS; +} + +result +ArrayList::RemoveItems(int startIndex, int count) +{ + SysTryReturnResult(NID_BASE_COL, startIndex >= 0 && count >= 0, E_OUT_OF_RANGE, "Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", startIndex, count); + SysTryReturnResult(NID_BASE_COL, startIndex < __count, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be less than the number of elements(%d).", startIndex, __count); + SysTryReturnResult(NID_BASE_COL, count <= __count && (startIndex + count <= __count), E_OUT_OF_RANGE, + "The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", startIndex, count, __count); + + if (count > 0) + { + __modCount++; + __count -= count; + + int i = 0; + + int arrayListCount = startIndex + count; + for (i = startIndex; i < arrayListCount; i++) + { + __deleter(__pObjArray[i]); + } + + memmove(__pObjArray + startIndex, __pObjArray + arrayListCount, sizeof(Object*) * (__count - startIndex)); + } + + return E_SUCCESS; +} + +result +ArrayList::RemoveItems(const ICollection& collection) +{ + result r = E_SUCCESS; + + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturnResult(NID_BASE_COL, pEnum != null, GetLastResult(), "Propagating."); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + Object* pItem = pEnum->GetCurrent(); + SysTryReturnResult(NID_BASE_COL, pItem != null, GetLastResult(), "Propagating."); + + r = Remove(*pItem); + SysTryLog(NID_BASE_COL, !IsFailed(r), "[%s] Propagating.", GetErrorMessage(r)); + } + return E_SUCCESS; +} + +void +ArrayList::RemoveAll() +{ + for (int i = 0; i < __count; i++) + { + __deleter(__pObjArray[i]); + __pObjArray[i] = null; + } + + __count = 0; + __modCount++; +} + +result +ArrayList::SetAt(Object* pObj, int index) +{ + SysTryReturnResult(NID_BASE_COL, pObj != null, E_INVALID_ARG, "Invalid argument used. The pObj is null"); + SysTryReturnResult(NID_BASE_COL, index >= 0 && index < __count, E_OUT_OF_RANGE, "The index(%d) MUST be greater than or equal to 0, less than the number of elements(%d).", index, __count); + + __modCount++; + + __deleter(__pObjArray[index]); + + __pObjArray[index] = pObj; + + return E_SUCCESS; +} + +result +ArrayList::SetCapacity(int newCapacity) +{ + SysTryReturnResult(NID_BASE_COL, (newCapacity >= 0), E_INVALID_ARG, "The newCapacity(%d) MUST be greater than or equal to 0.", newCapacity); + + if (__capacity == newCapacity) + { + return E_SUCCESS; + } + + Object** pNewArray = null; + if (newCapacity > 0) + { + pNewArray = new (std::nothrow) Object*[newCapacity]; + SysTryReturn(NID_BASE_COL, pNewArray != null, E_OUT_OF_MEMORY, E_OUT_OF_RANGE, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + if (__pObjArray != null) + { + int count = __count < newCapacity ? __count : newCapacity; + memcpy(pNewArray, __pObjArray, sizeof(Object*) * count); + } + } + if (__pObjArray != null) + { + delete[] __pObjArray; + } + + if (__count > newCapacity) + { + __count = newCapacity; + __modCount++; + } + __pObjArray = pNewArray; + __capacity = newCapacity; + + return E_SUCCESS; +} + +result +ArrayList::Sort(const IComparer& comparer) +{ + if (__count == 0) + { + return E_SUCCESS; + } + + __pComparer = const_cast< IComparer* >(&comparer); + result r = QuickSort(0, (__count - 1)); + if (IsFailed(r)) + { + SysLogException(NID_BASE_COL, r, "[%s] Propagating.", GetErrorMessage(r)); + __pComparer = null; + + return r; + } + + return E_SUCCESS; +} + +void +ArrayList::Trim(void) +{ + result r = E_SUCCESS; + r = SetCapacity(__count); + if (IsFailed(r) == true) + { + SetLastResult(r); + } +} + +int +ArrayList::GetCapacity(void) const +{ + return __capacity; +} + +int +ArrayList::GetCount(void) const +{ + return __count; +} + +bool +ArrayList::Contains(const Object& obj) const +{ + for (int i = 0; i < __count; i++) + { + if (__pObjArray[i]->Equals(obj)) + { + return true; + } + } + + return false; +} + +bool +ArrayList::ContainsAll(const ICollection& collection) const +{ + result r = E_SUCCESS; + SetLastResult(r); + + if (collection.GetCount() == 0) + { + return true; + } + + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturn(NID_BASE_COL, pEnum != null, false, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, false, r, "[%s] Propagating.", GetErrorMessage(r)); + + Object* pItem = pEnum->GetCurrent(); + SysTryReturn(NID_BASE_COL, pItem != null, false, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + if (!Contains(*pItem)) + { + return false; + } + } + + return true; +} + +bool +ArrayList::Equals(const Object& obj) const +{ + if (&obj == this) + { + return true; + } + + const ArrayList* pOther = dynamic_cast< const ArrayList* >(&obj); + if (pOther == null) + { + return false; + } + else if (__count != pOther->__count) + { + return false; + } + else + { + for (int i = 0; i < __count; i++) + { + if (!(__pObjArray[i]->Equals(*(pOther->__pObjArray[i])))) + { + return false; + } + } + } + + return true; +} + +int +ArrayList::GetHashCode(void) const +{ + int hash = 0; + for (int i = 0; i < __count; i++) + { + hash += __pObjArray[i]->GetHashCode(); + } + + return hash; +} + +DeleterFunctionType +ArrayList::GetDeleter(void) const +{ + return __deleter; +} + +result +ArrayList::QuickSort(int startIndex, int endIndex) +{ + result r = E_SUCCESS; + + if (startIndex < endIndex) + { + int middleIndex = 0; + int i = startIndex - 1; + int j = endIndex + 1; + + while (true) + { + int compareResult = 1; + + while ((compareResult > 0) && (j > static_cast< int >(startIndex))) + { + j--; + r = __pComparer->Compare(*(__pObjArray[j]), *(__pObjArray[startIndex]), compareResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + compareResult = -1; + while ((compareResult < 0) && (i < endIndex)) + { + i++; + r = __pComparer->Compare(*(__pObjArray[i]), *(__pObjArray[startIndex]), compareResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + if (i < j) + { + Object* pTemp = __pObjArray[j]; + __pObjArray[j] = __pObjArray[i]; + __pObjArray[i] = pTemp; + } + else + { + middleIndex = j; + break; + } + } + + r = QuickSort(startIndex, middleIndex); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + r = QuickSort(middleIndex + 1, endIndex); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + return r; +} + +void +ArrayList::SetDeleter(DeleterFunctionType deleter) +{ + __deleter = deleter; +} + +}}} // Tizen::Base::Collection diff --git a/src/base/collection/FBaseColHashMap.cpp b/src/base/collection/FBaseColHashMap.cpp new file mode 100644 index 0000000..9ced1a4 --- /dev/null +++ b/src/base/collection/FBaseColHashMap.cpp @@ -0,0 +1,934 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColHashMap.cpp + * @brief This is the implementation for HashMap class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class _HashMapEntry + * @brief This is an entry for HashMap class. + */ +class _HashMapEntry + : public MapEntry +{ +public: + /** + * This is the constructor. + * + * @param[in] pKey A key to be included in this entry. It can not be @c null. + * @param[in] pValue A value to be included in this entry. It can not be @c null. + * @param[in] pNext A pointer to the next entry + * @param[in] hash An hash value of the key + */ + _HashMapEntry(Object* pKey, Object* pValue, _HashMapEntry* pNext, int hash); + + /** + * This is the destructor. + */ + virtual ~_HashMapEntry(void); + + virtual const Object* GetKey(void) const; + virtual const Object* GetValue(void) const; + + int hash; + _HashMapEntry* pNext; + + friend class HashMap; + friend class _HashMapEnumerator; + +}; + +_HashMapEntry::_HashMapEntry(Object* pKey, Object* pValue, _HashMapEntry* pNextEntry, int h) + : MapEntry(*pKey, *pValue) + , hash(h) + , pNext(pNextEntry) +{ +} + +_HashMapEntry::~_HashMapEntry(void) +{ +} + +const Object* +_HashMapEntry::GetKey(void) const +{ + return _pKey; +} + +const Object* +_HashMapEntry::GetValue(void) const +{ + return _pValue; +} + +/** + * @class _HashMapDefaultComparer + * @brief This is an implementation of IComparer for HashMap. + */ +class _HashMapDefaultComparer + : public IComparer + , public Object +{ +public: + /** + * This is the default constructor. + */ + _HashMapDefaultComparer(void); + + /** + * This is the destructor. + */ + virtual ~_HashMapDefaultComparer(void); + + virtual result Compare(const Object& obj1, const Object& obj2, int& cmp) const; + +}; + +_HashMapDefaultComparer::_HashMapDefaultComparer(void) +{ +} + +_HashMapDefaultComparer::~_HashMapDefaultComparer(void) +{ +} + +result +_HashMapDefaultComparer::Compare(const Object& obj1, const Object& obj2, int& cmp) const +{ + if (obj1.Equals(obj2)) + { + cmp = 0; + } + else + { + cmp = 1; + } + + return E_SUCCESS; +} + +/** + * @class _HashMapDefaultProvider + * @brief This is an implementation of IHashCodeProvider for HashMap. + */ +class _HashMapDefaultProvider + : public IHashCodeProvider + , public Object +{ +public: + /** + * This is the default constructor. + */ + _HashMapDefaultProvider(void) {} + + /** + * This is the destructor. + */ + virtual ~_HashMapDefaultProvider(void) {} + + /** + * This method returns the hash code of the specified object. + * + * @return See the comment above. + * @see Tizen::Base::Object::GetHashCode + */ + using Object::GetHashCode; + virtual int GetHashCode(const Object& obj) const + { + return obj.GetHashCode(); + } +}; + +/** + * @class _HashMapEnumerator + * @brief This is an implementation of IMapEnumerator for HashMap. + */ +class _HashMapEnumerator + : public IMapEnumerator + , public Object +{ +public: + /** + * This is the constructor. + * + * @param[in] map A map to enumerate + * @param[in] modCount modification count to detect the change of map + */ + _HashMapEnumerator(const HashMap& map, int modCount); + + /** + * This is the destructor. + */ + virtual ~_HashMapEnumerator(void); + + /** + * This method returns the current object in the map, + * or it returns @c null if some exception occurs. + * + * @return See the comment above. + * @exception E_SUCCESS - This method is successful. + * @exception E_INVALID_OPERATION - The current state of the instance prohibits the execution of the specified operation.@n + *   This enumerator is currently positioned before the first element + * or past the last element or the map is modified after this enumerator is created. + * @exception E_OUT_OF_MEMORY - Failed to allocate required/requested memory. + * @remarks The specific error code can be accessed by GetLastResult() method. + * @see GetLastResult() + */ + virtual Object* GetCurrent(void) const; + + /** + * This method advances this enumerator to the next elements of the map. + * When this enumerator is first created or after call to Reset(), + * the first call to MoveNext() positions this enumerator to the first elements in the map. + * + * @return The error code. + * @exception E_SUCCESS - This method is successful. + * @exception E_INVALID_OPERATION - The current state of the instance prohibits the execution of the specified operation.@n + *   The map is modified after this enumerator is created. + * @exception E_OUT_OF_RANGE - This enumerator has passed the end of the map. + * @see Reset + */ + virtual result MoveNext(void); + + /** + * The method positions this enumerator before the first elements in the map. + * + * @return The error code. + * @exception E_SUCCESS - This method is successful. + * @exception E_INVALID_OPERATION - The current state of the instance prohibits the execution of the specified operation.@n + *   The map is modified after this enumerator is created. + */ + virtual result Reset(void); + + /** + * This method returns the current key in the map, + * or it returns @c null if some exception occurs. + * + * @return See the comment above. + * @exception E_SUCCESS - This method is successful. + * @exception E_INVALID_OPERATION - The current state of the instance prohibits the execution of the specified operation.@n + *   This enumerator is currently positioned before the first element or + * past the last element or the map is modified after the enumerator is created. + * @remarks The specific error code can be accessed by GetLastResult() method. + * @see GetLastResult() + */ + virtual Object* GetKey(void) const; + + /** + * This method returns the current value in the map, + * or it returns @c null if some exception occurs. + * + * @return See the comment above. + * @exception E_SUCCESS - This method is successful. + * @exception E_INVALID_OPERATION - The current state of the instance prohibits the execution of the specified operation.@n + *   This enumerator is currently positioned before the first element or + * past the last element or the map is modified after the enumerator is created. + * @remarks The specific error code can be accessed by GetLastResult() method. + * @see GetLastResult() + */ + virtual Object* GetValue(void) const; + +private: + const HashMap& __map; + int __modCount; + _HashMapEntry* __pEntry; + int __index; + +}; + +_HashMapEnumerator::_HashMapEnumerator(const HashMap& map, int modCount) + : __map(map) + , __modCount(modCount) + , __pEntry(null) + , __index(-1) +{ +} + +_HashMapEnumerator::~_HashMapEnumerator(void) +{ +} + +Object* +_HashMapEnumerator::GetCurrent(void) const +{ + SysTryReturn(NID_BASE_COL, (__modCount == __map.__modCount), null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, (__pEntry != null), null, E_INVALID_OPERATION, "[%s] Invalid position(pEntry is null).", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __pEntry; +} + +result +_HashMapEnumerator::MoveNext(void) +{ + SysTryReturnResult(NID_BASE_COL, (__modCount == __map.__modCount), E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + if ((null != __pEntry) && (__pEntry->pNext != null)) + { + __pEntry = __pEntry->pNext; + return E_SUCCESS; + } + else + { + while (++__index < __map.__capacity) + { + __pEntry = __map.__pTable[__index]; + if (null != __pEntry) + { + return E_SUCCESS; + } + } + } + + return E_OUT_OF_RANGE; +} + +result +_HashMapEnumerator::Reset(void) +{ + SysTryReturnResult(NID_BASE_COL, (__modCount == __map.__modCount), E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + __index = -1; + __pEntry = null; + + return E_SUCCESS; +} + +Object* +_HashMapEnumerator::GetKey(void) const +{ + SysTryReturn(NID_BASE_COL, (__modCount == __map.__modCount), null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, (null != __pEntry), null, E_INVALID_OPERATION, "[%s] Invalid position(pEntry is null).", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __pEntry->_pKey; +} + +Object* +_HashMapEnumerator::GetValue(void) const +{ + SysTryReturn(NID_BASE_COL, (__modCount == __map.__modCount), null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, (null != __pEntry), null, E_INVALID_OPERATION, "[%s] Invalid position(pEntry is null).", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __pEntry->_pValue; +} + +const float HashMap::DEFAULT_LOAD_FACTOR = 0.75; + +HashMap::HashMap(DeleterFunctionType deleter) + : __pTable(null) + , __count(0) + , __capacity(0) + , __loadFactor(0) + , __threshold(0) + , __pProvider(null) + , __pComparer(null) + , __needToRemoveProviderComparer(false) + , __modCount(0) + , __deleter(deleter) + , __pHashMapImpl(null) +{ +} + +HashMap::~HashMap(void) +{ + if (null != __pTable) + { + Reset(); + delete[] __pTable; + } + + if (__needToRemoveProviderComparer) + { + delete __pProvider; + delete __pComparer; + } +} + +result +HashMap::Construct(int capacity, float loadFactor) +{ + SysTryReturnResult(NID_BASE_COL, capacity >= 0, E_INVALID_ARG, "The capacity(%d) MUST be greater than or equal to 0.", capacity); + SysTryReturnResult(NID_BASE_COL, loadFactor >= 0, E_INVALID_ARG, "The loadFactor(%f) MUST be greater than or equal to 0.0.", loadFactor); + + std::unique_ptr< IHashCodeProvider > pProvider(new (std::nothrow) _HashMapDefaultProvider()); + SysTryReturnResult(NID_BASE_COL, pProvider != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + std::unique_ptr< IComparer > pComparer(new (std::nothrow) _HashMapDefaultComparer()); + SysTryReturnResult(NID_BASE_COL, pComparer != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __needToRemoveProviderComparer = true; + + result r = Construct(capacity, loadFactor, *(pProvider.release()), *(pComparer.release())); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + return r; +} + +result +HashMap::Construct(const IMap& map, float loadFactor) +{ + SysTryReturnResult(NID_BASE_COL, loadFactor >= 0, E_INVALID_ARG, "The loadFactor(%f) MUST be greater than or equal to 0.0.", loadFactor); + + std::unique_ptr< IHashCodeProvider > pProvider(new (std::nothrow) _HashMapDefaultProvider()); + SysTryReturnResult(NID_BASE_COL, pProvider != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + std::unique_ptr< IComparer > pComparer(new (std::nothrow) _HashMapDefaultComparer()); + SysTryReturnResult(NID_BASE_COL, pComparer != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __needToRemoveProviderComparer = true; + + result r = Construct(map, loadFactor, *(pProvider.release()), *(pComparer.release())); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + return r; +} + +result +HashMap::Construct(int capacity, float loadFactor, const IHashCodeProvider& provider, const IComparer& comparer) +{ + SysTryReturnResult(NID_BASE_COL, capacity >= 0, E_INVALID_ARG, "The capacity(%d) MUST be greater than or equal to 0.", capacity); + SysTryReturnResult(NID_BASE_COL, loadFactor >= 0, E_INVALID_ARG, "The loadFactor(%f) MUST be greater than or equal to 0.0.", loadFactor); + + int newCapacity = 0; + if (capacity == 0) + { + newCapacity = DEFAULT_CAPACITY; + } + else + { + newCapacity = 1; + while (newCapacity < capacity) + { + newCapacity <<= 1; + } + } + + float newLoadFactor = 0; + if (Float::Compare(loadFactor, 0) == 0) + { + newLoadFactor = DEFAULT_LOAD_FACTOR; + } + else + { + newLoadFactor = loadFactor; + } + + int newThreshold = static_cast< int >(newCapacity * newLoadFactor); + std::unique_ptr< IHashCodeProvider > pProvider(const_cast< IHashCodeProvider* >(&provider)); + std::unique_ptr< IComparer > pComparer(const_cast< IComparer* >(&comparer)); + std::unique_ptr< _HashMapEntry*[] > pTable(new (std::nothrow) _HashMapEntry*[newCapacity]); + SysTryReturnResult(NID_BASE_COL, pTable != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + memset(pTable.get(), null, sizeof(*(pTable.get())) * newCapacity); + + __capacity = newCapacity; + __loadFactor = newLoadFactor; + __threshold = newThreshold; + __pProvider = pProvider.release(); + __pComparer = pComparer.release(); + __pTable = pTable.release(); + + return E_SUCCESS; +} + +result +HashMap::Construct(const IMap& map, float loadFactor, const IHashCodeProvider& provider, const IComparer& comparer) +{ + SysTryReturnResult(NID_BASE_COL, (loadFactor >= 0), E_INVALID_ARG, "The loadFactor(%f) MUST be greater than or equal to 0.0.", loadFactor); + + result r = E_SUCCESS; + + Float flObj(loadFactor); + if (flObj.Equals(Float(static_cast< float >(0)))) + { + loadFactor = DEFAULT_LOAD_FACTOR; + } + + int capacity = static_cast< int >(map.GetCount() / loadFactor) + 1; + + r = Construct(capacity, loadFactor, provider, comparer); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + r = AddAll(map); + SysTryCatch(NID_BASE_COL, r == E_SUCCESS, , r, "[%s] Propagating.", GetErrorMessage(r)); + return r; + +CATCH: + DeleterFunctionType deleter = GetDeleter(); + SetDeleter(SingleObjectDeleter); + Reset(); + SetDeleter(deleter); + + delete[] __pTable; + __pTable = null; + + if (__needToRemoveProviderComparer) + { + delete __pProvider; + delete __pComparer; + } + + __capacity = 0; + __pProvider = null; + __pComparer = null; + + return r; +} + +result +HashMap::Add(Object* pKey, Object* pValue) +{ + SysTryReturnResult(NID_BASE_COL, pKey != null , E_INVALID_ARG, "Invalid argument used. The pKey is null"); + SysTryReturnResult(NID_BASE_COL, pValue != null, E_INVALID_ARG, "Invalid argument used. The pValue is null"); + + int hash = Hash(*pKey); + int i = hash & (__capacity - 1); + + // check whether the pKey is found or not in this map. + SysTryReturnResult(NID_BASE_COL, !(ContainsKey(*pKey)), E_OBJ_ALREADY_EXIST, "The key is already exist in this collection."); + + // pKey is not found. + _HashMapEntry* pNewEntry = new (std::nothrow) _HashMapEntry(pKey, pValue, __pTable[i], hash); + SysTryReturnResult(NID_BASE_COL, pNewEntry != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __pTable[i] = pNewEntry; + __modCount++; + + if (__count++ >= __threshold) + { + result r = Resize(__capacity * 2); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + return E_SUCCESS; +} + +IEnumerator* +HashMap::GetEnumeratorN(void) const +{ + std::unique_ptr< _HashMapEnumerator > pEnum(new (std::nothrow) _HashMapEnumerator(*this, __modCount)); + SysTryReturn(NID_BASE_COL, pEnum != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum.release(); +} + +IMapEnumerator* +HashMap::GetMapEnumeratorN(void) const +{ + return dynamic_cast< IMapEnumerator* >(GetEnumeratorN()); +} + +const Object* +HashMap::GetValue(const Object& key) const +{ + result r = E_OBJ_NOT_FOUND; + + int hash = Hash(key); + int i = hash & (__capacity - 1); + + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + r = __pComparer->Compare(key, *(pEntry->_pKey), cmpResult); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + if (cmpResult == 0) // key is found + { + SetLastResult(E_SUCCESS); + return pEntry->_pValue; + } + } + } + + SetLastResult(E_OBJ_NOT_FOUND); + return null; +} + +Object* +HashMap::GetValue(const Object& key) +{ + const Object* pObj = (static_cast< const HashMap* >(this))->GetValue(key); + return const_cast< Object* >(pObj); +} + +IList* +HashMap::GetKeysN(void) const +{ + result r = E_SUCCESS; + + std::unique_ptr< ArrayList > pList(new (std::nothrow) ArrayList()); + SysTryReturn(NID_BASE_COL, pList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pList->Construct(__count); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < __capacity; i++) + { + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + r = pList->Add(pEntry->_pKey); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + } + } + + SetLastResult(E_SUCCESS); + return pList.release(); +} + +IList* +HashMap::GetValuesN(void) const +{ + result r = E_SUCCESS; + + std::unique_ptr< ArrayList > pList(new (std::nothrow) ArrayList()); + SysTryReturn(NID_BASE_COL, pList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pList->Construct(__count); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < __capacity; i++) + { + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + r = pList->Add(pEntry->_pValue); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + } + } + + SetLastResult(E_SUCCESS); + return pList.release(); +} + +result +HashMap::Remove(const Object& key) +{ + result r = E_OBJ_NOT_FOUND; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + _HashMapEntry* pPrev = __pTable[i]; + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + r = __pComparer->Compare(key, *(pEntry->_pKey), cmpResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, E_INVALID_ARG, "The input argument is invalid"); + + if (cmpResult == 0) + { + __modCount++; + if (pPrev == pEntry) + { + __pTable[i] = pEntry->pNext; + } + else + { + pPrev->pNext = pEntry->pNext; + } + + __deleter(pEntry->_pKey); + __deleter(pEntry->_pValue); + + delete pEntry; + + __count--; + return E_SUCCESS; + } + } + pPrev = pEntry; + } + + return E_OBJ_NOT_FOUND; +} + +void +HashMap::RemoveAll(void) +{ + if (__count > 0) + { + __modCount++; + Reset(); + __count = 0; + } +} + +result +HashMap::SetValue(const Object& key, Object* pValue) +{ + SysTryReturnResult(NID_BASE_COL, pValue != null, E_INVALID_ARG, "Invalid argument used. The pValue is null"); + + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + int cmpResult = -1; + + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + r = __pComparer->Compare(key, *(pEntry->_pKey), cmpResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, E_INVALID_ARG, "Translating [%s] into [%s]", GetErrorMessage(r), GetErrorMessage(E_INVALID_ARG)); + + if (cmpResult == 0) // _pKey is found -> change _pValue. + { + __deleter(pEntry->_pValue); + + pEntry->_pValue = pValue; + break; + } + } + } + + if (cmpResult != 0) + { + r = E_OBJ_NOT_FOUND; + } + + __modCount++; + + return r; +} + +int +HashMap::GetCount(void) const +{ + return __count; +} + +bool +HashMap::ContainsKey(const Object& key) const +{ + int hash = Hash(key); + int i = hash & (__capacity - 1); + + SetLastResult(E_SUCCESS); + + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + result r = __pComparer->Compare(key, *(pEntry->_pKey), cmpResult); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, false, E_INVALID_ARG, "Translating [%s] into [%s]", GetErrorMessage(r), GetErrorMessage(E_INVALID_ARG)); + + if (cmpResult == 0) + { + return true; + } + } + } + + return false; +} + +bool +HashMap::ContainsValue(const Object& value) const +{ + for (int i = 0; i < __capacity; i++) + { + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (value.Equals(*(pEntry->_pValue))) + { + return true; + } + } + } + + return false; +} + +bool +HashMap::Equals(const Object& obj) const +{ + const HashMap* pOther = dynamic_cast< const HashMap* >(&obj); + if (pOther == null) // obj is not HashMap + { + return false; + } + else if (pOther == this) + { + return true; + } + else if (__count != pOther->__count) + { + return false; + } + else + { + const Object* pOtherValue = null; + for (int i = 0; i < __capacity; i++) + { + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + pOtherValue = pOther->GetValue(*(pEntry->_pKey)); + if (pOtherValue == null) + { + return false; + } + if (!(pEntry->_pValue->Equals(*pOtherValue))) + { + return false; + } + } + } + } + + return true; +} + +int +HashMap::GetHashCode(void) const +{ + int hash = 0; + + for (int i = 0; i < __capacity; i++) + { + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + hash += pEntry->_pKey->GetHashCode(); + hash += pEntry->_pValue->GetHashCode(); + } + } + + return hash; +} + +DeleterFunctionType +HashMap::GetDeleter(void) const +{ + return __deleter; +} + +result +HashMap::AddAll(const IMap& map) +{ + result r = E_SUCCESS; + + std::unique_ptr< IMapEnumerator > pMapEnum(map.GetMapEnumeratorN()); + SysTryReturnResult(NID_BASE_COL, pMapEnum != null, GetLastResult(), "Propagating."); + + while ((r = pMapEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + Object* pKey = pMapEnum->GetKey(); + SysTryReturnResult(NID_BASE_COL, pKey != null, GetLastResult(), "Propagating."); + + Object* pValue = pMapEnum->GetValue(); + SysTryReturnResult(NID_BASE_COL, pValue != null, GetLastResult(), "Propagating."); + + int hash = Hash(*pKey); + int i = hash & (__capacity - 1); + _HashMapEntry* pNewEntry = new (std::nothrow) _HashMapEntry(pKey, pValue, __pTable[i], hash); + SysTryReturnResult(NID_BASE_COL, pNewEntry != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __pTable[i] = pNewEntry; + __count++; + } + + return E_SUCCESS; +} + +int +HashMap::Hash(const Object& obj) const +{ + int h = __pProvider->GetHashCode(obj); + + h ^= (h >> 20) ^ (h >> 12); + + return h ^ (h >> 7) ^ (h >> 4); +} + +result +HashMap::Resize(int newCapacity) +{ + _HashMapEntry** pNewTable = new (std::nothrow) _HashMapEntry*[newCapacity]; + SysTryReturnResult(NID_BASE_COL, pNewTable != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + memset(pNewTable, null, sizeof(*pNewTable) * newCapacity); + + for (int i = 0; i < __capacity; i++) + { + _HashMapEntry* pNext = null; + int index = 0; + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pNext) + { + pNext = pEntry->pNext; + + index = pEntry->hash & (newCapacity - 1); + pEntry->pNext = pNewTable[index]; + pNewTable[index] = pEntry; + } + } + + delete[] __pTable; + __pTable = pNewTable; + __capacity = newCapacity; + __threshold = static_cast< int >(__capacity * __loadFactor); + + return E_SUCCESS; +} + +void +HashMap::Reset(void) +{ + for (int i = 0; i < __capacity; i++) + { + _HashMapEntry* pNext = null; + for (_HashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pNext) + { + pNext = pEntry->pNext; + + // Check the deallocate variable + __deleter(pEntry->_pKey); + __deleter(pEntry->_pValue); + + delete pEntry; + } + + __pTable[i] = null; + } +} + +void +HashMap::SetDeleter(DeleterFunctionType deleter) +{ + __deleter = deleter; +} +} } } // Tizen::Base::Collectionn diff --git a/src/base/collection/FBaseColLinkedList.cpp b/src/base/collection/FBaseColLinkedList.cpp new file mode 100644 index 0000000..d893149 --- /dev/null +++ b/src/base/collection/FBaseColLinkedList.cpp @@ -0,0 +1,976 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColLinkedList.cpp + * @brief This is the implementation for LinkedList class. + */ + +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +class _ListNode + : public Object +{ +public: + _ListNode(void); + virtual ~_ListNode(void); + + _ListNode* pPrev; + _ListNode* pNext; + Object* pObj; + _ListNode* pNextBlock; + +}; + +_ListNode::_ListNode(void) + : pPrev(null) + , pNext(null) + , pObj(null) + , pNextBlock(null) +{ +} + +_ListNode::~_ListNode(void) +{ +} + +class _LinkedListEnumerator + : public IBidirectionalEnumerator + , public Object +{ +public: + _LinkedListEnumerator(const LinkedList& list, int modCount); + + virtual ~_LinkedListEnumerator(void); + + virtual Object* GetCurrent(void) const; + virtual result MoveNext(void); + virtual result Reset(void); + + virtual result MovePrevious(); + virtual result ResetLast(); + +private: + const LinkedList& __list; + _ListNode* __pNode; + int __modCount; + +}; + +_LinkedListEnumerator::_LinkedListEnumerator(const LinkedList& list, int modCount) + : __list(list) + , __pNode(null) + , __modCount(modCount) +{ +} + +_LinkedListEnumerator::~_LinkedListEnumerator(void) +{ +} + +Object* +_LinkedListEnumerator::GetCurrent(void) const +{ + SysTryReturn(NID_BASE_COL, __modCount == __list.__modCount, null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, __pNode != null, null, E_INVALID_OPERATION, "[%s] Current position is before the first element or past the last element.", GetErrorMessage(E_INVALID_OPERATION)); + SetLastResult(E_SUCCESS); + return __pNode->pObj; +} + +result +_LinkedListEnumerator::MoveNext(void) +{ + SysTryReturnResult(NID_BASE_COL, __modCount == __list.__modCount, E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + if (__pNode == null) + { + __pNode = __list.__pListHead; + if (__pNode == null) + { + return E_OUT_OF_RANGE; + } + } + else + { + if (__pNode->pNext != null) + { + __pNode = __pNode->pNext; + } + else + { + return E_OUT_OF_RANGE; + } + } + + return E_SUCCESS; +} + +result +_LinkedListEnumerator::Reset(void) +{ + SysTryReturnResult(NID_BASE_COL, __modCount == __list.__modCount, E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + __pNode = null; + return E_SUCCESS; +} + +result +_LinkedListEnumerator::MovePrevious(void) +{ + SysTryReturnResult(NID_BASE_COL, __modCount == __list.__modCount, E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + if (__pNode == null) + { + __pNode = __list.__pListTail; + if (__pNode == null) + { + return E_OUT_OF_RANGE; + } + } + else + { + if (__pNode->pPrev != null) + { + __pNode = __pNode->pPrev; + } + else + { + return E_OUT_OF_RANGE; + } + } + + return E_SUCCESS; +} + +result +_LinkedListEnumerator::ResetLast(void) +{ + return Reset(); +} + +LinkedList::LinkedList(DeleterFunctionType deleter) + : __pListHead(null) + , __pListTail(null) + , __pAvailableHead(null) + , __pAvailableTail(null) + , __pBlocks(null) + , __count(0) + , __capacity(0) + , __modCount(0) + , __deleter(deleter) + , __pLinkedListImpl(null) +{ +} + +LinkedList::~LinkedList(void) +{ + RemoveAll(); + DeleteBlock(); +} + +result +LinkedList::Add(Object* pObj) +{ + SysTryReturnResult(NID_BASE_COL, pObj != null, E_INVALID_ARG, "Invalid argument used. The pObj is null"); + + result r = E_SUCCESS; + if (__count == 0) + { + r = InsertFirst(pObj); + } + else + { + r = InsertLast(pObj); + } + + if (r != E_SUCCESS) + { + SysLogException(NID_BASE_COL, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + __modCount++; + + return r; +} + +result +LinkedList::AddItems(const ICollection& collection) +{ + result r = InsertItemsFrom(collection, __count); + if (r != E_SUCCESS) + { + SysLogException(NID_BASE_COL, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; +} + +IEnumerator* +LinkedList::GetEnumeratorN(void) const +{ + return GetBidirectionalEnumeratorN(); +} + +IBidirectionalEnumerator* +LinkedList::GetBidirectionalEnumeratorN() const +{ + std::unique_ptr< _LinkedListEnumerator > pEnum(new (std::nothrow) _LinkedListEnumerator(*this, __modCount)); + SysTryReturn(NID_BASE_COL, pEnum != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum.release(); +} + +const Object* +LinkedList::GetAt(int index) const +{ + SysTryReturn(NID_BASE_COL, index >= 0 && index < __count, null, E_OUT_OF_RANGE, "[%s] The index(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + _ListNode* pNode = GetNode(index); + SetLastResult(E_SUCCESS); + return pNode->pObj; +} + +Object* +LinkedList::GetAt(int index) +{ + SysTryReturn(NID_BASE_COL, index >= 0 && index < __count, null, E_OUT_OF_RANGE, "[%s] The index(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), index, __count); + + const Object* pObj = (static_cast< const LinkedList* >(this))->GetAt(index); + SetLastResult(E_SUCCESS); + return const_cast< Object* >(pObj); +} + +IList* +LinkedList::GetItemsN(int startIndex, int count) const +{ + result r = E_SUCCESS; + + SysTryReturn(NID_BASE_COL, startIndex >= 0 && count >= 0, null, E_OUT_OF_RANGE, "[%s] Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), startIndex, count); + SysTryReturn(NID_BASE_COL, startIndex < __count, null, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) MUST be less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + SysTryReturn(NID_BASE_COL, count <= __count && (startIndex + count <= __count), null, E_OUT_OF_RANGE, + "[%s] The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, count, __count); + + _ListNode* pNode = GetNode(startIndex); + + int linkedListCount = startIndex + count; + std::unique_ptr< LinkedList > pList(new (std::nothrow) LinkedList()); + SysTryReturn(NID_BASE_COL, pList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = startIndex; i < linkedListCount; i++) + { + r = pList->Add(pNode->pObj); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + pNode = pNode->pNext; + } + SetLastResult(r); + return pList.release(); +} + +result +LinkedList::IndexOf(const Object& obj, int& index) const +{ + result r = E_SUCCESS; + if (__count == 0) + { + r = E_OBJ_NOT_FOUND; + } + else + { + r = IndexOf(obj, 0, __count, index); + } + + return r; +} + +result +LinkedList::IndexOf(const Object& obj, int startIndex, int& index) const +{ + SysTryReturn(NID_BASE_COL, (startIndex >= 0 && startIndex < __count), E_OUT_OF_RANGE, E_OUT_OF_RANGE, "[%s] The startIndex(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + + return IndexOf(obj, startIndex, (__count - startIndex), index); +} + +result +LinkedList::IndexOf(const Object& obj, int startIndex, int count, int& index) const +{ + SysTryReturnResult(NID_BASE_COL, __count != 0, E_OBJ_NOT_FOUND, "The number of elements on this list is equal to 0."); + SysTryReturnResult(NID_BASE_COL, startIndex >= 0 && count >= 0, E_OUT_OF_RANGE, "Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", startIndex, count); + SysTryReturnResult(NID_BASE_COL, startIndex < __count, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be less than the number of elements(%d).", startIndex, __count); + SysTryReturnResult(NID_BASE_COL, count <= __count && (startIndex + count <= __count), E_OUT_OF_RANGE, + "The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", startIndex, count, __count); + + result r = E_OBJ_NOT_FOUND; + _ListNode* pNode = GetNode(startIndex); + + int linkedListCount = startIndex + count; + for (int i = startIndex; i < linkedListCount; i++) + { + if (pNode->pObj->Equals(obj)) + { + index = i; + r = E_SUCCESS; + break; + } + pNode = pNode->pNext; + } + + return r; +} + +result +LinkedList::InsertAt(Object* pObj, int index) +{ + SysTryReturnResult(NID_BASE_COL, pObj != null, E_INVALID_ARG, "Invalid argument used. The pObj is null"); + SysTryReturnResult(NID_BASE_COL, index >= 0 && index <= __count, E_OUT_OF_RANGE, "The index(%d) MUST be greater than or equal to 0, and less than or equal to the number of elements(%d).", index, __count); + + result r = E_SUCCESS; + if (index == 0) + { + r = InsertFirst(pObj); + } + else if (index == __count) + { + r = InsertLast(pObj); + } + else + { + _ListNode* pNode = GetNode(index - 1); + if (pNode != null) + { + r = InsertNext(pObj, pNode); + } + } + + if (r != E_SUCCESS) + { + SysLogException(NID_BASE_COL, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + __modCount++; + + return r; +} + +result +LinkedList::InsertItemsFrom(const ICollection& collection, int startIndex) +{ + SysTryReturn(NID_BASE_COL, startIndex >= 0 && startIndex <= __count, E_OUT_OF_RANGE, E_OUT_OF_RANGE, "[%s] The startIndex(%d) MUST be greater than or equal to 0, and less than or equal to the number of elements(%d).", GetErrorMessage(E_OUT_OF_RANGE), startIndex, __count); + + result r = E_SUCCESS; + int insertingCount = collection.GetCount(); + + if (insertingCount <= 0) + { + return E_SUCCESS; + } + + int available = __capacity - __count; + if (available < insertingCount) + { + r = AddBlock(insertingCount - available); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + } + + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturnResult(NID_BASE_COL, pEnum != null, GetLastResult(), "Propagating."); + + __modCount++; + + while (true) + { + r = pEnum->MoveNext(); + // enumerator is reached to the end of collection + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + break; + } + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + Object* pObj = pEnum->GetCurrent(); + SysTryReturnResult(NID_BASE_COL, pObj != null, GetLastResult(), "Propagating."); + + r = InsertAt(pObj, startIndex++); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + return E_SUCCESS; +} + +result +LinkedList::LastIndexOf(const Object& obj, int& index) const +{ + result r = E_OBJ_NOT_FOUND; + _ListNode* pNode = __pListTail; + for (int i = (__count - 1); i >= 0; i--) + { + if (pNode->pObj->Equals(obj)) + { + index = i; + r = E_SUCCESS; + break; + } + pNode = pNode->pPrev; + } + + return r; +} + +result +LinkedList::Remove(const Object& obj) +{ + result r = E_OBJ_NOT_FOUND; + _ListNode* pNode = __pListHead; + for (int i = 0; i < __count; i++) + { + if (pNode->pObj->Equals(obj)) + { + __modCount++; + RemoveNode(pNode); + __count--; + r = E_SUCCESS; + break; + } + pNode = pNode->pNext; + } + + return r; +} + +result +LinkedList::RemoveAt(int index) +{ + SysTryReturnResult(NID_BASE_COL, index < __count && index >= 0, E_OUT_OF_RANGE, "The index(%d) MUST be greater than or equal to 0, and less than the number of elements(%d).", index, __count); + + __modCount++; + _ListNode* pNode = GetNode(index); + RemoveNode(pNode); + __count--; + + return E_SUCCESS; +} + +result +LinkedList::RemoveItems(int startIndex, int count) +{ + SysTryReturnResult(NID_BASE_COL, startIndex >= 0 && count >= 0, E_OUT_OF_RANGE, "Both of the startIndex(%d) and count(%d) MUST be greater than or equal to 0.", startIndex, count); + SysTryReturnResult(NID_BASE_COL, startIndex < __count, E_OUT_OF_RANGE, + "The startIndex(%d) MUST be less than the number of elements(%d).", startIndex, __count); + SysTryReturnResult(NID_BASE_COL, count <= __count && (startIndex + count <= __count), E_OUT_OF_RANGE, + "The startIndex(%d) + count(%d) MUST be less than or equal to the number of elements(%d).", startIndex, count, __count); + + __modCount++; + _ListNode* pNode = GetNode(startIndex); + + int linkedListCount = startIndex + count; + for (int i = startIndex; i < linkedListCount; i++) + { + _ListNode* pNextNode = pNode->pNext; + RemoveNode(pNode); + pNode = pNextNode; + } + __count -= count; + + return E_SUCCESS; +} + +result +LinkedList::RemoveItems(const ICollection& collection) +{ + result r = E_SUCCESS; + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturnResult(NID_BASE_COL, pEnum != null, GetLastResult(), "Propagating."); + + while (true) + { + r = pEnum->MoveNext(); + // enumerator is reached to the end of collection + if (E_OUT_OF_RANGE == r) + { + r = E_SUCCESS; + break; + } + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + Object* pTemp = pEnum->GetCurrent(); + SysTryReturnResult(NID_BASE_COL, pTemp != null, GetLastResult(), "Propagating."); + + r = Remove(*pTemp); + SysTryLog(NID_BASE_COL, !IsFailed(r), "[%s] Propagating.", GetErrorMessage(r)); + } + + return r; +} + +void +LinkedList::RemoveAll() +{ + if (__count > 0) + { + if (__pListHead == null) + { + __count = 0; + return; + } + + __modCount++; + + for (_ListNode* pNode = __pListHead; pNode != __pListTail; pNode = pNode->pNext) + { + __deleter(pNode->pObj); + pNode->pObj = null; + } + + if (__pListTail != null) + { + __deleter(__pListTail->pObj); + __pListTail->pObj = null; + } + + if (__pAvailableHead == null) + { + __pAvailableHead = __pListHead; + __pAvailableTail = __pListTail; + } + else + { + __pAvailableTail->pNext = __pListHead; + __pListHead->pPrev = __pAvailableTail; + __pAvailableTail = __pListTail; + } + __pListHead = null; + __pListTail = null; + __count = 0; + } +} + +result +LinkedList::SetAt(Object* pObj, int index) +{ + SysTryReturnResult(NID_BASE_COL, pObj != null, E_INVALID_ARG, "Invalid argument used. The pObj is null"); + SysTryReturnResult(NID_BASE_COL, index >= 0 && index < __count, E_OUT_OF_RANGE, "The index(%d) MUST be greater than or equal to 0, less than the number of elements(%d).", index, __count); + + __modCount++; + _ListNode* pNode = GetNode(index); + + __deleter(pNode->pObj); + + pNode->pObj = pObj; + + return E_SUCCESS; +} + +result +LinkedList::Sort(const IComparer& comparer) +{ + if (__count == 0) + { + return E_SUCCESS; + } + + ArrayList arrayList; + arrayList.Construct(*this); + + result r = arrayList.Sort(comparer); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + std::unique_ptr< IEnumerator > pEnum(arrayList.GetEnumeratorN()); + SysTryReturnResult(NID_BASE_COL, pEnum != null, GetLastResult(), "Propagating."); + + _ListNode* pNode = GetNode(0); + + while (pEnum->MoveNext() == E_SUCCESS) + { + Object* pItem = pEnum->GetCurrent(); + SysTryReturnResult(NID_BASE_COL, pItem != null, GetLastResult(), "Propagating."); + + pNode->pObj = pItem; + pNode = pNode->pNext; + SysTryReturnResult(NID_BASE_COL, pNode != null, GetLastResult(), "Propagating."); + } + + return r; +} + +int +LinkedList::GetCount(void) const +{ + return __count; +} + +bool +LinkedList::Contains(const Object& obj) const +{ + if (__count == 0) + { + return false; + } + + _ListNode* pNode = GetNode(0); + + while (pNode != null) + { + if (pNode->pObj->Equals(obj)) + { + return true; + } + pNode = pNode->pNext; + } + + return false; +} + +bool +LinkedList::ContainsAll(const ICollection& collection) const +{ + result r = E_SUCCESS; + SetLastResult(r); + + if (collection.GetCount() == 0) + { + return true; + } + + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturn(NID_BASE_COL, pEnum != null, false, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, false, r, "[%s] Propagating.", GetErrorMessage(r)); + + Object* pTemp = pEnum->GetCurrent(); + SysTryReturn(NID_BASE_COL, pTemp != null, false, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + if (!Contains(*pTemp)) + { + return false; + } + } + + return true; +} + +bool +LinkedList::Equals(const Object& obj) const +{ + if (&obj == this) + { + return true; + } + + const LinkedList* pOther = dynamic_cast< const LinkedList* >(&obj); + if (pOther == null) + { + return false; + } + else if (__count != pOther->__count) + { + return false; + } + else + { + _ListNode* pNode = __pListHead; + _ListNode* pOtherNode = pOther->__pListHead; + for (int i = 0; i < __count; i++) + { + if (!(pNode->pObj->Equals(*(pOtherNode->pObj)))) + { + return false; + } + + pNode = pNode->pNext; + pOtherNode = pOtherNode->pNext; + } + } + + return true; +} + +int +LinkedList::GetHashCode(void) const +{ + int hash = 0; + _ListNode* pNode = __pListHead; + for (int i = 0; i < __count; i++) + { + hash += pNode->pObj->GetHashCode(); + pNode = pNode->pNext; + } + + return hash; +} + +DeleterFunctionType +LinkedList::GetDeleter(void) const +{ + return __deleter; +} + +result +LinkedList::AddBlock(int blockSize) +{ + result r = E_SUCCESS; + + _ListNode* pNode = new (std::nothrow) _ListNode[blockSize]; + SysTryReturnResult(NID_BASE_COL, pNode != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + // add link + for (int i = 0; i < blockSize - 1; i++) + { + pNode[i].pNext = &pNode[i + 1]; + pNode[i + 1].pPrev = &pNode[i]; + } + + // add to __pBlocks + if (__pBlocks == null) + { + __pBlocks = pNode; + } + else + { + _ListNode* pBlock = __pBlocks; + while (pBlock->pNextBlock != null) + { + pBlock = pBlock->pNextBlock; + } + pBlock->pNextBlock = pNode; + } + + // add to available nodes + if (__pAvailableHead == null) + { + __pAvailableHead = pNode; + } + else + { + __pAvailableTail->pNext = pNode; + pNode->pPrev = __pAvailableTail; + } + __pAvailableTail = &pNode[blockSize - 1]; + + __capacity += blockSize; + + return r; +} + +void +LinkedList::DeleteBlock(void) +{ + while (__pBlocks != null) + { + _ListNode* pNode = __pBlocks->pNextBlock; + delete[] __pBlocks; + __pBlocks = pNode; + } +} + +result +LinkedList::InsertFirst(Object* pObj) +{ + if (__count == __capacity) + { + result r = AddBlock(); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + _ListNode* pNode = GetNewNode(); + + pNode->pObj = pObj; + + if (__pListHead == null) + { + __pListHead = pNode; + __pListTail = pNode; + } + else + { + pNode->pNext = __pListHead; + __pListHead->pPrev = pNode; + __pListHead = pNode; + } + __count++; + + return E_SUCCESS; +} + +result +LinkedList::InsertLast(Object* pObj) +{ + if (__count == __capacity) + { + result r = AddBlock(); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + _ListNode* pNode = GetNewNode(); + + pNode->pObj = pObj; + if (__pListHead == null) + { + __pListHead = pNode; + __pListTail = pNode; + } + else + { + pNode->pPrev = __pListTail; + __pListTail->pNext = pNode; + __pListTail = pNode; + } + + __count++; + + return E_SUCCESS; +} + +result +LinkedList::InsertNext(Object* pObj, _ListNode* pPrevNode) +{ + SysTryReturnResult(NID_BASE_COL, pPrevNode != null, E_INVALID_ARG, "pPrevNode is null."); + + if (__count == __capacity) + { + result r = AddBlock(); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + _ListNode* pNode = GetNewNode(); + + pNode->pObj = pObj; + pNode->pPrev = pPrevNode; + pNode->pNext = pPrevNode->pNext; + + pPrevNode->pNext->pPrev = pNode; + pPrevNode->pNext = pNode; + + __count++; + + return E_SUCCESS; +} + +_ListNode* +LinkedList::GetNewNode(void) +{ + SysTryReturn(NID_BASE_COL, __pAvailableHead != null, null, E_INVALID_STATE, "[%s] There is no available node.", GetErrorMessage(E_INVALID_STATE)); + + _ListNode* pNode = __pAvailableHead; + + if (__pAvailableHead == __pAvailableTail) + { + __pAvailableHead = null; + __pAvailableTail = null; + } + else + { + __pAvailableHead = __pAvailableHead->pNext; + __pAvailableHead->pPrev = null; + } + + pNode->pNext = null; + pNode->pPrev = null; + + return pNode; +} + +_ListNode* +LinkedList::GetNode(int index) const +{ + _ListNode* pNode = null; + if (index > static_cast< int >(__count / 2)) + { + pNode = __pListTail; + for (int i = __count - 1; i > index; i--) + { + pNode = pNode->pPrev; + } + } + else + { + pNode = __pListHead; + for (int i = 0; i < index; i++) + { + pNode = pNode->pNext; + } + } + + return pNode; +} + +void +LinkedList::RemoveNode(_ListNode* pNode) +{ + // remove links + if (pNode == __pListHead) + { + __pListHead = pNode->pNext; + if (__pListHead != null) + { + __pListHead->pPrev = null; + } + else + { + __pListTail = null; + } + } + else if (pNode == __pListTail) + { + __pListTail = pNode->pPrev; + __pListTail->pNext = null; + } + else + { + pNode->pNext->pPrev = pNode->pPrev; + pNode->pPrev->pNext = pNode->pNext; + } + + pNode->pNext = null; + pNode->pPrev = null; + + __deleter(pNode->pObj); + pNode->pObj = null; + + // add to available list + if (__pAvailableHead == null) + { + __pAvailableHead = pNode; + __pAvailableTail = pNode; + } + else + { + __pAvailableTail->pNext = pNode; + pNode->pPrev = __pAvailableTail; + __pAvailableTail = pNode; + } +} + +void +LinkedList::SetDeleter(DeleterFunctionType deleter) +{ + __deleter = deleter; +} + +} } } // Tizen::Base::Collection diff --git a/src/base/collection/FBaseColMapEntry.cpp b/src/base/collection/FBaseColMapEntry.cpp new file mode 100644 index 0000000..8239272 --- /dev/null +++ b/src/base/collection/FBaseColMapEntry.cpp @@ -0,0 +1,102 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColMapEntry.cpp + * @brief This is the implementation for MapEntry class. + */ + +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +MapEntry::MapEntry(void) + : _pKey(null) + , _pValue(null) + , __pMapEntryImpl(null) +{ +} + +MapEntry::MapEntry(const Object& pKey, const Object& pValue) + : __pMapEntryImpl(null) +{ + _pKey = const_cast (&pKey); + _pValue = const_cast (&pValue); +} + +MapEntry::~MapEntry(void) +{ +} + +const Object* +MapEntry::GetKey(void) const +{ + return _pKey; +} + +const Object* +MapEntry::GetValue(void) const +{ + return _pValue; +} + +Object* +MapEntry::GetKey(void) +{ + return _pKey; +} + +Object* +MapEntry::GetValue(void) +{ + return _pValue; +} + +bool +MapEntry::Equals(const Object& obj) const +{ + const MapEntry* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + if (_pKey->Equals(*(pOther->_pKey)) && _pValue->Equals(*(pOther->_pValue))) + { + return true; + } + + return false; +} +int +MapEntry::GetHashCode(void) const +{ + int hash = 0; + if (_pKey != null) + { + hash += _pKey->GetHashCode(); + } + if (_pValue != null) + { + hash += _pValue->GetHashCode(); + } + return hash; +} +} } } // Tizen::Base::Collection diff --git a/src/base/collection/FBaseColMultiHashMap.cpp b/src/base/collection/FBaseColMultiHashMap.cpp new file mode 100644 index 0000000..e246ede --- /dev/null +++ b/src/base/collection/FBaseColMultiHashMap.cpp @@ -0,0 +1,1193 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColMultiHashMap.cpp + * @brief This is the implementation for MultiHashMap class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class __Node + * @brief This is a node for MultiHashMap. + */ +class __Node + : public MapEntry +{ +public: + __Node(Object* pKey, Object* pValue); + virtual ~__Node(void); + + virtual Object* GetKey(void) const; + virtual Object* GetValue(void) const; + +private: + __Node(const __Node& node); + __Node& operator =(const __Node& rhs); + + __Node* pNext; + + friend class MultiHashMap; + friend class _MultiHashMapEnumerator; + friend class _EntryValueEnumerator; +}; + +__Node::__Node(Object* pKey, Object* pValue) + : MapEntry(*pKey, *pValue) + , pNext(null) +{ +} + +__Node::~__Node(void) +{ +} + +Object* +__Node::GetKey(void) const +{ + return _pKey; +} + +Object* +__Node::GetValue(void) const +{ + return _pValue; +} + +/** + * @class _MultiHashMapEntry + * @brief This is an entry for MultiHashMap class. + */ +class _MultiHashMapEntry +{ +public: + _MultiHashMapEntry(Object* key, __Node* list, _MultiHashMapEntry* next, int h); + virtual ~_MultiHashMapEntry(void); + + Object* pKey; + __Node* pList; + _MultiHashMapEntry* pNext; + int hash; + int modCount; + +private: + _MultiHashMapEntry(const _MultiHashMapEntry& entry); + _MultiHashMapEntry& operator =(const _MultiHashMapEntry& rhs); + + friend class MultiHashMap; + friend class _MultiHashMapEnumerator; + friend class _EntryValueEnumerator; + +}; + +_MultiHashMapEntry::_MultiHashMapEntry(Object* key, __Node* list, _MultiHashMapEntry* next, int h) + : pKey(key) + , pList(list) + , pNext(next) + , hash(h) + , modCount(0) +{ +} + +_MultiHashMapEntry::~_MultiHashMapEntry(void) +{ +} + +/** + * @class _MultiHashMapDefaultComparer + * @brief This is an implementation of IComparer for MultiHashMap. + */ +class _MultiHashMapDefaultComparer + : public IComparer + , public Object +{ +public: + _MultiHashMapDefaultComparer(void); + virtual ~_MultiHashMapDefaultComparer(void); + + virtual result Compare(const Object& obj1, const Object& obj2, int& cmp) const; + +}; + +_MultiHashMapDefaultComparer::_MultiHashMapDefaultComparer(void) +{ +} + +_MultiHashMapDefaultComparer::~_MultiHashMapDefaultComparer(void) +{ +} + +result +_MultiHashMapDefaultComparer::Compare(const Object& obj1, const Object& obj2, int& cmp) const +{ + if (obj1.Equals(obj2)) + { + cmp = 0; + } + else + { + cmp = 1; + } + + return E_SUCCESS; +} + +/** + * @class _MultiHashMapDefaultProvider + * @brief This is an implementation of IHashCodeProvider for MultiHashMap. + */ +class _MultiHashMapDefaultProvider + : public IHashCodeProvider + , public Object +{ +public: + _MultiHashMapDefaultProvider(void) {} + virtual ~_MultiHashMapDefaultProvider(void) {} + + using Object::GetHashCode; + virtual int GetHashCode(const Object& obj) const + { + return obj.GetHashCode(); + } + +}; + +/** + * @class _MultiHashMapEnumerator + * @brief This is an implementation of IMapEnumerator for MultiHashMap. + */ +class _MultiHashMapEnumerator + : public IMapEnumerator + , public Object +{ +public: + _MultiHashMapEnumerator(const MultiHashMap& map, int modCount); + virtual ~_MultiHashMapEnumerator(void); + + virtual Object* GetCurrent(void) const; + virtual result MoveNext(void); + virtual result Reset(void); + virtual Object* GetKey(void) const; + virtual Object* GetValue(void) const; + +private: + const MultiHashMap& __map; + int __modCount; + _MultiHashMapEntry* __pEntry; + __Node* __pNode; + int __index; + +}; + +_MultiHashMapEnumerator::_MultiHashMapEnumerator(const MultiHashMap& map, int modCount) + : __map(map) + , __modCount(modCount) + , __pEntry(null) + , __pNode(null) + , __index(-1) +{ +} + +_MultiHashMapEnumerator::~_MultiHashMapEnumerator(void) +{ +} + +Object* +_MultiHashMapEnumerator::GetCurrent(void) const +{ + SysTryReturn(NID_BASE_COL, (__modCount == __map.__modCount), null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, (__pEntry != null && __pNode != null), null, E_INVALID_OPERATION, "[%s] Invalid position(pEntry or pNode is null).", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __pNode; +} + +result +_MultiHashMapEnumerator::MoveNext(void) +{ + SysTryReturnResult(NID_BASE_COL, (__modCount == __map.__modCount), E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + if ((null != __pNode) && (__pNode->pNext != null)) + { + __pNode = __pNode->pNext; + return E_SUCCESS; + } + else if ((null != __pEntry) && (__pEntry->pNext != null)) + { + __pEntry = __pEntry->pNext; + __pNode = __pEntry->pList; + return E_SUCCESS; + } + else + { + while (++__index < __map.__capacity) + { + __pEntry = __map.__pTable[__index]; + if (null != __pEntry) + { + __pNode = __pEntry->pList; + return E_SUCCESS; + } + } + } + + return E_OUT_OF_RANGE; +} + +result +_MultiHashMapEnumerator::Reset(void) +{ + SysTryReturnResult(NID_BASE_COL, (__modCount == __map.__modCount), E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + __index = -1; + __pEntry = null; + __pNode = null; + + return E_SUCCESS; +} + +Object* +_MultiHashMapEnumerator::GetKey(void) const +{ + SysTryReturn(NID_BASE_COL, (__modCount == __map.__modCount), null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, (__pEntry != null && __pNode != null), null, E_INVALID_OPERATION, "[%s] Invalid position(pEntry or pNode is null).", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __pEntry->pKey; +} + +Object* +_MultiHashMapEnumerator::GetValue(void) const +{ + SysTryReturn(NID_BASE_COL, (__modCount == __map.__modCount), null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, (__pEntry != null && __pNode != null), null, E_INVALID_OPERATION, "[%s] Invalid position(pEntry or pNode is null).", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __pNode->GetValue(); +} + +/** + * @class _EntryValueEnumerator + * @brief This is an implementation of IEnumerator to enumerate values whose key is the same. + */ +class _EntryValueEnumerator + : public IEnumerator + , public Object +{ +public: + _EntryValueEnumerator(const _MultiHashMapEntry& entry, int modCount); + virtual ~_EntryValueEnumerator(void); + + virtual Object* GetCurrent(void) const; + virtual result MoveNext(void); + virtual result Reset(void); + +private: + const _MultiHashMapEntry& __entry; + int __modCount; + __Node* __pNode; + +}; + +_EntryValueEnumerator::_EntryValueEnumerator(const _MultiHashMapEntry& entry, int modCount) + : __entry(entry) + , __modCount(modCount) + , __pNode(null) +{ +} + +_EntryValueEnumerator::~_EntryValueEnumerator(void) +{ +} + +Object* +_EntryValueEnumerator::GetCurrent(void) const +{ + SysTryReturn(NID_BASE_COL, __modCount == __entry.modCount, null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, __pNode != null, null, E_INVALID_OPERATION, "[%s] Invalid position(pNode is null).", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __pNode->GetValue(); +} + +result +_EntryValueEnumerator::MoveNext(void) +{ + SysTryReturn(NID_BASE_COL, (__modCount == __entry.modCount), E_INVALID_OPERATION, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + if (__pNode == null) + { + __pNode = __entry.pList; + SysAssert(null != __pNode); + } + else if (__pNode->pNext != null) + { + __pNode = __pNode->pNext; + } + else + { + // Do not log the E_OUT_OF_RANGE, because it's normal or trivial in most cases. + return E_OUT_OF_RANGE; + } + + return E_SUCCESS; +} + +result +_EntryValueEnumerator::Reset(void) +{ + SysTryReturn(NID_BASE_COL, (__modCount == __entry.modCount), E_INVALID_OPERATION, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + + __pNode = null; + return E_SUCCESS; +} + +const float MultiHashMap::DEFAULT_LOAD_FACTOR = 0.75; + +MultiHashMap::MultiHashMap(DeleterFunctionType deleter) + : __pTable(null) + , __count(0) + , __capacity(0) + , __loadFactor(0) + , __threshold(0) + , __pProvider(null) + , __pComparer(null) + , __needToRemoveProviderComparer(false) + , __modCount(0) + , __deleter(deleter) + , __pMultiHashMapImpl(null) +{ +} + +MultiHashMap::~MultiHashMap(void) +{ + __modCount++; + if (__pTable != null) + { + Reset(); + delete[] __pTable; + } + + if (__needToRemoveProviderComparer) + { + delete __pProvider; + delete __pComparer; + } +} + +result +MultiHashMap::Construct(int capacity, float loadFactor) +{ + SysTryReturnResult(NID_BASE_COL, capacity >= 0, E_INVALID_ARG, "The capacity(%d) MUST be greater than or equal to 0.", capacity); + SysTryReturnResult(NID_BASE_COL, loadFactor >= 0, E_INVALID_ARG, "The loadFactor(%f) MUST be greater than or equal to 0.0.", loadFactor); + + std::unique_ptr< IHashCodeProvider > pProvider(new (std::nothrow) _MultiHashMapDefaultProvider()); + SysTryReturnResult(NID_BASE_COL, pProvider != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + std::unique_ptr< IComparer > pComparer(new (std::nothrow) _MultiHashMapDefaultComparer()); + SysTryReturnResult(NID_BASE_COL, pComparer != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __needToRemoveProviderComparer = true; + + result r = Construct(capacity, loadFactor, *(pProvider.release()), *(pComparer.release())); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + return r; +} + +result +MultiHashMap::Construct(const IMultiMap& map, float loadFactor) +{ + SysTryReturnResult(NID_BASE_COL, loadFactor >= 0, E_INVALID_ARG, "The loadFactor(%f) MUST be greater than or equal to 0.0.", loadFactor); + + std::unique_ptr< IHashCodeProvider > pProvider(new (std::nothrow) _MultiHashMapDefaultProvider()); + SysTryReturnResult(NID_BASE_COL, pProvider != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + std::unique_ptr< IComparer > pComparer(new (std::nothrow) _MultiHashMapDefaultComparer()); + SysTryReturnResult(NID_BASE_COL, pComparer != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __needToRemoveProviderComparer = true; + + result r = Construct(map, loadFactor, *(pProvider.release()), *(pComparer.release())); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + return r; +} + +result +MultiHashMap::Construct(int capacity, float loadFactor, const IHashCodeProvider& provider, const IComparer& comparer) +{ + SysTryReturnResult(NID_BASE_COL, capacity >= 0, E_INVALID_ARG, "The capacity(%d) MUST be greater than or equal to 0.", capacity); + SysTryReturnResult(NID_BASE_COL, loadFactor >= 0, E_INVALID_ARG, "The loadFactor(%f) MUST be greater than or equal to 0.0.", loadFactor); + + int newCapacity = 0; + if (capacity == 0) + { + newCapacity = DEFAULT_CAPACITY; + } + else + { + newCapacity = 1; + while (newCapacity < capacity) + { + newCapacity <<= 1; + } + } + + float newLoadFactor = 0; + if (Float::Compare(loadFactor, 0) == 0) + { + newLoadFactor = DEFAULT_LOAD_FACTOR; + } + else + { + newLoadFactor = loadFactor; + } + + int newThreshold = static_cast< int >(newCapacity * newLoadFactor); + std::unique_ptr< IHashCodeProvider > pProvider(const_cast< IHashCodeProvider* >(&provider)); + std::unique_ptr< IComparer > pComparer(const_cast< IComparer* >(&comparer)); + std::unique_ptr< _MultiHashMapEntry*[] > pTable(new (std::nothrow) _MultiHashMapEntry*[newCapacity]); + SysTryReturnResult(NID_BASE_COL, pTable != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + memset(pTable.get(), null, sizeof(*(pTable.get())) * newCapacity); + + __capacity = newCapacity; + __loadFactor = newLoadFactor; + __threshold = newThreshold; + __pProvider = pProvider.release(); + __pComparer = pComparer.release(); + __pTable = pTable.release(); + + return E_SUCCESS; +} + +result +MultiHashMap::Construct(const IMultiMap& map, float loadFactor, const IHashCodeProvider& provider, const IComparer& comparer) +{ + SysTryReturnResult(NID_BASE_COL, (loadFactor >= 0), E_INVALID_ARG, "The loadFactor(%f) MUST be greater than or equal to 0.0.", loadFactor); + + result r = E_SUCCESS; + if (Float::Compare(loadFactor, 0) == 0) + { + loadFactor = DEFAULT_LOAD_FACTOR; + } + + int capacity = static_cast< int >(map.GetCount() / loadFactor) + 1; + + r = Construct(capacity, loadFactor, provider, comparer); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + r = AddAll(map); + SysTryCatch(NID_BASE_COL, r == E_SUCCESS, , r, "[%s] Propagating.", GetErrorMessage(r)); + return r; + +CATCH: + DeleterFunctionType deleter = GetDeleter(); + SetDeleter(SingleObjectDeleter); + Reset(); + SetDeleter(deleter); + + delete[] __pTable; + __pTable = null; + + if (__needToRemoveProviderComparer) + { + delete __pProvider; + delete __pComparer; + } + + __capacity = 0; + __pProvider = null; + __pComparer = null; + + return r; +} + +result +MultiHashMap::Add(Object* pKey, Object* pValue) +{ + SysTryReturnResult(NID_BASE_COL, pKey != null , E_INVALID_ARG, "Invalid argument used. The pKey is null"); + SysTryReturnResult(NID_BASE_COL, pValue != null, E_INVALID_ARG, "Invalid argument used. The pValue is null"); + + __Node* pNewNode = null; + + result r = E_SUCCESS; + int hash = Hash(*pKey); + int i = hash & (__capacity - 1); + __Node* pNode = null; + _MultiHashMapEntry* pEntry = null; + + if (__pTable != null) + { + pEntry = __pTable[i]; + } + while (pEntry != null) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + r = __pComparer->Compare(*pKey, *(pEntry->pKey), cmpResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, E_INVALID_ARG, "Translating [%s] into [%s]", GetErrorMessage(r), GetErrorMessage(E_INVALID_ARG)); + + if (cmpResult == 0) + { + pNode = pEntry->pList; + while (true) + { + SysTryReturnResult(NID_BASE_COL, !(pNode->_pValue->Equals(*pValue)), E_OBJ_ALREADY_EXIST, "The value is already exist for the key."); + + if (pNode->pNext != null) + { + pNode = pNode->pNext; + } + else + { + pEntry->modCount++; + break; + } + } + break; + } + } + pEntry = pEntry->pNext; + } + + pNewNode = new (std::nothrow) __Node(pKey, pValue); + SysTryReturnResult(NID_BASE_COL, pNewNode != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + // pKey is not exist in this map. + if (pEntry == null) + { + _MultiHashMapEntry* pNewEntry = new (std::nothrow) _MultiHashMapEntry(pKey, pNewNode, __pTable[i], hash); + SysTryReturnResult(NID_BASE_COL, pNewEntry != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + __pTable[i] = pNewEntry; + } + // pKey is already exist in this map, but value is not. + else + { + // pNode is the last value associated to the pKey + pNode->pNext = pNewNode; + } + + __modCount++; + + if (__count++ >= __threshold) + { + r = Resize(__capacity * 2); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + return E_SUCCESS; +} + +IEnumerator* +MultiHashMap::GetEnumeratorN(void) const +{ + std::unique_ptr< _MultiHashMapEnumerator > pEnum(new (std::nothrow) _MultiHashMapEnumerator(*this, __modCount)); + SysTryReturn(NID_BASE_COL, pEnum != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum.release(); +} + +IMapEnumerator* +MultiHashMap::GetMapEnumeratorN(void) const +{ + return dynamic_cast< IMapEnumerator* >(GetEnumeratorN()); +} + +IEnumerator* +MultiHashMap::GetValuesN(const Object& key) const +{ + int hash = Hash(key); + int i = hash & (__capacity - 1); + + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + result r = __pComparer->Compare(key, *(pEntry->pKey), cmpResult); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (cmpResult == 0) + { + std::unique_ptr< IEnumerator > pEnum(new (std::nothrow) _EntryValueEnumerator(*pEntry, pEntry->modCount)); + SysTryReturn(NID_BASE_COL, pEnum != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum.release(); + } + } + } + + SetLastResult(E_OBJ_NOT_FOUND); + return null; +} + +IList* +MultiHashMap::GetKeysN(void) const +{ + result r = E_SUCCESS; + int keyCount = 0; + + std::unique_ptr< ArrayList > pList(new (std::nothrow) ArrayList()); + SysTryReturn(NID_BASE_COL, pList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pList->Construct(__count); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < __capacity; i++) + { + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + r = pList->Add(pEntry->pKey); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + keyCount++; + } + } + + SetLastResult(E_SUCCESS); + return pList.release(); +} + +IList* +MultiHashMap::GetValuesN(void) const +{ + result r = E_SUCCESS; + + std::unique_ptr< ArrayList > pList(new (std::nothrow) ArrayList()); + SysTryReturn(NID_BASE_COL, pList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pList->Construct(__count); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < __capacity; i++) + { + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + for (__Node* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + r = pList->Add(pNode->_pValue); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + } + } + } + + SetLastResult(E_SUCCESS); + return pList.release(); +} + +result +MultiHashMap::Remove(const Object& key) +{ + int hash = Hash(key); + int i = hash & (__capacity - 1); + + _MultiHashMapEntry* pPrev = __pTable[i]; + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + result r = __pComparer->Compare(key, *(pEntry->pKey), cmpResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, E_INVALID_ARG, "The input argument is invalid"); + + if (cmpResult == 0) + { + __modCount++; + if (pPrev == pEntry) + { + __pTable[i] = pEntry->pNext; + } + else + { + pPrev->pNext = pEntry->pNext; + } + + __Node* pNode = pEntry->pList; + while (pNode != null) + { + __Node* pTemp = pNode; + pNode = pNode->pNext; + + __deleter(pTemp->_pValue); + + delete pTemp; + __count--; + } + + __deleter(pEntry->pKey); + + delete pEntry; + + return E_SUCCESS; + } + } + pPrev = pEntry; + } + + return E_OBJ_NOT_FOUND; +} + +result +MultiHashMap::Remove(const Object& key, const Object& value) +{ + int hash = Hash(key); + int i = hash & (__capacity - 1); + + _MultiHashMapEntry* pPrev = __pTable[i]; + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + result r = __pComparer->Compare(key, *(pEntry->pKey), cmpResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, E_INVALID_ARG, "The input argument is invalid"); + + if (cmpResult == 0) + { + __Node* pPrevNode = pEntry->pList; + for (__Node* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + if (value.Equals(*(pNode->_pValue))) + { + __modCount++; + __count--; + if (pPrevNode == pNode) + { + pEntry->pList = pNode->pNext; + } + else + { + pPrevNode->pNext = pNode->pNext; + } + + __deleter(pNode->_pValue); + pNode->_pValue = null; + + delete pNode; + pNode = null; + + pEntry->modCount++; + + if (pEntry->pList == null) + { + if (pPrev == pEntry) + { + __pTable[i] = pEntry->pNext; + } + else + { + pPrev->pNext = pEntry->pNext; + } + + __deleter(pEntry->pKey); + pEntry->pKey = null; + + delete pEntry; + pEntry = null; + } + return E_SUCCESS; + } + pPrevNode = pNode; + } + if (!IsFailed(r)) + { + break; + } + } + } + pPrev = pEntry; + } + + return E_OBJ_NOT_FOUND; +} + +void +MultiHashMap::RemoveAll(void) +{ + if (__count > 0) + { + __modCount++; + Reset(); + __count = 0; + } +} + +result +MultiHashMap::SetValue(const Object& key, const Object& value, Object* pNewValue) +{ + SysTryReturnResult(NID_BASE_COL, pNewValue != null , E_INVALID_ARG, "Invalid argument used. The pNewValue is null"); + + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + __Node* pNode = null; + _MultiHashMapEntry* pEntry = __pTable[i]; + bool pairExist = false; + while (null != pEntry) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + r = __pComparer->Compare(key, *(pEntry->pKey), cmpResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, E_INVALID_ARG, "The input argument is invalid"); + + if (cmpResult == 0) + { + pNode = pEntry->pList; + while (true) + { + if (pNode->_pValue->Equals(value)) + { + __modCount++; + __deleter(pNode->_pValue); + pNode->_pValue = pNewValue; + pairExist = true; + break; + } + if (pNode->pNext != null) + { + pNode = pNode->pNext; + } + else + { + pEntry->modCount++; + break; + } + } + break; + } + } + pEntry = pEntry->pNext; + } + + if (!pairExist) + { + r = E_OBJ_NOT_FOUND; + } + + return r; + +} + +int +MultiHashMap::GetCount(void) const +{ + return __count; +} + +result +MultiHashMap::GetCount(const Object& key, int& count) const +{ + count = 0; + + result r = E_OBJ_NOT_FOUND; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + r = __pComparer->Compare(key, *(pEntry->pKey), cmpResult); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, E_INVALID_ARG, "The input argument is invalid"); + + if (cmpResult == 0) + { + int __count = 0; + for (__Node* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + __count++; + } + count = __count; + r = E_SUCCESS; + break; + } + } + } + + return r; +} + +bool +MultiHashMap::Contains(const Object& key, const Object& value) const +{ + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + SetLastResult(E_SUCCESS); + + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + r = __pComparer->Compare(key, *(pEntry->pKey), cmpResult); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, false, E_INVALID_ARG, "Translating [%s] into [%s]", GetErrorMessage(r), GetErrorMessage(E_INVALID_ARG)); + + if (cmpResult == 0) + { + for (__Node* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + if (value.Equals(*(pNode->_pValue))) + { + return true; + } + } + } + } + } + + return false; +} + +bool +MultiHashMap::ContainsKey(const Object& key) const +{ + result r = E_SUCCESS; + int hash = Hash(key); + int i = hash & (__capacity - 1); + + SetLastResult(E_SUCCESS); + + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + if (hash == pEntry->hash) + { + int cmpResult = 0; + r = __pComparer->Compare(key, *(pEntry->pKey), cmpResult); + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, false, E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(r)); + + if (cmpResult == 0) + { + return true; + } + } + } + + return false; +} + +bool +MultiHashMap::ContainsValue(const Object& value) const +{ + for (int i = 0; i < __capacity; i++) + { + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + for (__Node* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + if (value.Equals(*(pNode->_pValue))) + { + return true; + } + } + } + } + return false; +} + +bool +MultiHashMap::Equals(const Object& obj) const +{ + const MultiHashMap* pOther = dynamic_cast< const MultiHashMap* >(&obj); + if (pOther == null) + { + return false; + } + else if (pOther == this) + { + return true; + } + else if (__count != pOther->__count) + { + return false; + } + else + { + bool contain = true; + for (int i = 0; i < __capacity; i++) + { + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pEntry->pNext) + { + for (__Node* pNode = pEntry->pList; null != pNode; pNode = pNode->pNext) + { + contain = pOther->Contains(*(pEntry->pKey), *(pNode->_pValue)); + result r = GetLastResult(); + SysTryReturn(NID_BASE_COL, !IsFailed(r), false, r, "[%s] Propagating", GetErrorMessage(r)); + } + if (!contain) + { + break; + } + } + if (!contain) + { + break; + } + } + return contain; + } + + return true; +} + +int +MultiHashMap::GetHashCode(void) const +{ + int hash = 0; + _MultiHashMapEntry* pEntry = null; + _MultiHashMapEntry* pNext = null; + __Node* pNode = null; + for (int i = 0; i < __capacity; i++) + { + pEntry = __pTable[i]; + while (pEntry != null) + { + pNext = pEntry->pNext; + pNode = pEntry->pList; + while (pNode != null) + { + hash += pNode->_pValue->GetHashCode(); + pNode = pNode->pNext; + } + + hash += pEntry->pKey->GetHashCode(); + pEntry = pNext; + } + } + return hash; +} + +DeleterFunctionType +MultiHashMap::GetDeleter(void) const +{ + return __deleter; +} + +result +MultiHashMap::AddAll(const IMultiMap& map) +{ + result r = E_SUCCESS; + std::unique_ptr< IMapEnumerator > pMapEnum(map.GetMapEnumeratorN()); + SysTryReturnResult(NID_BASE_COL, pMapEnum != null, GetLastResult(), "Propagating."); + + while ((r = pMapEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + Object* pKey = pMapEnum->GetKey(); + SysTryReturnResult(NID_BASE_COL, pKey != null, GetLastResult(), "Propagating."); + + Object* pValue = pMapEnum->GetValue(); + SysTryReturnResult(NID_BASE_COL, pValue != null, GetLastResult(), "Propagating."); + + r = Add(pKey, pValue); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + } + + return E_SUCCESS; +} + +int +MultiHashMap::Hash(const Object& obj) const +{ + int h = __pProvider->GetHashCode(obj); + + h ^= (h >> 20) ^ (h >> 12); + + return h ^ (h >> 7) ^ (h >> 4); +} + +result +MultiHashMap::Resize(int newCapacity) +{ + _MultiHashMapEntry** pNewTable = new (std::nothrow) _MultiHashMapEntry*[newCapacity]; + SysTryReturnResult(NID_BASE_COL, pNewTable != null, E_OUT_OF_MEMORY, ""); + memset(pNewTable, null, sizeof(*pNewTable) * newCapacity); + + for (int i = 0; i < __capacity; i++) + { + _MultiHashMapEntry* pNext = null; + int index = 0; + for (_MultiHashMapEntry* pEntry = __pTable[i]; null != pEntry; pEntry = pNext) + { + pNext = pEntry->pNext; + index = pEntry->hash & (newCapacity - 1); + pEntry->pNext = pNewTable[index]; + pNewTable[index] = pEntry; + } + } + + delete[] __pTable; + __pTable = pNewTable; + __capacity = newCapacity; + __threshold = static_cast< int >(__capacity * __loadFactor); + + return E_SUCCESS; +} + +void +MultiHashMap::Reset(void) +{ + for (int i = 0; i < __capacity; i++) + { + _MultiHashMapEntry* pEntry = __pTable[i]; + while (pEntry != null) + { + _MultiHashMapEntry* pNext = pEntry->pNext; + __Node* pNode = pEntry->pList; + + while (pNode != null) + { + std::unique_ptr< __Node > pTemp(pNode); + pNode = pNode->pNext; + + __deleter(pTemp->_pValue); + } + + __deleter(pEntry->pKey); + delete pEntry; + pEntry = pNext; + } + __pTable[i] = null; + } +} + +void +MultiHashMap::SetDeleter(DeleterFunctionType deleter) +{ + __deleter = deleter; +} +} } } // Tizen::Base::Collectionn diff --git a/src/base/collection/FBaseColQueue.cpp b/src/base/collection/FBaseColQueue.cpp new file mode 100644 index 0000000..64a7583 --- /dev/null +++ b/src/base/collection/FBaseColQueue.cpp @@ -0,0 +1,355 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColQueue.cpp + * @brief This is the implementation for Queue class. + */ + +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class _QueueEnumerator + * @brief This is an implementation of IEnumerator for Queue. + */ +class _QueueEnumerator + : public IEnumerator + , public Object +{ +public: + _QueueEnumerator(const Queue& queue, int modCount); + virtual ~_QueueEnumerator(void); + + virtual Object* GetCurrent(void) const; + virtual result MoveNext(void); + virtual result Reset(void); + +private: + const Queue& __queue; + int __modCount; + int __position; +}; + +_QueueEnumerator::_QueueEnumerator(const Queue& queue, int modCount) + : __queue(queue) + , __modCount(modCount) + , __position(-1) +{ +} + +_QueueEnumerator::~_QueueEnumerator(void) +{ +} + +Object* +_QueueEnumerator::GetCurrent(void) const +{ + SysTryReturn(NID_BASE_COL, __modCount == __queue.__modCount, null, E_INVALID_OPERATION, "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, (__position >= __queue.__tail) && (__position < __queue.__head), null, E_INVALID_OPERATION, "[%s] Current position is before the first element or past the last element.", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __queue.__pObjArray[__position % __queue.__capacity]; +} + +result +_QueueEnumerator::MoveNext(void) +{ + SysTryReturnResult(NID_BASE_COL, __modCount == __queue.__modCount, E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + if ((__position + 1) >= __queue.__head) + { + return E_OUT_OF_RANGE; + } + + if (__position == -1) + { + __position = __queue.__tail; + } + else + { + __position++; + } + + return E_SUCCESS; +} + +result +_QueueEnumerator::Reset(void) +{ + SysTryReturnResult(NID_BASE_COL, __modCount == __queue.__modCount, E_INVALID_OPERATION, "The source collection was modified after the creation of this enumerator."); + + __position = -1; + return E_SUCCESS; +} + +Queue::Queue(void) + : __capacity(0) + , __head(0) + , __tail(0) + , __pObjArray(null) + , __modCount(0) + , __pQueueImpl(null) +{ +} + +Queue::~Queue(void) +{ + __modCount++; + + delete[] __pObjArray; +} + +result +Queue::Construct(int capacity) +{ + SysTryReturn(NID_BASE_COL, capacity >= 0, E_INVALID_ARG, E_INVALID_ARG, "[%s] Invalid argument(s) is used. The capacity(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), capacity); + + result r = E_SUCCESS; + + if (capacity > 0) + { + __pObjArray = new (std::nothrow) Object*[capacity]; + SysTryCatch(NID_BASE_COL, __pObjArray != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + } + __capacity = capacity; + + return r; + +CATCH: + return r; +} + +result +Queue::Construct(const ICollection& collection) +{ + result r = E_SUCCESS; + int count = collection.GetCount(); + r = Construct(count); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + if (count > 0) + { + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryCatch(NID_BASE_COL, pEnum != null, r = GetLastResult(), GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryCatch(NID_BASE_COL, r == E_SUCCESS, , r, "[%s] Propagating.", GetErrorMessage(r)); + + Object* pTemp = pEnum->GetCurrent(); + SysTryCatch(NID_BASE_COL, pTemp != null, r = GetLastResult(), GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + __pObjArray[__head % __capacity] = pTemp; + __head++; + } + } + + return E_SUCCESS; + +CATCH: + delete[] __pObjArray; + __pObjArray = null; + + return r; +} + +Object* +Queue::Dequeue(void) +{ + SysTryReturn(NID_BASE_COL, __head > __tail, null, E_UNDERFLOW, "[%s] Dequeue operation failed.", GetErrorMessage(E_UNDERFLOW)); + + __modCount++; + + SetLastResult(E_SUCCESS); + return __pObjArray[(__tail++) % __capacity]; +} + +result +Queue::Enqueue(Object* pObj) +{ + SysTryReturnResult(NID_BASE_COL, pObj != null, E_INVALID_ARG, "Invalid argument used. The pObj is null"); + + if (__pObjArray == null) + { + __pObjArray = new (std::nothrow) Object*[DEFAULT_CAPACITY]; + SysTryReturnResult(NID_BASE_COL, __pObjArray != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __capacity = DEFAULT_CAPACITY; + } + else if ((__head - __tail) >= __capacity) + { + Object** pNewArray = new (std::nothrow) Object*[__capacity + DEFAULT_CAPACITY]; + SysTryReturnResult(NID_BASE_COL, pNewArray != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + for (int i = 0, j = __tail; i < __capacity; i++, j++) + { + pNewArray[i] = __pObjArray[j % __capacity]; + } + + delete[] __pObjArray; + + __pObjArray = pNewArray; + __tail = 0; + __head = __capacity; + __capacity += DEFAULT_CAPACITY; + } + + __modCount++; + + __pObjArray[__head % __capacity] = pObj; + __head++; + + return E_SUCCESS; +} + +IEnumerator* +Queue::GetEnumeratorN(void) const +{ + std::unique_ptr< _QueueEnumerator > pEnum(new (std::nothrow) _QueueEnumerator(*this, __modCount)); + SysTryReturn(NID_BASE_COL, pEnum != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum.release(); +} + +const Object* +Queue::Peek(void) const +{ + SysTryReturn(NID_BASE_COL, __head > __tail, null, E_UNDERFLOW, "[%s] Peek operation failed.", GetErrorMessage(E_UNDERFLOW)); + + SetLastResult(E_SUCCESS); + return __pObjArray[__tail % __capacity]; +} + +void +Queue::RemoveAll(bool deallocate) +{ + __modCount++; + int count = GetCount(); + for (int i = 0; i < count; i++) + { + if (deallocate) + { + delete __pObjArray[(__tail + i) % __capacity]; + } + + __pObjArray[(__tail + i) % __capacity] = null; + } + + __head = 0; + __tail = 0; +} + +int +Queue::GetCount(void) const +{ + return(__head - __tail); +} + +bool +Queue::Contains(const Object& obj) const +{ + int count = GetCount(); + for (int i = 0; i < count; i++) + { + if (__pObjArray[(__tail + i) % __capacity]->Equals(obj)) + { + return true; + } + } + + return false; +} + +bool +Queue::ContainsAll(const ICollection& collection) const +{ + result r = E_SUCCESS; + SetLastResult(r); + + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturn(NID_BASE_COL, pEnum != null, false, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, false, r, "[%s] Propagating.", GetErrorMessage(r)); + + Object* pItem = pEnum->GetCurrent(); + SysTryReturn(NID_BASE_COL, pItem != null, false, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + if (!Contains(*pItem)) + { + return false; + } + } + + return true; +} + +bool +Queue::Equals(const Object& obj) const +{ + const Queue* pOther = dynamic_cast< const Queue* >(&obj); + if (pOther == null) + { + return false; + } + else if (pOther == this) + { + return true; + } + else if (GetCount() != pOther->GetCount()) + { + return false; + } + else + { + int count = GetCount(); + for (int i = 0; i < count; i++) + { + if (!(__pObjArray[(__tail + i) % __capacity]->Equals(*(pOther->__pObjArray[(pOther->__tail + i) % pOther->__capacity])))) + { + return false; + } + } + } + + return true; +} + +int +Queue::GetHashCode(void) const +{ + int hash = 0; + int count = GetCount(); + for (int i = 0; i < count; i++) + { + if (__pObjArray[(__tail + i) % __capacity] != null) + { + hash += __pObjArray[(__tail + i) % __capacity]->GetHashCode(); + } + } + return hash; +} +}}} // Tizen::Base::Collection diff --git a/src/base/collection/FBaseColStack.cpp b/src/base/collection/FBaseColStack.cpp new file mode 100644 index 0000000..ee5c1e2 --- /dev/null +++ b/src/base/collection/FBaseColStack.cpp @@ -0,0 +1,343 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColStack.cpp + * @brief This is the implementation for Stack class. + */ + +#include +#include +#include +#include +#include + + + +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * @class _StackEnumerator + * @brief This is an implementation of IEnumerator for Stack. + */ +class _StackEnumerator + : public IEnumerator + , public Object +{ +public: + _StackEnumerator(const Stack& stack, int modCount); + virtual ~_StackEnumerator(void); + + virtual Object* GetCurrent(void) const; + virtual result MoveNext(void); + virtual result Reset(void); + +private: + const Stack& __stack; + int __modCount; + int __position; +}; + +_StackEnumerator::_StackEnumerator(const Stack& stack, int modCount) + : __stack(stack) + , __modCount(modCount) + , __position(-1) +{ +} + +_StackEnumerator::~_StackEnumerator(void) +{ +} + +Object* +_StackEnumerator::GetCurrent(void) const +{ + SysTryReturn(NID_BASE_COL, __modCount == __stack.__modCount, null, E_INVALID_OPERATION, + "[%s] The source collection was modified after the creation of this enumerator.", GetErrorMessage(E_INVALID_OPERATION)); + SysTryReturn(NID_BASE_COL, (__position >= 0) && (__position <= (__stack.__index)), null, E_INVALID_OPERATION, + "[%s] Current position is before the first element or past the last element.", GetErrorMessage(E_INVALID_OPERATION)); + + SetLastResult(E_SUCCESS); + return __stack.__pObjArray[__position]; +} + +result +_StackEnumerator::MoveNext(void) +{ + SysTryReturnResult(NID_BASE_COL, __modCount == __stack.__modCount, E_INVALID_OPERATION, + "The source collection was modified after the creation of this enumerator."); + + if (__position >= __stack.__index) + { + return E_OUT_OF_RANGE; + } + + __position++; + + return E_SUCCESS; +} + +result +_StackEnumerator::Reset(void) +{ + SysTryReturnResult(NID_BASE_COL, __modCount == __stack.__modCount, E_INVALID_OPERATION, + "The source collection was modified after the creation of this enumerator."); + + __position = -1; + return E_SUCCESS; +} + +Stack::Stack(void) + : __capacity(0) + , __index(-1) + , __pObjArray(null) + , __modCount(0) + , __pStackImpl(null) +{ +} + +Stack::~Stack(void) +{ + delete[] __pObjArray; +} + +result +Stack::Construct(int capacity) +{ + SysTryReturnResult(NID_BASE_COL, capacity >= 0, E_INVALID_ARG, + "The capacity(%d) MUST be greater than or equal to 0.", capacity); + + if (capacity > 0) + { + __pObjArray = new (std::nothrow) Object*[capacity]; + SysTryReturnResult(NID_BASE_COL, __pObjArray != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + __capacity = capacity; + + return E_SUCCESS; +} + +result +Stack::Construct(const ICollection& collection) +{ + result r = E_SUCCESS; + int count = collection.GetCount(); + r = Construct(count); + SysTryReturnResult(NID_BASE_COL, r == E_SUCCESS, r, "Propagating."); + + if (count > 0) + { + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryCatch(NID_BASE_COL, pEnum != null, r = GetLastResult(), GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryCatch(NID_BASE_COL, r == E_SUCCESS, , r, "[%s] Propagating.", GetErrorMessage(r)); + + Object* pItem = pEnum->GetCurrent(); + SysTryCatch(NID_BASE_COL, pItem != null, r = GetLastResult(), GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + __pObjArray[++__index] = pItem; + } + } + + return E_SUCCESS; + +CATCH: + delete[] __pObjArray; + __pObjArray = null; + + return r; +} + +IEnumerator* +Stack::GetEnumeratorN(void) const +{ + std::unique_ptr< _StackEnumerator > pEnum(new (std::nothrow) _StackEnumerator(*this, __modCount)); + SysTryReturn(NID_BASE_COL, pEnum != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + SetLastResult(E_SUCCESS); + return pEnum.release(); +} + +const Object* +Stack::Peek(void) const +{ + SysTryReturn(NID_BASE_COL, __index >= 0, null, E_UNDERFLOW, "[%s] Peek operation failed.", GetErrorMessage(E_UNDERFLOW)); + + SetLastResult(E_SUCCESS); + return __pObjArray[__index]; +} + +Object* +Stack::Pop(void) +{ + SysTryReturn(NID_BASE_COL, __index >= 0, null, E_UNDERFLOW, "[%s] Pop operation failed.", GetErrorMessage(E_UNDERFLOW)); + + __modCount++; + + SetLastResult(E_SUCCESS); + return __pObjArray[__index--]; +} + +result +Stack::Push(Object* pObj) +{ + SysTryReturnResult(NID_BASE_COL, pObj != null, E_INVALID_ARG, "Invalid argument used. The pObj is null"); + + if (__pObjArray == null) + { + __pObjArray = new (std::nothrow) Object*[DEFAULT_CAPACITY]; + SysTryReturnResult(NID_BASE_COL, __pObjArray != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + __capacity = DEFAULT_CAPACITY; + } + else if (__index + 1 >= __capacity) + { + Object** pNewArray = new (std::nothrow) Object*[__capacity + DEFAULT_CAPACITY]; + SysTryReturnResult(NID_BASE_COL, pNewArray != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + memcpy(pNewArray, __pObjArray, sizeof(Object*) * (__index + 1)); + + delete[] __pObjArray; + + __pObjArray = pNewArray; + __capacity += DEFAULT_CAPACITY; + } + + __modCount++; + + __pObjArray[++__index] = pObj; + + return E_SUCCESS; +} + +void +Stack::RemoveAll(bool deallocate) +{ + __modCount++; + + for (int i = 0; i <= __index; i++) + { + if (deallocate) + { + delete __pObjArray[i]; + } + + __pObjArray[i] = null; + } + + __index = -1; +} + +int +Stack::GetCount(void) const +{ + return (__index + 1); +} + +bool +Stack::Contains(const Object& obj) const +{ + if (__index > -1) + { + for (int i = 0; i <= __index; i++) + { + if (__pObjArray[i]->Equals(obj)) + { + return true; + } + } + } + + return false; +} + +bool +Stack::ContainsAll(const ICollection& collection) const +{ + result r = E_SUCCESS; + SetLastResult(r); + + std::unique_ptr< IEnumerator > pEnum(collection.GetEnumeratorN()); + SysTryReturn(NID_BASE_COL, pEnum != null, false, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while ((r = pEnum->MoveNext()) != E_OUT_OF_RANGE) + { + SysTryReturn(NID_BASE_COL, r == E_SUCCESS, false, r, "[%s] Propagating.", GetErrorMessage(r)); + + Object* pItem = pEnum->GetCurrent(); + SysTryReturn(NID_BASE_COL, pItem != null, false, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + if (!Contains(*pItem)) + { + return false; + } + } + + return true; +} + +bool +Stack::Equals(const Object& obj) const +{ + const Stack* pOther = dynamic_cast< const Stack* >(&obj); + if (pOther == null) + { + return false; + } + else if (pOther == this) + { + return true; + } + else if (__index != pOther->__index) + { + return false; + } + else + { + for (int i = 0; i <= __index; i++) + { + if (!(__pObjArray[i]->Equals(*(pOther->__pObjArray[i])))) + { + return false; + } + } + } + + return true; +} + +int +Stack::GetHashCode(void) const +{ + int hash = 0; + for (int i = 0; i <= __index; i++) + { + if (__pObjArray[i] != null) + { + hash += __pObjArray[i]->GetHashCode(); + } + } + + return hash; +} + +}}} // Tizen::Base::Collection diff --git a/src/base/collection/FBaseColTypes.cpp b/src/base/collection/FBaseColTypes.cpp new file mode 100644 index 0000000..34ed734 --- /dev/null +++ b/src/base/collection/FBaseColTypes.cpp @@ -0,0 +1,66 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseColTypes.cpp + * @brief This is the implementation for the element deleter. + */ + +#include + +namespace Tizen { namespace Base { namespace Collection +{ + +/** + * This function doesn't remove the object. + * + * @since 2.0 + * + * @param[in] pObj The pointer to object to be removed. + */ +void +NoOpDeleter(Object* pObj) +{ +} + +/** + * This function removes the single object. + * + * @since 2.0 + * + * @param[in] pObj The pointer to object to be removed. + */ +void +SingleObjectDeleter(Object* pObj) +{ + delete pObj; +} + +/** + * This function removes the array object. + * + * @since 2.0 + * + * @param[in] pObj The pointer to object to be removed. + */ +void +ArrayDeleter(Object* pObj) +{ + delete[] pObj; +} + +}}} // Tizen::Base::Collection diff --git a/src/base/inc/FBaseInternalTypes.h b/src/base/inc/FBaseInternalTypes.h new file mode 100644 index 0000000..cf88a62 --- /dev/null +++ b/src/base/inc/FBaseInternalTypes.h @@ -0,0 +1,65 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseInternalTypes.h + * @brief This is the header file for the FBase internal types + */ + +#ifndef _FBASE_INTERNAL_TYPES_H_ +#define _FBASE_INTERNAL_TYPES_H_ + +namespace Tizen { namespace Base +{ + +/** + * @enum _ApiVersion + * Defines the Api version of the application + * + * @since 2.0 + */ +typedef enum +{ + _API_VERSION_INVALID = -1, /**< Invalid Api version */ + _API_VERSION_1_0 = 100, /**< Api version 1.0 */ + _API_VERSION_1_0_2 = 102, /**< Api version 1.02 */ + _API_VERSION_1_1 = 110, /**< Api version 1.1 */ + _API_VERSION_1_2 = 120, /**< Api version 1.2 */ + _API_VERSION_2_0 = 200, /**< Api version 2.0 */ + _API_VERSION_2_1 = 210, /**< Api version 2.1 */ + _API_VERSION_MAX = 65535 +} _ApiVersion; + +/** + * @enum _ApiVisibility + * Defines the visibility of the api + * + * @since 2.0 + */ +enum _ApiVisibility +{ + _API_VISIBILITY_NONE = 0, + _API_VISIBILITY_PUBLIC = 100, + _API_VISIBILITY_PARTNER = 200, + _API_VISIBILITY_PARTNER_OPERATOR = 210, + _API_VISIBILITY_PARTNER_MANUFACTURER = 220, + _API_VISIBILITY_MAX = 65535 +}; + +}} // Tizen::Base + +#endif // _FBASE_INTERNAL_TYPES_H_ diff --git a/src/base/inc/FBaseRtIEvent.h b/src/base/inc/FBaseRtIEvent.h new file mode 100644 index 0000000..0b13eec --- /dev/null +++ b/src/base/inc/FBaseRtIEvent.h @@ -0,0 +1,170 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtIEvent.h + * @brief This is the header file for IEvent. + */ + +#ifndef _FRT_IEVENT_H_ +#define _FRT_IEVENT_H_ + + +#include +#include + +#include "FBaseRtIEventFilter.h" +#include "FBaseRtIEventArg.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + + +// forward declaration +class _EventDispatcher; + +/** + * @interface IEvent + * @brief This interface is the root class for all event types. + * + * This interface is used for defining the kind of the occurrences. For example, one of the sub-classes + * of this interface can be the key event, and it represents there can be the occurrences about the key. + * An occurrence is represented by the event arguments. The event argument keeps the information + * about the occurrence of the key event. You can get the information about what key is pressed or released from the + * event argument of the key event. + * + * The event instance may have some event filters and event listeners. + * The event filters are the filtering mechanism for fired event. It can modify or consume the event argument. + * Modified event argument is passed to the next event filter, and finally event listeners listen with modified event + * argument. Consumed event argument is neither passed to the next event filter nor to the event listeners. + * When you want to get the numeric keys or remap the keys, you can add the filter to the key event for filtering + * the non-numeric keys or changing the key codes. + * + * The event listener listens to the event argument which is fired at the event. + * Listening event argument is passed by event filters. The event listener is called with + * its corresponding method by passing event argument's value. + * The sample of the event listener is in the Event class' description. + * + * @remarks The default implementation of this interface is Event class. + * @see Event + */ +class _OSP_EXPORT_ IEvent +{ +public: + // + // This is a virtual destructor. + // + virtual ~IEvent(void) {} + + + /** + * Adds a filter object. + * Added filter can process all the fired events before event listening. + * + * @param[in] filter Filter to be added + * @return Error code. + * @exception E_SUCCESS - This method is successful. + * @exception E_OUT_OF_MEMORY - Failed to allocate required/requested memory. + * @remark It is not forced how to implement this method. It depends on the implementation of + * the inherited classes. But in general Event class which is the default implementation + * of this interface is used + * in many cases. + * @see RemoveFilter + */ + virtual result AddFilter(const IEventFilter& filter) = 0; + + + /** + * Removes a filter object. + * + * @param[in] filter Filter to be removed + * @return Error code. + * @exception E_SUCCESS - This method is successful. + * @exception E_OBJ_NOT_FOUND - The specified object is not found within the indicated range. + * @remark It is not forced how to implement this method. It depends on the implementation of + * the inherited classes. But in general Event class which is the default implementation + * of this interface is used + * in many cases. + * @see AddFilter + */ + virtual result RemoveFilter(const IEventFilter& filter) = 0; + + + /** + * Adds a listener object. + * Added listener can listen to events when they are fired. + * + * @param[in] listener Listener to be added + * @return Error code. + * @exception E_SUCCESS - This method is successful. + * @exception E_OUT_OF_MEMORY - Failed to allocate required/requested memory. + * @remark It is not forced how to implement this method. It depends on the implementation of + * the inherited classes. But in general Event class which is the default implementation + * of this interface is used in many cases. + * @see RemoveListener + */ + virtual result AddListener(const IEventListener& listener) = 0; + + + /** + * Removes a listener object. + * Removed listener cannot listen to events when they are fired. + * + * @param[in] listener Listener to be removed + * @return Error code. + * @exception E_SUCCESS - This method is successful. + * @exception E_OBJ_NOT_FOUND - The specified object is not found within the indicated range. + * @remark It is not forced how to implement this method. It depends on the implementation of + * the inherited classes. But in general Event class which is the default implementation + * of this interface is used + * in many cases. + * @see AddListener + */ + virtual result RemoveListener(const IEventListener& listener) = 0; + + + /** + * Fires the event with event argument. + * All listeners that are added to this method listen when it is called. + * + * @param[in] arg The event argument. + * @return true, if the event has been fired without filtering. false, otherwise. + */ + virtual bool Fire(const IEventArg& arg) = 0; + + /** + * Fires the event with event argument. + * All listeners that are added to this method listen when it is called. + * + * @param[in] arg The event argument. + * @return true, if the event has been fired without filtering. false, otherwise. + */ + virtual bool Fire(const IEventArg& arg, bool async) = 0; + + + virtual int AddRef(void) = 0; + + + virtual int Release(void) = 0; +}; + + +} } } // Tizen::Runtime + + +#endif diff --git a/src/base/inc/FBaseRtIEventFilter.h b/src/base/inc/FBaseRtIEventFilter.h new file mode 100644 index 0000000..e695e68 --- /dev/null +++ b/src/base/inc/FBaseRtIEventFilter.h @@ -0,0 +1,75 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtIEventFilter.h + * @brief This is the header file for the %IEventFilter class. + * + * This file contains the declarations of the %IEventFilter class. + */ + +#ifndef _FBASE_RT_IEVENT_FILTER_H_ +#define _FBASE_RT_IEVENT_FILTER_H_ + + +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +class IEventArg; + +/** + * @interface IEventFilter + * @brief This is a filtering interface that can filter the fired event. + * + * The event model supports the event filtering mechanisms by providing this interface. + * You can implement the event filter classes by inheriting this interface. Instances of this + * interface can be added to the event instances. These event filter instances take the event + * arguments before the event listeners listen to it. + * The event filter can modify the event argument or consume it. + * Consuming can be done by returning @c false at the @c Filter() method. + * Consumed event can not be listened by the event listeners. + * + * @see IEvent::AddFilter, IEvent::RemoveFilter + */ +class _OSP_EXPORT_ IEventFilter +{ +public: + // + // This is a virtual destructor. + // + virtual ~IEventFilter(void) {} + +public: + /** + * Filters events. + * + * Can be called before executing event listeners. It can consume the event + * without processing next filters or event listeners and convert the event argument and etc. + * + * @param[in,out] eventArg It is an event argument, and it can be converted by this method. + * @return @c true if it can continue processing. It returns @c false if it + * stops processing. + * + */ + virtual bool Filter(const IEventArg& eventArg) = 0; +}; // IEventArg + +} } } // Tizen::Runtime + +#endif // _FBASE_RT_IEVENT_FILTER_H_ diff --git a/src/base/inc/FBaseRt_Event.h b/src/base/inc/FBaseRt_Event.h new file mode 100644 index 0000000..e39cda5 --- /dev/null +++ b/src/base/inc/FBaseRt_Event.h @@ -0,0 +1,280 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_Event.h + * @brief This is the header file for the %_Event class. + * + * This file contains the declarations of the %_Event class. + */ + +#ifndef _FBASE_RT_INTERNAL_EVENT_H_ +#define _FBASE_RT_INTERNAL_EVENT_H_ + +#include +#include +#include +#include +#include +#include +#include "FBaseRtIEventArg.h" +#include "FBase_HandleT.h" +#include "FBase_ObjectManagerT.h" + + + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _EventManager; + +/** + * @class _Event + * @brief This class provides methods for delivering an event with an argument synchronously and asynchronously. + * + * This class provides methods for asynchronous operation. + * @see IEventListener, IEventArg + */ +class _OSP_EXPORT_ _Event + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _Event(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_Event(void); + + /** + * Adds the listener object. + * The added listener can listen to events when they are fired. + * + * @since 2.0 + * + * @return An error code + * @param[in] listener Listener to add + * @param[in] calledByCallerThread true, to call the listener on the caller thread of this method + * false, to call the listener on the thread in which the event is created. + * @exception E_SUCCESS This method is successful. + * @exception E_OBJ_ALREADY_EXIST The listener already exists. + * @exception E_INVALID_OPERATION calledByCallerThread is set to true but the caller thread is a worker thread. + */ + result AddListener(const IEventListener& listener, bool calledByCallerThread = false); + + /** + * Removes a listener object. + * Removed listener cannot listen to events when they are fired. + * + * @since 2.0 + * @return An error code + * @param[in] listener Listener to remove + * @exception E_SUCCESS This method was successful. + * @exception E_OBJ_NOT_FOUND The listener was not found. + * @see AddListener + */ + result RemoveListener(const IEventListener& listener); + + /** + * Fires the event with an argument synchronously. + * + * @since 2.0 + * + * @code + * void + * MyClass::SendModeChangeEvent(int mode) + * { + * // An event argument should be created on a heap. + * MyEventArg* pArg = new MyEventArg(MY_EVENT_TYPE_MODE_CHANGED, mode); + * + * // Fires a MyEvent with asynchronous mode. + * // _Event takes the ownership of the pArg and will delete it after it is delivered to listeners. + * __pMyEvent->Fire(*pArg); + * } + * + * @endcode + * @return An error code + * @param[in] arg The event argument. + * @exception E_SUCCESS This method was successful. + * @exception E_INVALID_STATE This event has not been initialized. + * + * @remark This takes the ownership of @c arg. So arg should be created on a heap and should not be deleted. + */ + result Fire(IEventArg& arg); + + /** + * Fires the event with an argument asynchronously. + * This post the event in the event queue of the thread that the event belongs to. And the listener will + * be called on that thread context. + * + * @since 2.0 + * + * @code + * void + * MyClass::SendModeChangeEvent(int mode) + * { + * // An event argument should be created on a heap. + * MyEventArg* pArg = new MyEventArg(MY_EVENT_TYPE_MODE_CHANGED, mode); + * + * // Fires a MyEvent with asynchronous mode. + * // _Event takes the ownership of the pArg and will delete it after it is delivered to listeners. + * __pMyEvent->Fire(*pArg); + * } + * + * @endcode + * @return An error code + * @param[in] arg The event argument. + * @exception E_SUCCESS This method was successful. + * @exception E_INVALID_STATE This event has not been initialized. + * @exception E_INVALID_OPERATION This event does not support asynchronous mode. + * + * @remark This takes the ownership of @c arg. So arg should be created on a heap and should not be deleted. + */ + result FireAsync(IEventArg& arg); + + /** + * Fires the event with an argument asynchronously. + * + * @since 2.1 + * + * @return The number of listeners in the current event instance. + */ + int GetListenerCount(void); +protected: + /** + * Initializes the event + * + * @since 2.0 + * + * @code + * result + * MyEvent::Construct(void) + * { + * _Event::Initialize(); // You should always invoke this method at your event construction phase + * } + * @endcode + * + * @return An error code + * @exception E_SUCCESS This method was successful. + * @exception E_INVALID_STATE The event was already initialized. + * @exception E_INVALID_OPERATION This was called by a worker thread. + * + * @remark A derived class from _Event should call this method + */ + result Initialize(void); + + /** + * Implement to call the corresponding event listener's method. + * + * @since 2.0 + * + * @code + * void + * MyEvent::FireImpl(IEventListener& listener, const IEventArg& arg) + * { + * const MyEventArg* pMyEventArg = dynamic_cast(&arg); + * IMyEventListener* pMyEventListener = dynamic_cast(&listener); + * + * if (pMyEventArg->GetType() == MY_EVENT_TYPE_LEVEL_CHANGED) + * { + * pMyEventListener->OnLevelChanged(pMyEventArg->GetValue()); + * } + * else (pMyEventArg->GetType() == MY_EVENT_TYPE_MODE_CHANGED) + * { + * pMyEventListener->OnModeChanged(pMyEventArg->GetValue()); + * } + * else + * { + * + * } + * } + * @endcode + * + * @param[in] listener The listener instance which is currently processing + * @param[in] arg The event argument that is fired + * + * @remark A derived class must override this method. + */ + virtual void FireImpl(IEventListener& listener, const IEventArg& arg); + +private: + _Event(const _Event& rhs); + + _Event& operator =(const _Event& rhs); + + result Fire(std::tr1::shared_ptr< IEventArg > arg); + + result ProcessListeners(std::tr1::shared_ptr< IEventArg > arg); + + const _HandleT< _Event > GetHandle(void) const; + + _HandleT< _Event > GetHandle(void); + +private: + struct _ListenerInfo + { + _ListenerInfo(void) + : pListener(null) + { + } + + const IEventListener* pListener; + _HandleT< IEventListener > listener; + _HandleT< _EventManager > eventManager; + + bool operator ==(const _ListenerInfo& rhs) const; + bool operator !=(const _ListenerInfo& rhs) const; + + _ListenerInfo& operator =(const _ListenerInfo& rhs); + }; + + struct _RefCount + { + _RefCount(void); + ~_RefCount(void); + + int AddRef(void); + int Release(void); + + private: + int __count; + bool __destroyed; + + friend class _Event; + }; + +private: + Tizen::Base::Collection::LinkedListT< _ListenerInfo > __listeners; + + _RefCount* __pRefCount; + + _HandleT< _EventManager > __eventManager; + _HandleT< _Event > __handle; + + friend class _EventManager; +}; // _Event + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_EVENT_H_ diff --git a/src/base/inc/FBaseRt_EventDispatcher.h b/src/base/inc/FBaseRt_EventDispatcher.h new file mode 100644 index 0000000..92dd168 --- /dev/null +++ b/src/base/inc/FBaseRt_EventDispatcher.h @@ -0,0 +1,134 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventDispatcher.h + * @brief This is the header file for the %_EventDispatcher class. + * + * This file contains the declarations of the %_EventDispatcher class. + */ + + +#ifndef _FBASE_RT_INTERNAL_EVENT_DISPATCHER_H_ +#define _FBASE_RT_INTERNAL_EVENT_DISPATCHER_H_ + +#include + +#include +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _ITask; +class Mutex; + +/** +* @class _EventDispatcher +* @brief This class provides methods for _EventDispatcher. +* @since 2.0 +* +* This class provides methods for asynchronous operation. +*/ +class _OSP_EXPORT_ _EventDispatcher + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * value. + * + * @since 2.0 + */ + _EventDispatcher(void); + + + /** + * This is the destructor for this class + * @since 2.0 + */ + virtual ~_EventDispatcher(void); + + /** + * Initializes this instanc of %_EventDispatcher. + * + * @since 2.0 + * @return An error code + * @param[in] pGMainContext A GMainLoopContext + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM An unknown operating system error occurred. + */ + result Construct(GMainContext* pGMainContext); + + /** + * Returns an %_EventDispatcher of current thread. + * + * @since 2.0 + * @return The pointer of _EventDispatcher + */ + static _EventDispatcher* GetCurrentEventDispatcher(void); + + + /** + * Add an asynchronous task to an %_EventDispatcher. + * + * @since 2.0 + * @return An error code + * @param[in] pITask An _ITask to send + * @param[in] pParam A param + * @exception E_SUCCESS The method was successful. + */ + result PutTask(_ITask* pITask, void* pParam); + + + /** + * Returns the GMainContext + * + * @since 2.0 + * @return The pointer of GMainContext + */ + GMainContext* GetGMainContext(void); + +private: + /** + * Handles incoming events + */ + static gboolean OnEventReceived(GIOChannel* pGIOChannel, GIOCondition condition, gpointer data); + + _EventDispatcher(const _EventDispatcher& rhs); + + _EventDispatcher& operator =(const _EventDispatcher& rhs); + +private: + struct _EventMessage + { + _ITask* pITask; + void* pParam; + }; + +private: + Mutex* __pMutex; + Tizen::Base::Collection::LinkedListT <_EventMessage*> __events; + GMainContext* __pGMainContext; + GIOChannel* __pEventFdIo; + GSource* __pEventFdSource; +}; // _EventDispatcher + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_EVENT_DISPATCHER_H_ diff --git a/src/base/inc/FBaseRt_IEventListener.h b/src/base/inc/FBaseRt_IEventListener.h new file mode 100644 index 0000000..7d6ac51 --- /dev/null +++ b/src/base/inc/FBaseRt_IEventListener.h @@ -0,0 +1,53 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_IEventListener.h + * @brief This is the header file for the %_IEventListener class. + * + * This file contains the declarations of the %_IEventListener class. + */ + +#ifndef _FBASE_RT_INTERNAL_IEVENT_LISTENER_H_ +#define _FBASE_RT_INTERNAL_IEVENT_LISTENER_H_ + +namespace Tizen { namespace Base { namespace Runtime +{ +/** + * @interface _IEventListener + * @brief This is a tagging interface that all event listeners must implement. + * @since 2.0 + * + * The event listener can listen when the specific event is fired. The event listener + * has several methods, and each method will be called when the specific event is fired. + * + */ +class _IEventListener +{ +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_IEventListener(void) {} +}; // _IEventListener + + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_IEVENT_LISTENER_H_ diff --git a/src/base/inc/FBaseRt_ITask.h b/src/base/inc/FBaseRt_ITask.h new file mode 100644 index 0000000..a9e526a --- /dev/null +++ b/src/base/inc/FBaseRt_ITask.h @@ -0,0 +1,44 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_ITask.h + * @brief This is the header file for the %_ITask class. + * + * This file contains the declarations of the %_ITask class. + */ + +#ifndef _FBASE_RT_INTERNAL_ITASK_H_ +#define _FBASE_RT_INTERNAL_ITASK_H_ + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _OSP_EXPORT_ _ITask +{ +public: + virtual ~_ITask(void); + virtual void* DoTask(void* pParam) = 0; +}; // _ITask + +} } } // Tizen::Base::Runtime + + +#endif // _FBASE_RT_INTERNAL_ITASK_H_ diff --git a/src/base/inc/FBaseRt_LibraryImpl.h b/src/base/inc/FBaseRt_LibraryImpl.h new file mode 100644 index 0000000..c20f4d0 --- /dev/null +++ b/src/base/inc/FBaseRt_LibraryImpl.h @@ -0,0 +1,126 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_LibraryImpl.h + * @brief This is the header file for the %_LibraryImpl class. + * + * This file contains the declarations of the %_LibraryImpl class. + */ + +#ifndef _FBASE_RT_INTERNAL_LIBRARY_IMPL_H_ +#define _FBASE_RT_INTERNAL_LIBRARY_IMPL_H_ + +#include +#include + +namespace Tizen { namespace Base { class String; }} + +namespace Tizen { namespace Base { namespace Runtime +{ +/** +* @enum _LibraryLoadOption +* Defines the library loading options. +* +* @since 2.0 +*/ +enum _LibraryLoadOption +{ + _LIBRARY_LOAD_OPTION_LAZY = 0x1, /** < Lazy binding. This option cannot be used with _LIBRARY_LOAD_OPTION_NOW */ + _LIBRARY_LOAD_OPTION_NOW = 0x2, /** < All undefined symbols in the library are resolved + This option cannot be used with _LIBRARY_LOAD_OPTION_LAZY. */ + _LIBRARY_LOAD_OPTION_GLOBAL = 0x4, /** < The symbols defined by this library will be made available for symbol + resolution of subsequently loaded libraries. + This option cannot be used with _LIBRARY_LOAD_OPTION_LOCAL */ + _LIBRARY_LOAD_OPTION_LOCAL = 0x8, /** < Symbols defined in this library are not made available to resolve references + in subsequently loaded libraries. + This option cannot be used with _LIBRARY_LOAD_OPTION_GLOBAL*/ + _LIBRARY_LOAD_OPTION_NODELETE = 0x10, /** < Do not unload the library during destroy*/ +}; + +/** + * @brief This is the class for shared library. + * @since 2.0 + * + * @final This class is not intended for extension. + * + * This class loads the shared library with the given file path. @n + * It loads the library in current process' memory space, and application can use this library explicitly. + */ +class _LibraryImpl + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _LibraryImpl(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_LibraryImpl(void); + + /** + * Initializes the dynamic linking library instance. @n + * It loads the library in current process' memory space. + * + * @since 2.0 + * + * @param[in] libraryPath The path of the library file + * @param[in] option Library loading option. One of _LIBRARY_LOAD_OPTION_LAZY or _LIBRARY_LOAD_OPTION_NOW must be included. + * And a bitwise-or of other values in _LibraryLoadOption to it is possible. + * @return An error code + * + * @exception E_SUCCESS The method is successful. + * @exception E_LIBRARY_NOT_FOUND The library cannot be found. + * @exception E_INVALID_ARG The path is null or the option is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(const Tizen::Base::String& libraryPath, unsigned long option = _LIBRARY_LOAD_OPTION_LAZY); + + /** + * Gets the address of the specified symbol. + * + * @since 2.0 + * + * @return The address of the specified symbol + * @param[in] symbol Symbol of the address to get + * + * @exception E_SUCCESS The method is successful. + * @exception E_SYMBOL_NOT_FOUND The symbol can not be found in the symbol table of the dynamic linking library. + * @exception E_INVALID_STATE The library is not loaded yet. + * @exception E_INVALID_ARG The symbol is null. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * + */ + void* GetProcAddress(const Tizen::Base::String& symbol); + +private: + void* __pHandle; + +}; // _LibraryImpl + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_LIBRARY_IMPL_H_ diff --git a/src/base/inc/FBaseRt_MainLoop.h b/src/base/inc/FBaseRt_MainLoop.h new file mode 100644 index 0000000..b063d83 --- /dev/null +++ b/src/base/inc/FBaseRt_MainLoop.h @@ -0,0 +1,119 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_MainLoop.h + * @brief This is the header file for the %_MainLoop class. + * + * This file contains the declarations of the %_MainLoop class. + */ + +#ifndef _FBASE_RT_INTERNAL_MAIN_LOOP_H_ +#define _FBASE_RT_INTERNAL_MAIN_LOOP_H_ + +#include + +#include +#include +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +class Mutex; +class _IMainLoopEventListener; + +/** +* @class _MainLoop +* @brief This class provides methods for _MainLoop. +* @since 2.0 +* +* This class provides methods for asynchronous operation. +*/ +class _MainLoop + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * value. + * + * @since 2.0 + */ + _MainLoop(void); + + /** + * This is the destructor for this class + * @since 2.0 + */ + virtual ~_MainLoop(void); + + /** + * Initializes this instanc of %_MainLoop. + * + * @since 2.0 + * @return An error code + * @param[in] pGMainContext A GMainLoopContext + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM An unknown operating system error occurred. + */ + result Construct(GMainLoop* pGmainLoop, GMainContext* pGmainContext); + + GMainContext* GetGmainContext(void) const; + + /** + * Returns an %_MainLoop of current thread. + * + * @since 2.0 + * @return The pointer of _MainLoop + */ + static _MainLoop* GetCurrentMainLoop(void); + +private: + result SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs); + + void SetMainLoopEventListener(_IMainLoopEventListener* pListener); + + static gboolean OnMessageArrived(GIOChannel* pChannel, GIOCondition condition, gpointer data); + + struct _Message + { + RequestId requestId; + const void* pArgs; + + bool operator== (const _Message& rhs) const; + bool operator!= (const _Message& rhs) const; + }; + +private: + GMainLoop* __pGmainLoop; + GMainContext* __pGmainContext; + GIOChannel* __pChannel; + GSource* __pSource; + Mutex* __pMutex; + _IMainLoopEventListener* __pListener; + Tizen::Base::Collection::ArrayListT<_Message> __messages1; + Tizen::Base::Collection::ArrayListT<_Message> __messages2; + Tizen::Base::Collection::ArrayListT<_Message>* __pActive; + Tizen::Base::Collection::ArrayListT<_Message>* __pReady; + +}; // _MainLoop + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_MAIN_LOOP_H_ diff --git a/src/base/inc/FBaseRt_Process.h b/src/base/inc/FBaseRt_Process.h new file mode 100644 index 0000000..23e8b93 --- /dev/null +++ b/src/base/inc/FBaseRt_Process.h @@ -0,0 +1,84 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_Process.h + * @brief This is the header file for the %_Process class. + * + * This file contains the declarations of the %_Process class. + */ + +#ifndef _FBASE_RT_INTERNAL_PROCESS_H_ +#define _FBASE_RT_INTERNAL_PROCESS_H_ + +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** +* The constant for success termination code. +* +* @since 2.0 +*/ +static const int EXIT_CODE_SUCCESS = 0; + +/** +* The constant for failure termination code. +* +* @since 2.0 +*/ +static const int EXIT_CODE_FAILURE = 1; + +/** +* @class _Process +* @brief This class provides method for managing process. +* @since 2.0 +*/ +class _OSP_EXPORT_ _Process +{ +public: + /** + * Terminates current process. + * + * @since 2.0 + * + * @param[in] exitCode The exit code + */ + static void Exit(int exitCode); + +private: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _Process(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + ~_Process(void); + +}; // _Process + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_PROCESS_H_ diff --git a/src/base/inc/FBaseUtil_IcuConverter.h b/src/base/inc/FBaseUtil_IcuConverter.h new file mode 100644 index 0000000..192622b --- /dev/null +++ b/src/base/inc/FBaseUtil_IcuConverter.h @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtil_IcuConverter.h + * @brief This is the header file for _ICUConverter. + */ + +#ifndef _FBASE_UTIL_ICU_CONVERTER_H_ +#define _FBASE_UTIL_ICU_CONVERTER_H_ + +#include "unicode/ucnv.h" +#include "unicode/utypes.h" +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +class _ICUConverter +{ + public: + _ICUConverter(); + ~_ICUConverter(); + + private: + result GetResultFromIcuErrorCode(UErrorCode& err); + public: + bool OpenConverter(const Tizen::Base::String& encodingScheme); + wchar_t* ConvertToUcharN(const char* src, int srcLength); + char* ConvertFromUcharN(const wchar_t* pSrc, int srcLength, int& retLength); + void CloseConverter(void); + + private: + UConverter* __pConverter; +}; // _ICUConverter + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_ICU_CONVERTER_H_ diff --git a/src/base/inc/FBase_Exception.h b/src/base/inc/FBase_Exception.h new file mode 100644 index 0000000..ec0e732 --- /dev/null +++ b/src/base/inc/FBase_Exception.h @@ -0,0 +1,403 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBase_Exception.h + * @brief This file defines the exception types. + */ + +#ifndef _FBASE_INTERNAL_EXCEPTION_H_ +#define _FBASE_INTERNAL_EXCEPTION_H_ + +/** + * Exception type. Refer to Exceptions for more information. + */ +typedef int Exception; +/** + * Exception Group + */ +enum _ExceptionBase +{ + GENERAL_EXCEPTION_GROUP, /**< %General Exception Group @n*/ + BASE_EXCEPTION_GROUP, /**< %Base Exception Group @n*/ + SERVICE_EXCEPTION_GROUP, /**< %Service Exception Group @n*/ + GROUP_EXCEPTION_GROUP, /**< %GROUP_ Exception Group @n*/ + SECURITY_EXCEPTION_GROUP, /**< %Security Exception Group @n*/ + STORAGE_EXCEPTION_GROUP, /**< %Storage Exception GROUP_*/ + CONTEXT_EXCEPTION_GROUP, /**< %Context Exception Group @n*/ + SECOND_LIFE_EXCEPTION_GROUP, /**< %Secondlife Exception Group @n*/ + LOCATION_EXCEPTION_GROUP, /**< %Location Exception Group @n*/ + EMS_CLIENT_EXCEPTION_GROUP, /**< %EMS client Exception Group @n*/ + DEVICE_EXCEPTION_GROUP, /**< %Device Exception Group @n*/ + UNDEFINED_EXCEPTION_GROUP /**< %Undefined Exception Group @n*/ +}; + +#define EXCEPTION_BASE(x) ((x) << 16) +#define EXCEPTION_INDEX(x) ((x) & 0xffff) + + +#ifndef Success +#define Success EXCEPTION_BASE(GENERAL_EXCEPTION_GROUP) +#endif + +/** + * @enum _Exceptions + * + * Pre-defined exceptions. + */ +enum _Exceptions +{ + // General exception + OUT_OF_MEMORY = EXCEPTION_BASE(GENERAL_EXCEPTION_GROUP) + 1, /**< No sufficient memory to allocate */ + INDEX_OUT_OF_BOUNDS_EXCEPTION, /**< %The index of array is out of bounds. */ + INSTANCE_ALREADY_EXISTS_EXCEPTION, /**< %Instance already exists. */ + ILLEGAL_ARGUMENT_EXCEPTION, /**< %Input parameter(s) is/are invalid. */ + ILLEGAL_ACCESS_EXCEPTION, /**< %Operation is not permitted. */ + ILLEGAL_STATE_EXCEPTION, /**< %The current state is not proper for the next operation. */ + NULL_POINTER_EXCEPTION, /**< %Pointer is null. */ + UNDEFINED_TYPE_EXCEPTION, + NOT_IMPLEMENTED_EXCEPTION, /**< %Method is not yet implemented. */ + PARSE_EXCEPTION, /**< %Parsing of file/data failed. */ + DATA_FORMAT_EXCEPTION, /**< %Data format error has occurred. */ + SYSTEM_EXCEPTION, /**< %System operation is not working correctly. */ + IOEXCEPTION, /**< %I/O operation is not working correctly. */ + NETWORK_CONNECTION_EXCEPTION, /**< %Network is disconnected. */ + ARITHMETIC_EXCEPTION, /**< %Unexpected arithmetic exception */ + TIME_OUT_EXCEPTION, /**< %Timed operation is expired. */ + UNKNOWN_EXCEPTION, /**< %Unknown exception */ + UNKNOWN_ERROR, /**< %Unknown error @n*/ + END_OF_GENERAL_EXCEPTION, + + // BASE_ exception + CREATE_FAILED_EXCEPTION, /**< The creation of an object failed. */ + NO_SUCH_INSTANCE_EXCEPTION, /**< Instance is not found. */ + COMPONENT_NOT_FOUND_EXCEPTION, /**< %Component is not found. */ + METHOD_NOT_FOUND_EXCEPTION, /**< %Class factory or general function entry is not found. */ + INTERFACE_NOT_FOUND_EXCEPTION, /**< %Interface is not found. */ + SECTION_NOT_FOUND_EXCEPTION, /**< %Section is not found. */ + ENTRY_NOT_FOUND_EXCEPTION, + VALUE_NOT_ASSIGNED_EXCEPTION, + INVALID_DOCUMENT_EXCEPTION, + + FILE_LONG_PATH_EXCEPTION, + FILE_INVALID_PATH_EXCEPTION, + FILE_NOT_FOUND_EXCEPTION, + FILE_ALREADY_EXIST_EXCEPTION, + FILE_END_OF_FILE_EXCEPTION, + FILE_PERMISSION_EXCEPTION, + FILE_NOT_EMPTY_DIR_EXCEPTION, + FILE_OPEN_LIMIT_EXCEEDED_EXCEPTION, + FILE_CORRUPTED_EXCEPTION, + FILE_VOLUME_FULL_EXCEPTION, + FILE_QUOTA_EXCEEDED_EXCEPTION, + FILE_DEVICE_FAILURE_EXCEPTION, + FILE_VOLUME_NOT_MOUNTED_EXCEPTION, + FILE_MEDIA_EJECTED_EXCEPTION, + FILE_PANIC_EXCEPTION, + + KEY_NOT_FOUND_EXCEPTION, /**< %key is not found. */ + ACTOR_NOT_FOUND_EXCEPTION, /**< %Actor is not found. */ + CONTEXT_MODEL_NOT_FOUND_EXCEPTION, /**< %Context model is not found. */ + LISTENER_NOT_FOUND_EXCEPTION, /**< %Listner is not found. */ + CHANNEL_NOT_FOUND_EXCEPTION, /**< %Channel is not found */ + + IPC_PROXY_METHOD_EXCEPTION, /**< %IPC proxy method is failed */ + IPC_STUB_METHOD_EXCEPTION, /**< %IPC stub method is failed */ + STUB_IS_ALREADY_RUNNING, /**< %Stub is already running */ + NO_STUB_FOUND, /**< %No such stub is running */ + NO_PROXY_FOUND, + NO_SUCH_PROXY_CONNECTED, /**< %proxy is not exist */ + NO_IPC_LISTENER_FOUND, /**< %No listener is registered */ + NO_IPC_EVENT_FOUND, /**< %Stub has no such event @n*/ + IPC_USER_DATA_ALREADY_EXIST, + IPC_STUB_NO_USER_DATA_FOUND, + IPC_ADD_LISTENER_DENIED, + IPC_EVENT_NOT_FOUND, + IPC_INTERFACE_NOT_FOUND, + IPC_NO_LISTENER_FOUND, + IPC_ALL_IPC_CALL_SLOT_IS_USING, + IPC_NO_AVAILABLE_ID, + IPC_MSG_QUEUE_NOT_FOUND, + DATA_BASE_ERROR_EXCEPTION, /**< Exceptions thrown from db engine. And it includes errors related to syntax or usage. */ + DATA_BASE_TOO_BIG_EXCEPTION, /**< String or BLOB exceeds size limit. */ + DATA_BASE_BUSY_EXCEPTION, /**< The database file is locked. */ + DATA_BASE_END_OF_RESULT_SET, /**< Reached the end of result set. */ + DATA_BASE_NOT_CHANGED_EXCEPTION, /**< There was no changes on table after INSERT, UPDATE, DELETE. */ + APP_IDALREADY_EXIST_, + APP_IDIS_NOT_EXIST_, + ENCODING_FAILED_EXCEPTION, + DECODING_FAILED_EXCEPTION, + + + END_OF_BASE_EXCEPTION, + + // service exception + SERVICE_ALREADY_REGISTERED_EXCEPTION, /**< Service Already is registered */ + XML_PARSING_EXCEPTION, /**< %Xml parsing is fail. */ + SERVICE_NOT_REGISTERED_EXCEPTION, /**< %Service is not registered. */ + EVENT_SOURCE_NOT_REGISTERED_EXCEPTION, /**< %Event SourceID is not registered. */ + SERVER_EXCEPTION, /**< %Server side system error. */ + INVALID_PEER_CREDENTIAL_EXCEPTION, /**< %Peer Credential is invalid. */ + UNSUPPORTED_PROTOCOL_EXCEPTION, /**< %UnSupport protocol context. */ + UNSUPPORTED_ENCODING_EXCEPTION, /**< %UnSupport encoding. */ + DOM_EXCEPTION, /**< %DomException. */ + INVALID_MESSAGE_TYPE_EXCEPTION, /**< %Invalid message type Exception @n*/ + NETWORK_ABORT_EXCEPTION, /**< %Network abort Exception @n*/ + NETWORK_ALREADY_ABORTED_EXCEPTION, /**< %Network is already aborted @n*/ + NETWORK_ABORT_FAILED_EXCEPTION, /**< %network abort is fail @n*/ + END_OF_SERVICE_EXCEPTION, + + // group exception + GROUP_NOT_FOUND_EXCEPTION, /**< GROUP_ is not found */ + USER_NOT_FOUND_EXCEPTION, /**< %User is not found. */ + SERVICE_NOT_FOUND_EXCEPTION, /**< %Service is not found. */ + ATTRIBUTE_NOT_FOUND_EXCEPTION, /**< %Attribute is not found. */ + DUPLICATE_ATTRIBUTE_EXCEPTION, /**< %Attribute already exists. */ + ALREADY_JOINED_GROUP_EXCEPTION, /**< %Alread joined group. */ + NOT_JOINED_GROUP_EXCEPTION, /**< %Not a member of the group. */ + ALREADY_INVITED_EXCEPTION, /**< %The user is already invited. */ + INVITATION_NOT_FOUND_EXCEPTION, /**< %There is no invitation for the user.*/ + MAX_MEMBER_EXCEEDED_EXCEPTION, /**< %Maximum number of allowed members in this group has exceeded. */ + NOT_PERMITTED_GENDER_EXCEPTION, /**< %The gender constraint of this group. */ + CATEGORY_NOT_FOUND_EXCEPTION, /**< %Category is not found. */ + DUPLICATE_JOIN_REQUEST_EXCEPTION, /**< %The group already has the join request. */ + JOIN_PROHIBHITED_EXCEPTION, /**< %Joining this group is prohibited by the owner. (Expelled member). */ + DUPLICATE_GROUP_NAME_EXCEPTION, + + + END_OF_GROUP_EXCEPTION, + + // security exception + SIGN_FAILED_EXCEPTION, /**< %Generation signature failed. */ + INVALID_SIGNATURE_EXCEPTION, /**< %Signature is not valid */ + VERSION_NOT_MATCH_EXCEPTION, /**< %Version is not matched */ + + AMBIGOUS_CREDENTIAL_EXCEPTION, /**< %Credential is not unique. */ + CREDENTIAL_FOUND_EXCEPTION, /**< %Credential is not found. */ + + ALREADY_USER_REGISTERED_EXCEPTION, /**< %Already user registered to server @n*/ + USER_NOT_REGISTERED_EXCEPTION, /**< %The user didn't register to server @n*/ + ALREADY_USER_AUTHENTICATED_EXCEPTION, /**< %Already user AUTHENTICATED_ to server @n*/ + USER_NOT_AUTHENTICATED_EXCEPTION, /**< %The user didn't Authenticate to server @n*/ + USER_IDNOT_MATCHED_EXCEPTION, /**< %The user ID in the device and loginID is not matched @*/ + + ENCRYPT_FAILED_EXCEPTION, + DECRYPT_FAILED_EXCEPTION, + HMACFAILED_EXCEPTION, + RANDOM_BYTE_FAILED_EXCEPTION, + HASH_FAILED_EXCEPTION, + PASSWORD_NOT_MATCHED_EXCEPTION, + + PRIVILEGEDENIEDEXCEPTION, + + END_OF_SECURITY_EXCEPTION, + + // storage exception + PATH_NOT_FOUND_EXCEPTION, /**< Path is not found.*/ + PATH_ALREADY_EXIST_EXCEPTION, /**< %Path already exists. @n*/ + + END_OF_STORAGE_EXCEPTION, + + // context exception + CONTEXT_MODEL_COUNT_MAX_EXCEPTION, /**< Context model count is exceeded.*/ + DATA_NOT_FOUND_EXCEPTION, /**< %Data is not found. */ + SQLEXCEPTION, /**< %Database access error */ + INVALID_SENSOR_CIDEXCEPTION, /**< %Sensor CID in *.xsd file is invalid. */ + OBJECT_DATA_NOT_FOUND_EXCEPTION, /**< %Object is not found. */ + ILLEGAL_CONDITION_OBJECT_EXCEPTION, /**< %Context condition's object is invalid. */ + ILLEGAL_CONDITION_CHANNEL_EXCEPTION, /**< %Context condition's channel is invalid. */ + INVALID_MODEL_DEFINITION_EXCEPTION, /**< %Definition of context model is invalid. */ + NO_SUCH_TABLE_EXCEPTION, /**< %Table name is not found */ + SERVICE_UNAVAILABLE_EXCEPTION, /**< %Server is not working. */ + + // context query processor exception + CONTEXT_STORAGE_NOT_FOUND_EXCEPTION, /**< Context storage is not found. */ + CONTEXT_STORAGE_EXIST_EXCEPTION, /**< %Context storage exists. */ + CONTEXT_TYPE_NOT_FOUND_EXCEPTION, /**< %Context type described on CQL is not found in context storage. */ + CONTEXT_STORAGE_NOT_OPENED_EXCEPTION, /**< %Context storage is not opened. */ + CONTEXT_STORAGE_NOT_CLOSED_EXCEPTION, /**< %Context storage is not closed. */ + CONTEXT_ELEMENT_NOT_FOUND_EXCEPTION, /**< %Context element described on CQL is not found in context storage. */ + CURSOR_NOT_DELETED_EXCEPTION, /**< %Cursors ofa context storage is still being used. */ + + CAN_NOT_LAUNCH_SERVER_EXCEPTION, /**<%Failed to launch server instance. */ + CAN_NOT_ALLOC_RESOURCE_EXCEPTION, /**<%Failed to allocate system resources such as mutex, thread, file, timer and so on. */ + TOO_MANY_ON_GOING_SESSIONS_EXCEPTION, /**< %Too many sessions are present. */ + CAN_NOT_DECODE_EXCEPTION, /**< %Can not proceed any more in parsing string or decoding data. */ + INVALID_ENCODE_TYPE_EXCEPTION, /**< %Undefined or unknown type was found during encode/decode. */ + NEED_CO_PROCESSOR_EXCEPTION, /**< %When initialization of co-processor is missed, let the user launch missed server instance according to module dependency. */ + CO_PROCESSING_EXCEPTION, /**< %Caught exception after execution of subsystem or co-processing module. */ + CAUGHT_BROKEN_INTERNALS_EXCEPTION, /**< %Caught inconsistent state of current system or availability of malfunction. */ + CAUGHT_INCOMPLETE_CODE_EXCEPTION, /**< %Caught unexpected exception from sub-system or co-processing module/library. */ + NOT_CQPENABLED_DEVICE_NAME_EXCEPTION, /**< %Given device is not a CQP enabled, or temporarily fall in blacklist due to current network connectivity or machine failure. */ + CAN_NOT_FIND_ENTITY_EXCEPTION, /**< %Can notnot find entity in container. */ + EXCEED_MAXIMUM_BUFFER_LIMIT_EXCEPTION, /**< %Exceeded maximum buffer limitation during encoding or decoding raw data. */ + REMOTE_EXECUTE_QUERY_EXCEPTION, /**< %Common exception which represents for multiple remote exceptions came from remote devices during executequery()/executequery2() family In this case, all the remote devices delivered exception */ + + INVALID_HANDLE_EXCEPTION, + SESSION_ALREADY_IN_PROGRESS_EXCEPTION, + EXCEED_MAXIMUM_HANDLE_COUNT_EXCEPTION, + TOO_MANY_ON_GOING__TASKS_EXCEPTION, + INVALID_CQL_STATEMENT_EXCEPTION, + TYPE_MISMATCHING_EXCEPTION, + ALREADY_REGISTERED_EXCEPTION, + LOADING_CSR256_FAILED_EXCEPTION, + END_OF_RESULT_SETEXCEPTION, + NOT_SUPPORTED_OPERATION_EXCEPTION, + HANDLE_CLOSED_BY_OTHER_THREAD_EXCEPTION, + REQUEST_CANCELED_BY_OTHER_THREAD_EXCEPTION, + QUERY_EXECUTION_NOT_COMPLETED_EXCEPTION, + INVALID_CURSOR_OBJECT_EXCEPTION, + TRIGGER_FIRED_EXCEPTION, + INVALID_CURSOR_POSITION_EXCEPTION, + EMPTY_CURSOR_OBJECT_EXCEPTION, + OPENED_HANDLE_EXIST_EXCEPTION, + + // context importer exception + DBCONNECTION_FAILED_EXCEPTION, /**< %Initializing DB CONNECTION is failed */ + SQLEXECUTION_FAILED_EXCEPTION, /**< %executing SQL query is failed @n*/ + + //Rfid exceptions + TAG_NOT_FOUND_EXCEPTION, /**< Tag was not found*/ + TAG_LOGIN_FAILED_EXCEPTION, /**< %Login to tag failed */ + TAG_ERROR_EXCEPTION, /**<%Tag returned error */ + NO_DATA_ON_TAG_EXCEPTION, /**<%Tag contains no data */ + INCOMPATIBLE_TAG_EXCEPTION, /**<%Tag is not matrix compatible */ + TAG_LOCKED_EXCEPTION, /**<%Tag is Locked @n*/ + END_OF_CONTEXT_EXCEPTION, + + // SECOND_LIFE_EXCEPTION_GROUP + NOT_LOGGED_IN_EXCEPTION, /**< Not logged in the second life server */ + BALANCE_NOT_RECIEVED_EXCEPTION, /** +#include "FBase_ObjectManagerImpl.h" + +namespace Tizen { namespace Base +{ + +template +class _ObjectManagerT; + +template +class _HandleT + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _HandleT(void) + : __handle(0), __pObjectManagerImpl(null) + { + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_HandleT(void) + { + } + + /** + * Checks whether the handle is initialized or not. + * + * @since 2.0 + * @return @c true if the handle is not initialized, @n + else @c false + */ + bool IsNull(void) const + { + return __handle == 0; + } + + /** + * Checks whether the handle is valid or not. + * + * @since 2.0 + * return @c true if the handle is valid, @n else @c false + */ + bool IsValid(void) const + { + if (__handle == 0 || __pObjectManagerImpl == null) + { + return false; + } + + return __pObjectManagerImpl->IsValidHandle(__handle); + } + + /** + * Get the signed @c int equivalent of the current instance. + * + * @since 2.0 + * @return Signed @c int equivalent of the current instance + */ + int ToInt(void) const + { + return (int)__handle; + } + + /** + * Checks whether the two instances of _HandleT are equal. + * + * @since 2.0 + * @return @c true if the values of the two instances of _HandleT are similar, @n + * else @c false + * @param[in] rhs An instance of %_HandleT + */ + inline bool operator ==(const _HandleT & rhs) const + { + return __handle == rhs.__handle; + } + + /** + * Checks whether the two instances of _HandleT are not equal. + * + * @since 2.0 + * @return @c true if the values of the two instances of _HandleT are not similar, @n + * else @c false + * @param[in] rhs An instance of %_HandleT + * + */ + inline bool operator !=(const _HandleT & rhs) const + { + return !(*this == rhs); + } + + _HandleT(const _HandleT& handle) + { + this->__handle = handle.__handle; + this->__pObjectManagerImpl = handle.__pObjectManagerImpl; + } + + _HandleT& operator = (const _HandleT& handle) + { + if (this == &handle) + { + return *this; + } + + this->__handle = handle.__handle; + this->__pObjectManagerImpl = handle.__pObjectManagerImpl; + + return *this; + } + +private: + void Initialize(unsigned int handle, _ObjectManagerImpl* pObjectManagerImpl) + { + __handle = handle; + __pObjectManagerImpl = pObjectManagerImpl; + } + +private: + unsigned int __handle; + _ObjectManagerImpl* __pObjectManagerImpl; + + friend class _ObjectManagerT ; +}; // _HandleT + +}} // Tizen::Base + +#endif // _FBASE_RT_INTERNAL_HANDLE_TEMPLATE_H_ diff --git a/src/base/inc/FBase_Log.h b/src/base/inc/FBase_Log.h new file mode 100644 index 0000000..518bb06 --- /dev/null +++ b/src/base/inc/FBase_Log.h @@ -0,0 +1,100 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBase_Log.h + * @brief This file is internal header for Log. + */ + +#ifndef _FBASE_INTERNAL_LOG_H_ +#define _FBASE_INTERNAL_LOG_H_ + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +#define LOG_MODULE_NAME_LEN_MAX 30 +#define LOG_TAG_LEN_MAX 50 +#define LOG_LEN_MAX 1024 +#define PROPAGATION_LEN_MAX 512 + +#define NID_MAX 190 + +/** + * LogEntry + * + */ +typedef struct LogEntry +{ + int logID; + char logIDName[LOG_MODULE_NAME_LEN_MAX]; + char logModuleName[LOG_MODULE_NAME_LEN_MAX]; + bool loggingEnabled; +} LogEntry; + +/** + * LogInfo + */ +typedef struct LogInfo +{ + LogEntry logTable[NID_MAX]; + + bool consoleOut; + bool fileOut; + + bool platformInfoEnabled; + bool platformExceptionEnabled; + + bool applicationInfoEnabled; + bool applicationDebugEnabled; + bool applicationExceptionEnabled; +} LogInfo; + +/** + * Log Types + */ +enum _LogType +{ + LOG_INFO = 10, + LOG_DEBUG = 11, + LOG_EXCEPTION = 12, + LOG_USER = 13 +}; + +void __PrintLog(_LogType type, const char* pFunction, int lineNumber, const char* pFormat, va_list args); +void __PrintLogTag(const char* pTag, _LogType type, const char* pFunction, int lineNumber, const char* pFormat, va_list args); +void __PrintSysLog(_LogType type, LogID id, const char* pFunction, int lineNumber, const char* pFormat, va_list args); +void __PrintSysLogTag(const char* pTag, _LogType type, LogID id, const char* pFunction, int lineNumber, const char* pFormat, va_list args); + +char* __GetModuleName(LogID id); +bool __GetEnableInfo(LogID id); + +void __InitializeLogInfo(void); +void __InitializeLogLevel(const Tizen::Io::Registry& reg); +void __InitializePlatformModule(const Tizen::Io::Registry& reg); + +#ifdef __cplusplus +} +#endif // __cplusplus + + +#endif // _FBASE_INTERNAL_LOG_H_ diff --git a/src/base/inc/FBase_NativeError.h b/src/base/inc/FBase_NativeError.h new file mode 100644 index 0000000..877c124 --- /dev/null +++ b/src/base/inc/FBase_NativeError.h @@ -0,0 +1,125 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseNativeError.h + * @brief This is the header file for handling Native errors. + */ + +#ifndef _FBASE_NATIVE_ERROR_H_ +#define _FBASE_NATIVE_ERROR_H_ + +#include + + +#define __FUNCX__ __PRETTY_FUNCTION__ + +#ifdef _OSP_DEBUG_ +#define __ConvertNativeErrorToResult(errNo) _NativeError::ConvertNativeErrorToResult(errNo, __FILE__, __LINE__, __FUNCX__) +#define __ConvertNativeErrorToMessage(errNo) _NativeError::ConvertNativeErrorToMessage(errNo, __FILE__, __LINE__, __FUNCX__) +#else +#define __ConvertNativeErrorToResult(errNo) _NativeError::ConvertNativeErrorToResult(errNo) +#define __ConvertNativeErrorToMessage(errNo) _NativeError::ConvertNativeErrorToMessage(errNo) +#endif + +#define __ConvertNativeSystemErrorToResult(errNo) _NativeError::ConvertNativeSystemErrorToResult(errNo) +#define __ConvertNativeDeviceErrorToResult(errNo) _NativeError::ConvertNativeDeviceErrorToResult(errNo) +#define __ConvertNativePowerErrorToResult(errNo) _NativeError::ConvertNativePowerErrorToResult(errNo) +#define __ConvertNativeAlarmErrorToResult(errNo) _NativeError::ConvertNativeAlarmErrorToResult(errNo) +#define __ConvertNativeHapticErrorToResult(errNo) _NativeError::ConvertNativeHapticErrorToResult(errNo) +#define __ConvertNativeTelephonyErrorToResult(errNo) _NativeError::ConvertNativeTelephonyErrorToResult(errNo) +#define __ConvertNativeSoundManagerErrorToResult(errNo) _NativeError::ConvertNativeSoundManagerErrorToResult(errNo) +#define __ConvertNativeSqliteErrorToResult(errNo) _NativeError::ConvertNativeSqliteErrorToResult(errNo) +#define __ConvertNativeSqliteErrorToDetailResult(errNo) _NativeError::ConvertNativeSqliteErrorToDetailResult(errNo) + +/** + * @class _NativeError & FBaseNativeError.h + * @brief This is implemenatation of handling native errors. + * + */ +class _NativeError +{ +public: + // + // Convert Linux errno to Result type + // + static result ConvertNativeErrorToResult(int errNo, bool logNativeErr = false); + + // + // Convert Linux errno to Result type + // + static result ConvertNativeErrorToResult(int errNo, const char* pFile, int line, const char* pFunction, bool logNativeErr = false); + + // + // Convert Linux errno to Result type message + // + static const char* ConvertNativeErrorToMessage(int errNo); + + // + // Convert Linux errno to Result type message + // + static const char* ConvertNativeErrorToMessage(int errNo, const char* pFile, int line, const char* pFunction); + + // + // Convert SLP system_info error to Result type + // + static result ConvertNativeSystemErrorToResult(int err); + + // + // Convert SLP device error to Result type + // + static result ConvertNativeDeviceErrorToResult(int err); + + // + // Convert SLP power error to Result type + // + static result ConvertNativePowerErrorToResult(int err); + + // + // Convert SLP alarm error to Result type + // + static result ConvertNativeAlarmErrorToResult(int err); + + // + // Convert SLP haptic error to Result type + // + static result ConvertNativeHapticErrorToResult(int err); + + // + // Convert SLP Telephony error to Result type + // + static result ConvertNativeTelephonyErrorToResult(int err); + + // + // Convert SLP Telephony error to Result type + // + static result ConvertNativeSoundManagerErrorToResult(int err); + + // + // Converts SQLite error to Result type for OSP 2.0 + // + static result ConvertNativeSqliteErrorToResult(int err); + + // + // Converts SQLite error to Result type for OSP 3.0 + // + static result ConvertNativeSqliteErrorToDetailResult(int err); + +}; // _NativeError + +#endif //_FBASE_NATIVE_ERROR_H_ + diff --git a/src/base/inc/FBase_ObjectManagerImpl.h b/src/base/inc/FBase_ObjectManagerImpl.h new file mode 100644 index 0000000..439bf26 --- /dev/null +++ b/src/base/inc/FBase_ObjectManagerImpl.h @@ -0,0 +1,365 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBase_ObjectManagerImpl.h + * @brief This is the header file for the %_ObjectManagerImpl class. + * + * This file contains the declarations of the %_ObjectManagerImpl class. + */ + + +#ifndef _FBASE_INTERNAL_OBJECT_MANAGER_IMPL_H_ +#define _FBASE_INTERNAL_OBJECT_MANAGER_IMPL_H_ + +#include +#include + + +namespace Tizen { namespace Base +{ + +class _ObjectManagerImpl + : Tizen::Base::Object +{ + struct _HandleElement; + union _Handle; +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _ObjectManagerImpl(void) + : __slotCount(0) + { + __slotCapacity = DEFAULT_CAPACITY; + __pSlots = new _HandleElement[__slotCapacity]; + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_ObjectManagerImpl(void) + { + delete[] __pSlots; + } + + /** + * This is the copy constructor for this class. + * + * @since 2.0 + */ + _ObjectManagerImpl(_ObjectManagerImpl& pObjectManagerImpl) + { + __slotCount = pObjectManagerImpl.__slotCount; + __slotCapacity = pObjectManagerImpl.__slotCapacity; + __pSlots = new _HandleElement[pObjectManagerImpl.__slotCapacity]; + + for (unsigned int i = 0; i < pObjectManagerImpl.__slotCapacity; i++) + { + __pSlots[i] = pObjectManagerImpl.__pSlots[i]; + } + } + + /** + * This is the assignement operator for this class. + * + * @since 2.0 + */ + _ObjectManagerImpl& operator =(const _ObjectManagerImpl& pObjectManagerImpl) + { + //Check for self-assignment + if (this == &pObjectManagerImpl) + { + return *this; + } + + delete [] __pSlots; + __pSlots = null; + + __slotCount = pObjectManagerImpl.__slotCount; + __slotCapacity = pObjectManagerImpl.__slotCapacity; + __pSlots = new _HandleElement[pObjectManagerImpl.__slotCapacity]; + + for (unsigned int i = 0; i < pObjectManagerImpl.__slotCapacity; i++) + { + __pSlots[i] = pObjectManagerImpl.__pSlots[i]; + } + + return *this; + } + + /** + * Registers the specified object to the object manager. + * + * @since 2.0 + * @return The handle of the object + * @param[in] object An object to register + * @exception E_SUCCESS The method was successful. + * @see Unregister() + */ + int Register(void* pObject) + { + _Handle handle; + + if (__freeSlots.GetCount() == 0) + { + unsigned int index = __slotCount; + + __slotCount++; + if (__slotCount == __slotCapacity) + { + ExpandSlots(); + } + + InitializeHandle(index, handle); + + __pSlots[index].__id = handle.__id; + __pSlots[index].__pObject = pObject; + } + else + { + unsigned int index = 0; + + __freeSlots.GetAt(0, index); + __freeSlots.RemoveAt(0); + + InitializeHandle(index, handle); + + __pSlots[index].__id = handle.__id; + __pSlots[index].__pObject = pObject; + } + + return handle.__handle; + } + + /** + * Unregisters the specified handle from the object manager. + * + * @since 2.0 + * @return The object specified by the handle + * @param[in] handle A handle to release + * @exception E_SUCCESS The method was successful. + * @exception E_OBJ_NOT_FOUND The specified handle was not found. + * @see Register() + */ + void* Unregister(unsigned int handle) + { + void* pObject = null; + const unsigned int index = ((_Handle*)&handle)->__index; + + if (index >= __slotCount) + { + SetLastResult(E_OBJ_NOT_FOUND); + return null; + } + + _HandleElement& element = __pSlots[index]; + if (element.__id != ((_Handle*)&handle)->__id) + { + SetLastResult(E_OBJ_NOT_FOUND); + return null; + } + + pObject = element.__pObject; + + element.__id = 0; + element.__pObject = null; + + __freeSlots.Add(index); + + return pObject; + } + + + /** + * Gets an object specified by the handle. + * + * @since 2.0 + * @return The object specified by the handle + * @param[in] handle A handle to release + * @exception E_SUCCESS The method was successful. + * @exception E_OBJ_NOT_FOUND The specified handle was not found. + */ + const void* GetObject(unsigned int handle) const + { + const unsigned int index = ((_Handle*)&handle)->__index; + + if (index >= __slotCount) + { + SetLastResult(E_OBJ_NOT_FOUND); + return null; + } + + const _HandleElement& element = __pSlots[index]; + if (element.__id != ((_Handle*)&handle)->__id) + { + SetLastResult(E_OBJ_NOT_FOUND); + return null; + } + + return element.__pObject; + } + + /** + * Gets an object specified by the handle. + * + * @since 2.0 + * @return The object specified by the handle + * @param[in] handle A handle to release + * @exception E_SUCCESS The method was successful. + * @exception E_OBJ_NOT_FOUND The specified handle was not found. + */ + void* GetObject(unsigned int handle) + { + const void* pObj = (static_cast(this))->GetObject(handle); + return const_cast(pObj); + } + + + /** + * Gets the number of objects in the object manager. + * + * @since 2.0 + * @return The number of object + */ + int GetObjectCount(void) const + { + return static_cast (__slotCount - __freeSlots.GetCount()); + } + + bool IsValidHandle(unsigned int handle) const + { + const void* pObject = GetObject(handle); + + if (pObject != null) + { + return true; + } + else + { + return false; + } + } + +private: + void InitializeHandle(unsigned int index, _Handle& handle) + { + static unsigned int autoId = 0; + if (++autoId > MAX_ID) + { + autoId = 1; + } + + handle.__index = index; + handle.__id = autoId; + } + + void ExpandSlots(void) + { + unsigned int newCapacity = __slotCapacity*2; + _HandleElement* pNewArray = new _HandleElement[newCapacity]; + + for (unsigned int i = 0; i < __slotCapacity; i++) + { + pNewArray[i] = __pSlots[i]; + } + + delete[] __pSlots; + + __pSlots = pNewArray; + __slotCapacity = newCapacity; + } + + void SetElementAt(int index) + { + + } + + _HandleElement GetElementAt(int index) + { + _HandleElement element; + + return element; + } + +private: + enum + { + MAX_BITS_INDEX = 16, + MAX_BITS_ID = 16, + MAX_INDEX = (1 << MAX_BITS_INDEX) - 1, + MAX_ID = (1 << MAX_BITS_ID) - 1, + }; + + union _Handle + { + unsigned int __handle; + struct + { + unsigned __index : MAX_BITS_INDEX; + unsigned __id : MAX_BITS_ID; + }; + }; + + struct _HandleElement + { + _HandleElement(unsigned int id = 0, void* pObject = null) + : __id(id) + , __pObject(pObject) + { + } + + _HandleElement(const _HandleElement& element) + { + __id = element.__id; + __pObject = element.__pObject; + } + + _HandleElement& operator = (const _HandleElement& element) + { + if (this == &element) + { + return *this; + } + + __id = element.__id; + __pObject = element.__pObject; + + return *this; + } + + unsigned int __id; + void* __pObject; + }; + + static const int DEFAULT_CAPACITY = 64; + +private: + _HandleElement* __pSlots; + unsigned int __slotCount; + unsigned int __slotCapacity; + Tizen::Base::Collection::LinkedListT __freeSlots; + +}; + +}} // Tizen::Base + +#endif // _FBASE_INTERNAL_OBJECT_MANAGER_IMPL_H_ diff --git a/src/base/inc/FBase_ObjectManagerT.h b/src/base/inc/FBase_ObjectManagerT.h new file mode 100644 index 0000000..1a23b6d --- /dev/null +++ b/src/base/inc/FBase_ObjectManagerT.h @@ -0,0 +1,216 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBase_ObjectManagerT.h + * @brief This is the header file for the %_ObjectManagerT class. + * + * This file contains the declarations of the %_ObjectManagerT class. + */ + + +#ifndef _FBASE_INTERNAL_OBJECT_MANAGER_TEMPLATE_H_ +#define _FBASE_INTERNAL_OBJECT_MANAGER_TEMPLATE_H_ + +#include +#include +#include "FBase_HandleT.h" +#include "FBase_ObjectManagerImpl.h" + + + +namespace Tizen { namespace Base +{ + +/** + * @class _ObjectManagerT + * @brief This class represents a template-based object manager. + * @since 2.0 + * + * @code + * @include + * + * using namespace Tizen::Base; + * + * void + * MyClass::ObjectManagerTSample(void) + * { + * //Creates an object manager for specified data type + * _ObjectManagerT objectManager; + * + * int int1 = 1; + * int int2 = 2; + * int int3 = 3; + * + * // Registers objects to an object manager + * _HandleT handle1 = objectManager.Register(int1); + * _HandleT handle2 = objectManager.Register(int2); + * _HandleT handle3 = objectManager.Register(int3); + * + * // Gets objects from an object manager with handles + * int* pInt1 = objectManager.GetObject(handle1); // *pInt1 == 1 + * int* pInt2 = objectManager.GetObject(handle2); // *pInt2 == 2 + * int* pInt3 = objectManager.GetObject(handle3); // *pInt3 == 3 + * + * _HandleT handle4 = handle1; + * _HandleT handle5 = handle2; + * _HandleT handle6 = handle3; + * + * // Gets objects from an object manager with handles + * int* pInt4 = objectManager.GetObject(handle4); // *pInt4 == 1 + * int* pInt5 = objectManager.GetObject(handle5); // *pInt5 == 2 + * int* pInt6 = objectManager.GetObject(handle6); // *pInt6 == 3 + * } + * @endcode + */ +template +class _ObjectManagerT + : Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _ObjectManagerT(void) + { + __pImpl = new _ObjectManagerImpl; + } + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_ObjectManagerT(void) + { + delete __pImpl; + } + + /** + * Registers the specified object to the object manager. + * + * @since 2.0 + * @return The handle of the object + * @param[in] object An object to register + * @exception E_SUCCESS The method was successful. + * @see Unregister() + */ + _HandleT Register(const T& object) + { + _HandleT handle; + unsigned int rawHandle = 0; + + rawHandle = __pImpl->Register((void*)&object); + handle.Initialize(rawHandle, __pImpl); + + return handle; + } + + /** + * Unregisters the specified handle from the object manager. + * + * @since 2.0 + * @return The object specified by the handle + * @param[in] handle A handle to release + * @exception E_SUCCESS The method was successful. + * @exception E_OBJ_NOT_FOUND The specified handle was not found. + * @see Register() + */ + T* Unregister(const _HandleT & handle) + { + void* pObject = __pImpl->Unregister(handle.__handle); + + return (T*)pObject; + } + + /** + * Get a handle specified by a signed @c integer value. + * + * @since 2.0 + * @return Handle specifed by a signed @c integer + * @param[in] value A signed @c integer value; + */ + _HandleT GetHandle(int value) + { + _HandleT handle; + handle.Initialize((unsigned int)value, __pImpl); + + return handle; + } + + /** + * Gets an object specified by the handle. + * + * @since 2.0 + * @return The object specified by the handle + * @param[in] handle A handle to release + * @exception E_SUCCESS The method was successful. + * @exception E_OBJ_NOT_FOUND The specified handle was not found. + */ + T* GetObject(const _HandleT & handle) + { + void* pObject = null; + + if (handle.IsNull()) + return null; + + pObject = __pImpl->GetObject(handle.__handle); + + return (T*)pObject; + } + + + /** + * Gets an object specified by the handle. + * + * @since 2.0 + * @return The object specified by the handle + * @param[in] handle A handle to release + * @exception E_SUCCESS The method was successful. + * @exception E_OBJ_NOT_FOUND The specified handle was not found. + */ + const T* GetObject(const _HandleT & handle) const + { + if (handle.IsNull()) + return null; + + const void* pObject = __pImpl->GetObject(handle.__handle); + + return (const T*)pObject; + } + + + /** + * Gets the number of objects in the object manager. + * + * @since 2.0 + * @return The number of object + */ + int GetObjectCount(void) const + { + return __pImpl->GetObjectCount(); + } + +private: + _ObjectManagerImpl* __pImpl; +}; // _ObjectManagerT + +}} // Tizen::Base + +#endif // _FBASE_INTERNAL_OBJECT_MANAGER_TEMPLATE_H_ diff --git a/src/base/inc/FBase_StringConverter.h b/src/base/inc/FBase_StringConverter.h new file mode 100644 index 0000000..fd2c866 --- /dev/null +++ b/src/base/inc/FBase_StringConverter.h @@ -0,0 +1,56 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBase_StringConverter.h + * @brief This is the header file for the _StringConverter class. + */ + +#ifndef _FBASE_STRING_CONVERTER_H_ +#define _FBASE_STRING_CONVERTER_H_ + +#include + + +namespace Tizen { namespace Base +{ + + +class _OSP_EXPORT_ _StringConverter +{ +public: + /** + * Convert String instance to Char array type + * + * @return A Char array + * @param[in] str A String instance + */ + static char* CopyToCharArrayN(const String& str); + + /** + * Convert String instance to Char array type + * + * @return A Char array + * @param[in] pValue A wchar_t pointer + */ + static char* CopyToCharArrayN(const wchar_t* pValue); + +}; // _StringConverter + +}} // Tizen::Base + +#endif // _FBASE_STRING_CONVERTER_H_ diff --git a/src/base/runtime/FBaseRtEvent.cpp b/src/base/runtime/FBaseRtEvent.cpp new file mode 100644 index 0000000..29abdfd --- /dev/null +++ b/src/base/runtime/FBaseRtEvent.cpp @@ -0,0 +1,65 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtEvent.cpp + * @brief This is the implementation file for the Event class. + * + */ + +#include +#include +#include +#include "FBaseRt_EventImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime +{ + +Event::Event(void) + :__pEventImpl(null) +{ + __pEventImpl = new _EventImpl(*this); + //__pEventImpl->Initialize(); +} + +Event::~Event(void) +{ + delete __pEventImpl; +} + +result +Event::AddListener(IEventListener& listener, bool calledByCallerThread) +{ + return __pEventImpl->AddListener(listener, calledByCallerThread); +} + +result +Event::RemoveListener(IEventListener& listener) +{ + return __pEventImpl->RemoveListener(listener); +} + +result +Event::Fire(IEventArg& arg) +{ + return __pEventImpl->Fire(arg); +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRtEventDrivenThread.cpp b/src/base/runtime/FBaseRtEventDrivenThread.cpp new file mode 100644 index 0000000..7e6f363 --- /dev/null +++ b/src/base/runtime/FBaseRtEventDrivenThread.cpp @@ -0,0 +1,100 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtEventDrivenThread.cpp + * @brief This is the implementation file for the EventDrivenThread class. + * + */ + +#include +#include +#include + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Base { namespace Runtime +{ + +EventDrivenThread::EventDrivenThread(void) + : __pEventDrivenThreadImpl(null) +{ + +} + +EventDrivenThread::~EventDrivenThread(void) +{ + +} + +result +EventDrivenThread::Construct(long stackSize, ThreadPriority priority) +{ + SysTryReturnResult(NID_BASE_RT, stackSize > 0, E_INVALID_ARG, "Stack size must be greater than zero."); + + return EventDrivenThread::Construct(L"thread", stackSize, priority); +} + +result +EventDrivenThread::Construct(const String& name, long stackSize, ThreadPriority priority) +{ + SysTryReturnResult(NID_BASE_RT, !name.IsEmpty(), E_INVALID_ARG, "Thread name is empty string."); + SysTryReturnResult(NID_BASE_RT, stackSize > 0, E_INVALID_ARG, "Stack size must be greater than zero."); + + return Thread::Construct(name, THREAD_TYPE_EVENT_DRIVEN, stackSize, priority); +} + +result +EventDrivenThread::Quit(void) +{ + return Thread::Stop(); +} + +result +EventDrivenThread::SendUserEvent(RequestId requestId, const IList* pArgs) +{ + return Thread::SendUserEvent(requestId, pArgs); +} + +Object* +EventDrivenThread::Run(void) +{ + return null; +} + +bool +EventDrivenThread::OnStart(void) +{ + + return true; +} + +void +EventDrivenThread::OnStop(void) +{ + +} + +void +EventDrivenThread::OnUserEventReceivedN(RequestId requestId, IList* pArgs) +{ + +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRtIEventListener.cpp b/src/base/runtime/FBaseRtIEventListener.cpp new file mode 100644 index 0000000..cfbc2a6 --- /dev/null +++ b/src/base/runtime/FBaseRtIEventListener.cpp @@ -0,0 +1,51 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtIEventListener.cpp + * @brief This is the implementation file for the IEventListener class. + * + */ + + +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ + + +/** + * @interface IEventListener + * @brief This is a tagging interface that all event listeners must implement. + * + * The event listener can listen that the specific event is fired. In general, the event listener + * has several methods, and each method will be called when specific event is fired. + * + * @see IEvent, Event + */ + +// +// This is a virtual destructor. +// +IEventListener::~IEventListener(void) +{ + +} + + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRtIRunnable.cpp b/src/base/runtime/FBaseRtIRunnable.cpp new file mode 100644 index 0000000..6220343 --- /dev/null +++ b/src/base/runtime/FBaseRtIRunnable.cpp @@ -0,0 +1,35 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtThreadIRunnable.cpp + * @brief This is the implementation file for the IRunnable class. + * + */ + +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ + +IRunnable::~IRunnable(void) +{ + +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRtLibrary.cpp b/src/base/runtime/FBaseRtLibrary.cpp new file mode 100644 index 0000000..f9aa65f --- /dev/null +++ b/src/base/runtime/FBaseRtLibrary.cpp @@ -0,0 +1,79 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtLibrary.cpp + * @brief This is the implementation file for the License class. + * + */ + +#include +#include +#include +#include "FBaseRt_LibraryImpl.h" + +namespace Tizen { namespace Base { namespace Runtime +{ +Library::Library(void) + : __pLibraryImpl(null) +{ + +} + +Library::~Library(void) +{ + delete __pLibraryImpl; + __pLibraryImpl = null; +} + +result +Library::Construct(const Tizen::Base::String& libraryPath) +{ + // Object is not allowed to construct twice + SysAssertf(__pLibraryImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + SysTryReturnResult(NID_BASE_RT, !libraryPath.IsEmpty(), E_INVALID_ARG, "Library path is null string."); + + __pLibraryImpl = new (std::nothrow) _LibraryImpl; + SysTryReturnResult(NID_BASE_RT, __pLibraryImpl != null, E_OUT_OF_MEMORY, "Not enough memory."); + + result r = __pLibraryImpl->Construct(libraryPath, _LIBRARY_LOAD_OPTION_LAZY); + if (IsFailed(r)) + { + delete __pLibraryImpl; + __pLibraryImpl = null; + } + + return r; +} + +void* +Library::GetProcAddress(const Tizen::Base::String& symbol) const +{ + SysAssertf(__pLibraryImpl != null, "Not yet constructed! Construct() should be called before use."); + + SysTryReturn(NID_BASE_RT, !symbol.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] Symbol name is null."); + + void* pSymAddr = __pLibraryImpl->GetProcAddress(symbol); + result r = GetLastResult(); + SysTryReturn(NID_BASE_RT, pSymAddr != null, null, r, "[%s] Failed to get symbol address.", GetErrorMessage(r)); + + return pSymAddr; +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRtMemoryManager.cpp b/src/base/runtime/FBaseRtMemoryManager.cpp new file mode 100644 index 0000000..1b0127e --- /dev/null +++ b/src/base/runtime/FBaseRtMemoryManager.cpp @@ -0,0 +1,86 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtMemoryManager.cpp + * @brief This is the implementation file for the MemoryManager class. + * + */ + +#include +#include + +#include + +#include + + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime { + +MemoryManager::MemoryManager() +{ + +} +MemoryManager::~MemoryManager() +{ + +} + +result +MemoryManager::ProtectMemory(const void* pAddress, long long length, unsigned long protection) +{ + result r = E_SUCCESS; + int prot = PROT_NONE; + int ret = -1; + + if (protection & MEMORY_PROTECTION_MODE_READ) + { + prot |= PROT_READ; + } + + if (protection & MEMORY_PROTECTION_MODE_WRITE) + { + prot |= PROT_WRITE; + } + + if (protection & MEMORY_PROTECTION_MODE_EXEC) + { + prot |= PROT_EXEC; + } + + ret = mprotect((void*)pAddress, length, prot); + if (ret == -1) + { + if (errno == EINVAL) + { + r = E_INVALID_ARG; + SysLogException(NID_BASE_RT, r, "[E_INVALID_ARG] pAddress(0x%x) is not a valid address or length is not a multiple of the system page size."); + } + else + { + r = E_SYSTEM; + SysLogException(NID_BASE_RT, r, "[E_SYSTEM] pAddress(0x%x) is not a valid address or length is not a multiple of the system page size."); + } + } + + return r; +} + +} } } diff --git a/src/base/runtime/FBaseRtMonitor.cpp b/src/base/runtime/FBaseRtMonitor.cpp new file mode 100644 index 0000000..385726a --- /dev/null +++ b/src/base/runtime/FBaseRtMonitor.cpp @@ -0,0 +1,123 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtThreadMonitor.cpp + * @brief This is the implementation file for the Monitor class. + * + */ + +#include + +#include + +#include +#include "FBaseRt_MonitorImpl.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +Monitor::Monitor(void) + : __pMonitorImpl(null) +{ + +} + +Monitor::~Monitor(void) +{ + delete __pMonitorImpl; + __pMonitorImpl = null; +} + +result +Monitor::Construct(void) +{ + // Object is not allowed to construct twice + SysAssertf(__pMonitorImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + result r = E_SUCCESS; + __pMonitorImpl = new (std::nothrow) _MonitorImpl; + SysTryReturnResult(NID_BASE_RT, __pMonitorImpl != null, E_OUT_OF_MEMORY, "Not enough memory."); + + r = __pMonitorImpl->Construct(); + if (IsFailed(r)) + { + delete __pMonitorImpl; + __pMonitorImpl = null; + } + + return r; +} + +result +Monitor::Enter(void) +{ + SysAssertf(__pMonitorImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pMonitorImpl->Enter(); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r, "[%s] System error has occurred", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +Monitor::Exit(void) +{ + SysAssertf(__pMonitorImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pMonitorImpl->Exit(); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r, "[%s] System error has occurred", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +Monitor::Wait(void) +{ + SysAssertf(__pMonitorImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pMonitorImpl->Wait(); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r, "[%s] System error has occurred", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +Monitor::Notify(void) +{ + SysAssertf(__pMonitorImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pMonitorImpl->Notify(); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r, "[%s] System error has occurred", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +Monitor::NotifyAll(void) +{ + SysAssertf(__pMonitorImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pMonitorImpl->NotifyAll(); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r, "[%s] System error has occurred", GetErrorMessage(r)); + + return E_SUCCESS; +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRtMutex.cpp b/src/base/runtime/FBaseRtMutex.cpp new file mode 100644 index 0000000..409a157 --- /dev/null +++ b/src/base/runtime/FBaseRtMutex.cpp @@ -0,0 +1,99 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtThreadMutex.cpp + * @brief This is the implementation file for the Mutex class. + * + */ + +#include + +#include + +#include "FBase_NativeError.h" +#include +#include "FBaseRt_MutexImpl.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +Mutex::Mutex(void) + : __pMutexImpl(null) +{ + +} + +Mutex::~Mutex(void) +{ + delete __pMutexImpl; + __pMutexImpl = null; +} + +result +Mutex::Create(void) +{ + return Create(L""); +} + +result +Mutex::Create(const String& name) +{ + // Object is not allowed to construct twice + SysAssertf(__pMutexImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + result r = E_SUCCESS; + + __pMutexImpl = new (std::nothrow) _MutexImpl; + SysTryReturnResult(NID_BASE_RT, __pMutexImpl != null, E_OUT_OF_MEMORY, "Not enough memory."); + + r = __pMutexImpl->Create(name); + SysTryCatch(NID_BASE_RT, !IsFailed(r), , r, "[%s] Mutex initialization failed.", GetErrorMessage(r)); + + return E_SUCCESS; + +CATCH: + delete __pMutexImpl; + __pMutexImpl = null; + + return r; +} + +result +Mutex::Acquire(void) +{ + SysAssertf(__pMutexImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pMutexImpl->Acquire(); +} + +result +Mutex::TryToAcquire(void) +{ + SysAssertf(__pMutexImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pMutexImpl->TryToAcquire(); +} + +result +Mutex::Release(void) +{ + SysAssertf(__pMutexImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pMutexImpl->Release(); +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRtSemaphore.cpp b/src/base/runtime/FBaseRtSemaphore.cpp new file mode 100644 index 0000000..0753e38 --- /dev/null +++ b/src/base/runtime/FBaseRtSemaphore.cpp @@ -0,0 +1,97 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtThreadSemaphore.cpp + * @brief This is the implementation file for the Semaphore class. + * + */ + +#include + +#include + +#include "FBase_NativeError.h" +#include +#include "FBaseRt_SemaphoreImpl.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +Semaphore::Semaphore(void) + : __pSemaphoreImpl(null) +{ + +} + +Semaphore::~Semaphore(void) +{ + delete __pSemaphoreImpl; + __pSemaphoreImpl = null; +} + +result +Semaphore::Create(int count) +{ + return Create(L"", count); +} + +result +Semaphore::Create(const String& name, int count) +{ + // Object is not allowed to construct twice + SysAssertf(__pSemaphoreImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + SysTryReturnResult(NID_BASE_RT, count >= 0, E_INVALID_ARG, "The count(%d) MUST be greater than or equal to 0.", count); + + __pSemaphoreImpl = new (std::nothrow) _SemaphoreImpl; + SysTryReturnResult(NID_BASE_RT, __pSemaphoreImpl != null, E_OUT_OF_MEMORY, "Not enough memory."); + + result r = __pSemaphoreImpl->Create(name, count); + if (IsFailed(r)) + { + delete __pSemaphoreImpl; + __pSemaphoreImpl = null; + } + + return r; +} + +result +Semaphore::Acquire(long timeout) +{ + SysAssertf(__pSemaphoreImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pSemaphoreImpl->Acquire(timeout); +} + +result +Semaphore::TryToAcquire(void) +{ + SysAssertf(__pSemaphoreImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pSemaphoreImpl->TryToAcquire(); +} + +result +Semaphore::Release(void) +{ + SysAssertf(__pSemaphoreImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pSemaphoreImpl->Release(); +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRtThread.cpp b/src/base/runtime/FBaseRtThread.cpp new file mode 100644 index 0000000..74ccce9 --- /dev/null +++ b/src/base/runtime/FBaseRtThread.cpp @@ -0,0 +1,238 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtThreadThread.cpp + * @brief This is the implementation file for the Thread class. + * + */ + +#include +#include +#include +#include "FBaseRt_ThreadImpl.h" +#include "FBaseRt_WorkerThreadImpl.h" +#include "FBaseRt_EventDrivenThreadImpl.h" +#include "FBaseRt_MainThreadImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Base { namespace Runtime +{ + +result +Thread::Sleep(long milliSeconds) +{ + SysTryReturnResult(NID_BASE_RT, milliSeconds >= 0, E_INVALID_ARG, "milliSeconds is less than zero."); + + result r = _ThreadImpl::Sleep(milliSeconds); + SysTryReturnResult(NID_BASE_RT, !IsFailed(r), E_INVALID_ARG, "milliSeconds is less than zero."); + + return E_SUCCESS; +} + +result +Thread::Yield(void) +{ + result r = _ThreadImpl::Yield(); + SysTryReturnResult(NID_BASE_RT, !IsFailed(r), E_SYSTEM, "Yield failed due to a system error."); + + return E_SUCCESS; +} + +result +Thread::Exit(int exitCode) +{ + _ThreadImpl::Exit(exitCode); + + return E_SUCCESS; +} + +Thread* +Thread::GetCurrentThread(void) +{ + Thread* pThread = _ThreadImpl::GetCurrentThread(); + SysTryReturn(NID_BASE_RT, pThread != null, null, E_SYSTEM, "Getting current thread failed due to a system error."); + + return pThread; +} + +Thread::Thread(void) + : __pThreadImpl(null) +{ + +} + +Thread::~Thread(void) +{ + delete __pThreadImpl; +} + +result +Thread::Construct(ThreadType threadType, long stackSize, ThreadPriority priority) +{ + return Construct(L"thread", threadType, stackSize, priority); +} + +result +Thread::Construct(long stackSize, ThreadPriority priority) +{ + return Construct(L"thread", THREAD_TYPE_WORKER, stackSize, priority); +} + + +result +Thread::Construct(const String& name, ThreadType threadType, long stackSize, ThreadPriority priority) +{ + // Object is not allowed to construct twice + SysAssertf(__pThreadImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + SysTryReturnResult(NID_BASE_RT, !name.IsEmpty(), E_INVALID_ARG, "Thread name is empty string."); + SysTryReturnResult(NID_BASE_RT, stackSize > 0, E_INVALID_ARG, "Stack size must be greater than zero."); + + if (threadType == THREAD_TYPE_EVENT_DRIVEN) + { + __pThreadImpl = new (std::nothrow) _EventDrivenThreadImpl(*this, name, stackSize, priority); + } + else if (threadType == THREAD_TYPE_WORKER) + { + __pThreadImpl = new (std::nothrow) _WorkerThreadImpl(*this, null, name, stackSize, priority); + } + else + { + __pThreadImpl = new (std::nothrow) _MainThreadImpl(*this, name); + } + + SysTryReturnResult(NID_BASE_RT, __pThreadImpl != null, E_OUT_OF_MEMORY, "Not enough memory."); + + return E_SUCCESS; +} + +result +Thread::Construct(const String& name, long stackSize, ThreadPriority priority) +{ + return Construct(name, THREAD_TYPE_WORKER, stackSize, priority); +} + +result +Thread::Construct(IRunnable& target, long stackSize, ThreadPriority priority) +{ + return Construct(L"thread", target, stackSize, priority); +} + +result +Thread::Construct(const String& name, IRunnable& target, long stackSize, ThreadPriority priority) +{ + // Object is not allowed to construct twice + SysAssertf(__pThreadImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + SysTryReturnResult(NID_BASE_RT, !name.IsEmpty(), E_INVALID_ARG, "Thread name is empty string."); + SysTryReturnResult(NID_BASE_RT, stackSize > 0, E_INVALID_ARG, "Stack size must be greater than zero."); + + __pThreadImpl = new (std::nothrow) _WorkerThreadImpl(*this, &target, name, stackSize, priority); + SysTryReturnResult(NID_BASE_RT, __pThreadImpl != null, E_OUT_OF_MEMORY, "Not enough memory."); + + return E_SUCCESS; +} + +result +Thread::Join(void) +{ + SysAssertf(__pThreadImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pThreadImpl->Join(); + SysTryReturnResult(NID_BASE_RT, !IsFailed(r), E_SYSTEM, "Join failed due to a system error."); + + return E_SUCCESS; +} + +result +Thread::Start(void) +{ + SysAssertf(__pThreadImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pThreadImpl->Start(); + SysTryReturnResult(NID_BASE_RT, !IsFailed(r), E_SYSTEM, "Start a thread has failed due to a system error."); + + return E_SUCCESS; +} + +result +Thread::Stop(void) +{ + SysAssertf(__pThreadImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pThreadImpl->Stop(); + SysTryReturnResult(NID_BASE_RT, !IsFailed(r), E_SYSTEM, "Stop a thread has failed due to a system error."); + + return E_SUCCESS; +} + +result +Thread::GetExitCode(int& exitCode) const +{ + SysAssertf(__pThreadImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pThreadImpl->GetExitCode(exitCode); + SysTryReturnResult(NID_BASE_RT, !IsFailed(r), E_INVALID_STATE, "Thread is not terminated."); + + return E_SUCCESS; +} + +const String& +Thread::GetName(void) const +{ + SysAssertf(__pThreadImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pThreadImpl->GetName(); +} + +result +Thread::SendUserEvent(RequestId requestId, const IList* pArgs) +{ + SysAssertf(__pThreadImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pThreadImpl->SendUserEvent(requestId, pArgs); +} + +Object* +Thread::Run(void) +{ + return null; +} + +bool +Thread::OnStart(void) +{ + + return true; +} + +void +Thread::OnStop(void) +{ + +} + +void +Thread::OnUserEventReceivedN(RequestId requestId, IList* pArgs) +{ + +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRtTimer.cpp b/src/base/runtime/FBaseRtTimer.cpp new file mode 100644 index 0000000..e52fb82 --- /dev/null +++ b/src/base/runtime/FBaseRtTimer.cpp @@ -0,0 +1,98 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtTimer.cpp + * @brief This is the implementation file for the Timer class. + * + */ + +#include +#include +#include +#include "FBaseRt_TimerImpl.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +Timer::Timer(void) + : __pTimerImpl(null) +{ + +} + +Timer::~Timer(void) +{ + delete __pTimerImpl; + __pTimerImpl = null; +} + +result +Timer::Construct(ITimerEventListener& listener) +{ + // Object is not allowed to construct twice + SysAssertf(__pTimerImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pTimerImpl = new (std::nothrow) _TimerImpl; + SysTryReturnResult(NID_BASE_RT, __pTimerImpl != null, E_OUT_OF_MEMORY, "Not enough memory."); + + result r = __pTimerImpl->Construct(*this, listener); + if (IsFailed(r)) + { + delete __pTimerImpl; + __pTimerImpl = null; + } + + return r; +} + +result +Timer::Start(int timeout) +{ + SysAssertf(__pTimerImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pTimerImpl->Start(timeout); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Failed to start a timer.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +Timer::StartAsRepeatable(int interval) +{ + SysAssertf(__pTimerImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pTimerImpl->StartAsRepeatable(interval); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Failed to start a timer.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +Timer::Cancel(void) +{ + SysAssertf(__pTimerImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pTimerImpl->Cancel(); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Failed to cancel a timer.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRtWaitingLoop.cpp b/src/base/runtime/FBaseRtWaitingLoop.cpp new file mode 100755 index 0000000..fb396fa --- /dev/null +++ b/src/base/runtime/FBaseRtWaitingLoop.cpp @@ -0,0 +1,98 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRtWaitingLoop.cpp + * @brief This is the implementation for the %WaitingLoop class. + * + */ + +#include +#include "FBaseRt_WaitingLoopImpl.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +WaitingLoop::WaitingLoop(void) + : __pWaitingLoopImpl(null) +{ +} + + +WaitingLoop::~WaitingLoop(void) +{ + delete __pWaitingLoopImpl; +} + +WaitingLoop* +WaitingLoop::GetInstance(void) +{ + static WaitingLoop* pWaitingLoop = null; + if (pWaitingLoop == null) + { + pWaitingLoop = _WaitingLoopImpl::GetInstanceN(); + } + else + { + if (pWaitingLoop->__pWaitingLoopImpl->IsSameThread() == false) + { + pWaitingLoop->__pWaitingLoopImpl->Notify(); + delete pWaitingLoop; + + pWaitingLoop = _WaitingLoopImpl::GetInstanceN(); + } + } + + return pWaitingLoop; +} + +result +WaitingLoop::Wait(int timeout) +{ + return __pWaitingLoopImpl->Wait(timeout); +} + +result +WaitingLoop::Wait(IWaitingLoopCondition& condition) +{ + return __pWaitingLoopImpl->Wait(condition); +} + +result +WaitingLoop::Wait(int timeout, IWaitingLoopCondition& condition) +{ + return __pWaitingLoopImpl->Wait(timeout, condition); +} + +void +WaitingLoop::Notify(void) +{ + __pWaitingLoopImpl->Notify(); +} + +void +WaitingLoop::SetMaxTimeoutForWaiting(int timeout) +{ + WaitingLoop* pWaitingLoop = WaitingLoop::GetInstance(); + + if (pWaitingLoop != null) + { + pWaitingLoop->__pWaitingLoopImpl->SetMaxTimeoutForWaiting(timeout); + } +} + +}}} // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_Event.cpp b/src/base/runtime/FBaseRt_Event.cpp new file mode 100644 index 0000000..92c7923 --- /dev/null +++ b/src/base/runtime/FBaseRt_Event.cpp @@ -0,0 +1,332 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_Event.cpp + * @brief This is the implementation file for the _Event class. + * + */ + +#include + +#include + +#include +#include "FBaseRt_Event.h" +#include "FBaseRt_EventManager.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime +{ + +_Event::_ListenerInfo& +_Event::_ListenerInfo::operator =(const _ListenerInfo& rhs) +{ + if (this != &rhs) + { + pListener = rhs.pListener; + listener = rhs.listener; + eventManager = rhs.eventManager; + } + + return *this; +} + +bool +_Event::_ListenerInfo::operator ==(const _ListenerInfo& rhs) const +{ + if (listener == rhs.listener && eventManager == rhs.eventManager) + { + return true; + } + + return false; +} + +bool +_Event::_ListenerInfo::operator !=(const _ListenerInfo& rhs) const +{ + if (listener != rhs.listener || eventManager != rhs.eventManager) + { + return true; + } + + return false; +} + +_Event::_RefCount::_RefCount(void) + : __count(1) + , __destroyed(false) +{ + +} + +_Event::_RefCount::~_RefCount(void) +{ + +} + +int +_Event::_RefCount::AddRef(void) +{ + __count++; + return __count; +} + +int +_Event::_RefCount::Release(void) +{ + __count--; + if (__count == 0) + { + delete this; + return 0; + } + + return __count; +} + +_Event::_Event(void) +{ + __pRefCount = new (std::nothrow) _RefCount(); + + __handle = _EventManager::GetEventObjectManager().Register(*this); +} + +_Event::~_Event(void) +{ + __pRefCount->__destroyed = true; + __pRefCount->Release(); + + if (__handle.IsValid()) + { + _EventManager::GetEventObjectManager().Unregister(__handle); + } +} + +result +_Event::AddListener(const IEventListener& listener, bool calledByCallerThread) +{ + result r = E_SUCCESS; + bool exist = false; + _ListenerInfo listenerInfo; + _HandleT< _EventManager > eventManager; + + if (calledByCallerThread) + { + _EventManager* pEventManager = _EventManager::GetCurrentEventManager(); + SysTryReturnResult(NID_BASE_RT, pEventManager != null, E_INVALID_OPERATION + , "The caller thread is not an event driven thread."); + + eventManager = pEventManager->GetHandle(); + } + + IEnumeratorT< _ListenerInfo >* pEnum = __listeners.GetEnumeratorN(); + SysTryReturnResult(NID_BASE_RT, pEnum != null, E_OUT_OF_MEMORY, "Not enough memory."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetCurrent(listenerInfo); + + if (&listener == listenerInfo.pListener) + { + exist = true; + break; + } + } + + delete pEnum; + + SysTryReturnResult(NID_BASE_RT, !exist, E_OBJ_ALREADY_EXIST, "[E_OBJ_ALREADY_EXIST] Listener already exist."); + + listenerInfo.pListener = &listener; + listenerInfo.listener = _EventManager::GetEventListenerObjectManager().Register(listener); + listenerInfo.eventManager = eventManager; + + r = __listeners.Add(listenerInfo); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_Event::RemoveListener(const IEventListener& listener) +{ + result r = E_SUCCESS; + bool exist = false; + _ListenerInfo listenerInfo; + + IEnumeratorT< _ListenerInfo >* pEnum = __listeners.GetEnumeratorN(); + SysTryReturnResult(NID_BASE_RT, pEnum != null, E_OUT_OF_MEMORY, "Not enough memory."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetCurrent(listenerInfo); + + if (listenerInfo.pListener == &listener) + { + r = __listeners.Remove(listenerInfo); + SysTryLog(NID_BASE_RT, !IsFailed(r), "[%s] Propagating.", GetErrorMessage(r)); + + _EventManager::GetEventListenerObjectManager().Unregister(listenerInfo.listener); + + exist = true; + break; + } + } + + delete pEnum; + + SysTryReturnResult(NID_BASE_RT, exist, E_OBJ_NOT_FOUND, "Listener not found."); + + return E_SUCCESS; +} + +result +_Event::Initialize(void) +{ + result r = E_SUCCESS; + + _EventManager* pEventManager = _EventManager::GetCurrentEventManager(); + SysTryReturnResult(NID_BASE_RT, pEventManager != null, E_INVALID_OPERATION, "Event manager does not exist."); + + r = pEventManager->RegisterEvent(this->GetHandle()); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Failed to register an event.", GetErrorMessage(r)); + + __eventManager = pEventManager->GetHandle(); + + return E_SUCCESS; +} + +result +_Event::FireAsync(IEventArg& arg) +{ + SysTryReturnResult(NID_BASE_RT, __eventManager.IsValid(), E_INVALID_STATE, "Event manager is invalid state."); + + _EventManager* pEventManager = _EventManager::GetEventManagerByHandle(__eventManager); + SysTryReturnResult(NID_BASE_RT, pEventManager != null, E_INVALID_STATE, "Event manager is invalid state."); + + pEventManager->FireEventAsync(__handle, std::tr1::shared_ptr< IEventArg >(&arg)); + + return E_SUCCESS; +} + +result +_Event::Fire(IEventArg& arg) +{ + std::tr1::shared_ptr< IEventArg > sharedArg(&arg); + + return Fire(sharedArg); +} + +result +_Event::Fire(std::tr1::shared_ptr< IEventArg > arg) +{ + _RefCount* pRefCount = __pRefCount; + + pRefCount->AddRef(); + + ProcessListeners(arg); + + pRefCount->Release(); + + return E_SUCCESS; +} + +result +_Event::ProcessListeners(std::tr1::shared_ptr< IEventArg > arg) +{ + _RefCount* pRefCount = __pRefCount; + + _ListenerInfo listenerInfo; + _EventManager* pEventManager = null; + IEventListener* pEventListener = null; + + IEnumeratorT< _ListenerInfo >* pEnum = __listeners.GetEnumeratorN(); + SysTryReturnResult(NID_BASE_RT, pEnum != null, E_OUT_OF_MEMORY, "Not enough memory."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetCurrent(listenerInfo); + + if (listenerInfo.eventManager.IsValid()) + { + pEventManager = _EventManager::GetEventManagerByHandle(listenerInfo.eventManager); + if (pEventManager == null) + { + continue; + } + + _EventManager* pCurrentEventManager = _EventManager::GetCurrentEventManager(); + if (pCurrentEventManager != null) + { + if (pEventManager->GetHandle() != pCurrentEventManager->GetHandle()) + { + pEventManager->CallListenerAsync(this->GetHandle(), arg, listenerInfo.listener); + continue; + } + } + else + { + pEventManager->CallListenerAsync(this->GetHandle(), arg, listenerInfo.listener); + continue; + + } + } + + pEventListener = _EventManager::GetEventListenerObjectManager().GetObject(listenerInfo.listener); + if (pEventListener != null) + { + FireImpl(*pEventListener, *arg); + if (pRefCount->__destroyed) + { + break; + } + } + } + + delete pEnum; + return E_SUCCESS; +} + +int +_Event::GetListenerCount(void) +{ + return __listeners.GetCount(); +} + +const _HandleT< _Event > +_Event::GetHandle(void) const +{ + return __handle; +} + +_HandleT< _Event > +_Event::GetHandle(void) +{ + return __handle; +} + +void +_Event::FireImpl(IEventListener& listener, const IEventArg& arg) +{ + +} +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_EventDispatcher.cpp b/src/base/runtime/FBaseRt_EventDispatcher.cpp new file mode 100644 index 0000000..db5bec8 --- /dev/null +++ b/src/base/runtime/FBaseRt_EventDispatcher.cpp @@ -0,0 +1,218 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventDispatcher.cpp + * @brief This is the implementation file for the _EventDispatcher class. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBaseRt_ITask.h" +#include "FBaseRt_EventDispatcher.h" +#include "FBaseRt_ThreadManager.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime +{ +__thread _EventDispatcher* pCurrentEventDispatcher = null; + +_EventDispatcher::_EventDispatcher(void) + : __pMutex(null) + , __pGMainContext(null) + , __pEventFdIo(null) + , __pEventFdSource(null) +{ + +} + +_EventDispatcher::~_EventDispatcher(void) +{ + if (__pEventFdSource) + { + g_source_destroy(__pEventFdSource); + g_source_unref(__pEventFdSource); + __pEventFdSource = null; + } + + if (__pEventFdIo) + { + g_io_channel_unref(__pEventFdIo); + __pEventFdIo = null; + } + + if (__pMutex) + { + delete __pMutex; + __pMutex = null; + } +} + +result +_EventDispatcher::Construct(GMainContext* pGMainContext) +{ + result r = E_SUCCESS; + GError* pGError = null; + int eventFd = -1; + + __pGMainContext = pGMainContext; + g_main_context_ref(__pGMainContext); + + eventFd = eventfd(0, 0); + SysTryCatch(NID_BASE_RT, -1 != eventFd, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open eventfd."); + + __pEventFdIo = g_io_channel_unix_new(eventFd); + SysTryCatch(NID_BASE_RT, __pEventFdIo != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a channel for eventfd."); + g_io_channel_set_encoding(__pEventFdIo, null, &pGError); + g_io_channel_set_flags(__pEventFdIo, G_IO_FLAG_NONBLOCK, &pGError); + + __pEventFdSource = g_io_create_watch(__pEventFdIo, G_IO_IN); + SysTryCatch(NID_BASE_RT, __pEventFdSource != null, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to create a gsource for a channel."); + + g_source_set_callback(__pEventFdSource, (GSourceFunc) _EventDispatcher::OnEventReceived, this, null); + g_source_attach(__pEventFdSource, __pGMainContext); + + __pMutex = new (std::nothrow) Mutex(); + SysTryCatch(NID_BASE_RT, __pMutex != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + r = __pMutex->Create(); + SysTryCatch(NID_BASE_RT, !IsFailed(r), , r, "[%s] Failed to create mutex.", GetErrorMessage(r)); + + pCurrentEventDispatcher = this; + + return E_SUCCESS; + +CATCH: + if (__pMutex) + { + delete __pMutex; + __pMutex = null; + } + + if (__pEventFdSource) + { + g_source_unref(__pEventFdSource); + __pEventFdSource = null; + } + + if (__pEventFdIo) + { + g_io_channel_unref(__pEventFdIo); + __pEventFdIo = null; + } + + return r; +} + +result +_EventDispatcher::PutTask(_ITask* pITask, void* pParam) +{ + gsize writtenSize = 0; + uint64_t tmp = 1; + _EventMessage* pMessage = null; + + SysTryReturn(NID_BASE_RT, __pMutex != null, E_INVALID_STATE, E_INVALID_STATE, "[E_INVALID_STATE] Not constructed."); + + pMessage = new (std::nothrow) _EventMessage; + ; + SysTryReturn(NID_BASE_RT, pMessage != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + pMessage->pITask = pITask; + pMessage->pParam = pParam; + + __pMutex->Acquire(); + + __events.Add(pMessage); + + __pMutex->Release(); + + g_io_channel_write(__pEventFdIo, (const gchar*) &tmp, sizeof(tmp), &writtenSize); + + return E_SUCCESS; +} + +gboolean +_EventDispatcher::OnEventReceived(GIOChannel* pGIOChannel, GIOCondition condition, gpointer data) +{ + _EventMessage* pMessage = null; + _EventDispatcher* pEventDispatcher = (_EventDispatcher*) data; + uint64_t tmp = 0; + gsize readSize = 0; + + if (condition & G_IO_IN) + { + g_io_channel_read(pGIOChannel, (gchar*) &tmp, sizeof(tmp), &readSize); + + if (readSize == 0) + { + return TRUE; + } + + while (true) + { + pEventDispatcher->__pMutex->Acquire(); + + pMessage = null; + if (pEventDispatcher->__events.GetAt(0, pMessage) == E_SUCCESS) + { + pEventDispatcher->__events.RemoveAt(0); + } + + pEventDispatcher->__pMutex->Release(); + + if (pMessage) + { + pMessage->pITask->DoTask(pMessage->pParam); + + delete pMessage; + } + else + { + break; + } + } + } + + return TRUE; +} + +_EventDispatcher* +_EventDispatcher::GetCurrentEventDispatcher(void) +{ + return pCurrentEventDispatcher; +} + +GMainContext* +_EventDispatcher::GetGMainContext(void) +{ + SysTryReturn(NID_BASE_RT, __pMutex != null, null, E_INVALID_STATE, "[E_INVALID_STATE] Not constructed."); + + return __pGMainContext; +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_EventDrivenThreadEvent.cpp b/src/base/runtime/FBaseRt_EventDrivenThreadEvent.cpp new file mode 100644 index 0000000..72e887f --- /dev/null +++ b/src/base/runtime/FBaseRt_EventDrivenThreadEvent.cpp @@ -0,0 +1,83 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventDrivenThreadEvent.cpp + * @brief This is the implementation file for the _EventDrivenThreadEvent class. + * + */ + + +#include +#include "FBaseRt_EventDrivenThreadEvent.h" +#include "FBaseRt_EventDrivenThreadEventArg.h" +#include "FBaseRt_IEventDrivenThreadEventListener.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime +{ + +_EventDrivenThreadEvent::_EventDrivenThreadEvent(void) +{ + +} + +_EventDrivenThreadEvent::~_EventDrivenThreadEvent(void) +{ + +} + +result +_EventDrivenThreadEvent::Construct(_IEventDrivenThreadEventListener& listener) +{ + result r = E_SUCCESS; + + r = Initialize(); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Failed to initialize.", GetErrorMessage(r)); + + r = AddListener(listener); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Failed add listener.", GetErrorMessage(r)); + + return r; +} + +void +_EventDrivenThreadEvent::FireImpl(IEventListener& listener, const IEventArg& arg) +{ + _IEventDrivenThreadEventListener* pEventDrivenThreadEventListener = + dynamic_cast <_IEventDrivenThreadEventListener*>(&listener); + const _EventDrivenThreadEventArg* pEventDrivenThreadEventArg = dynamic_cast (&arg); + SysTryReturnVoidResult(NID_BASE_RT, pEventDrivenThreadEventListener != null && pEventDrivenThreadEventArg != null, E_INVALID_ARG, + "[%s] listener or agr is null.", + E_INVALID_ARG); + + if (pEventDrivenThreadEventArg->GetType() == EVENT_DRIVEN_THREAD_EVENT_TYPE_USER_EVENT) + { + pEventDrivenThreadEventListener->OnUserEventReceivedN( + pEventDrivenThreadEventArg->GetRequestId(), pEventDrivenThreadEventArg->GetArgs()); + } + else + { + pEventDrivenThreadEventListener->OnStop(); + } +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_EventDrivenThreadEvent.h b/src/base/runtime/FBaseRt_EventDrivenThreadEvent.h new file mode 100644 index 0000000..1a5acf7 --- /dev/null +++ b/src/base/runtime/FBaseRt_EventDrivenThreadEvent.h @@ -0,0 +1,61 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventDrivenThreadEvent.h + * @brief This is the header file for the _EventDrivenThreadEvent class. + * + * This file contains the declarations of _EventDrivenThreadEvent. + */ + + +#ifndef _FBASERT_INTERNAL_EVENT_DRIVEN_THREAD_EVENT_H_ +#define _FBASERT_INTERNAL_EVENT_DRIVEN_THREAD_EVENT_H_ + +#include +#include +#include + +#include "FBaseRt_Event.h" +#include "FBaseRt_IEventDrivenThreadEventListener.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _EventDrivenThreadEvent + : public Tizen::Base::Runtime::_Event +{ +public: + _EventDrivenThreadEvent(void); + + /** + * This is the destructor. + */ + virtual ~_EventDrivenThreadEvent(void); + + result Construct(_IEventDrivenThreadEventListener& listener); + +protected: + virtual void FireImpl(IEventListener& listener, const IEventArg& arg); +}; + + +} } } // Tizen::Runtime + + +#endif diff --git a/src/base/runtime/FBaseRt_EventDrivenThreadEventArg.cpp b/src/base/runtime/FBaseRt_EventDrivenThreadEventArg.cpp new file mode 100644 index 0000000..f3fdadf --- /dev/null +++ b/src/base/runtime/FBaseRt_EventDrivenThreadEventArg.cpp @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventDrivenThreadEventArg.cpp + * @brief This is the implementation file for the _EventDrivenThreadEventArg class. + * + */ + +#include +#include "FBaseRt_EventDrivenThreadEventArg.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime +{ +_EventDrivenThreadEventArg::_EventDrivenThreadEventArg(_EventDrivenTrheadEventType type, RequestId reqId, const Tizen::Base::Collection::IList* pArgs) + : __type(type) + , __reqId(reqId) + , __pArgs(pArgs) +{ + +} + +_EventDrivenThreadEventArg::~_EventDrivenThreadEventArg(void) +{ + +} + +RequestId +_EventDrivenThreadEventArg::GetRequestId(void) const +{ + return __reqId; +} + +IList* +_EventDrivenThreadEventArg::GetArgs(void) const +{ + return (IList*) __pArgs; +} + +_EventDrivenTrheadEventType +_EventDrivenThreadEventArg::GetType(void) const +{ + return __type; +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_EventDrivenThreadEventArg.h b/src/base/runtime/FBaseRt_EventDrivenThreadEventArg.h new file mode 100644 index 0000000..1f51d9d --- /dev/null +++ b/src/base/runtime/FBaseRt_EventDrivenThreadEventArg.h @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventDrivenThreadEventArg.h + * @brief This is the header file for the _EventDrivenThreadEventArg class. + * + * This file contains the declarations of _EventDrivenThreadEventArg. + */ + +#ifndef _FBASERT_INTERNAL_EVENT_DRIVEN_THREAD_EVENT_ARG_H_ +#define _FBASERT_INTERNAL_EVENT_DRIVEN_THREAD_EVENT_ARG_H_ + +#include +#include +#include "FBaseRtIEventArg.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +enum _EventDrivenTrheadEventType +{ + EVENT_DRIVEN_THREAD_EVENT_TYPE_USER_EVENT, + EVENT_DRIVEN_THREAD_EVENT_TYPE_STOP +}; + +class _EventDrivenThreadEventArg + : public Tizen::Base::Object + , public IEventArg +{ +public: + _EventDrivenThreadEventArg(_EventDrivenTrheadEventType type, RequestId reqId, const Tizen::Base::Collection::IList* pArgs); + virtual ~_EventDrivenThreadEventArg(void); + + RequestId GetRequestId(void) const; + Tizen::Base::Collection::IList* GetArgs(void) const; + _EventDrivenTrheadEventType GetType(void) const; + +private: + _EventDrivenTrheadEventType __type; + RequestId __reqId; + const Tizen::Base::Collection::IList* __pArgs; +}; + + +} } } // Tizen::Runtime + + +#endif diff --git a/src/base/runtime/FBaseRt_EventDrivenThreadImpl.cpp b/src/base/runtime/FBaseRt_EventDrivenThreadImpl.cpp new file mode 100644 index 0000000..e1e3e93 --- /dev/null +++ b/src/base/runtime/FBaseRt_EventDrivenThreadImpl.cpp @@ -0,0 +1,182 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventDrivenThreadImpl.cpp + * @brief This is the implementation file for the _EventDrivenThreadImpl class. + * + */ + +#include +#include +#include "FBaseRt_EventDrivenThreadImpl.h" + +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Base { namespace Runtime +{ + +_EventDrivenThreadImpl::_EventDrivenThreadImpl(Thread& thread, const String& name, long stackSize, ThreadPriority priority) + : _ThreadImpl(thread, name, stackSize, priority, THREAD_TYPE_EVENT_DRIVEN) + , __pGMainLoop(null) + , __pEventDispatcher(null) + , __pEventManager(null) + , __pEvent(null) +{ + +} + +_EventDrivenThreadImpl::~_EventDrivenThreadImpl(void) +{ + delete __pEventDispatcher; + delete __pEventManager; + delete __pEvent; +} + +result +_EventDrivenThreadImpl::Stop(void) +{ + result r = E_SUCCESS; + + _EventDrivenThreadEventArg* pEventArg = new (std::nothrow) _EventDrivenThreadEventArg(EVENT_DRIVEN_THREAD_EVENT_TYPE_STOP + , 0, null); + if (__pEvent) + { + r = __pEvent->Fire(*pEventArg); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Failed to send a stop event", GetErrorMessage(r)); + } + else + { + __pendingEvents.Add(pEventArg); + } + + + return E_SUCCESS; +} + +Tizen::Base::Object* +_EventDrivenThreadImpl::Run(void) +{ + result r = E_SUCCESS; + _EventDrivenThreadEventArg* pArg = null; + + for (int i = 0; i < __pendingEvents.GetCount(); i++) + { + __pendingEvents.GetAt(i, pArg); + + r = __pEvent->FireAsync(*pArg); + if (IsFailed(r)) + { + continue; + } + } + + g_main_loop_run(__pGMainLoop); + + return null; +} + +result +_EventDrivenThreadImpl::Initialize(void) +{ + result r = E_SUCCESS; + GMainContext* pGMainContext = null; + _EventManager* pEventManager = null; + _EventDrivenThreadEvent* pEvent = null; + + _ThreadImpl::Initialize(); + + pGMainContext = g_main_context_new(); + g_main_context_push_thread_default(pGMainContext); + + pEventManager = new (std::nothrow) _EventManager; + SysTryReturn(NID_BASE_RT, pEventManager != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + r = pEventManager->Construct(pGMainContext); + SysTryCatch(NID_BASE_RT, !IsFailed(r), , r, "[%s] Failed to initialize event manager.", GetErrorMessage(r)); + + _ThreadImpl::SetEventManager(pEventManager); + + // Initialize event driven thread + // This should be done after initialzing event manager has finished. + pEvent = new (std::nothrow) _EventDrivenThreadEvent; + SysTryReturn(NID_BASE_RT, pEvent != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + r = pEvent->Construct(*this); + SysTryCatch(NID_BASE_RT, !IsFailed(r), , r, "[%s] Failed to initialize event driven thread event.", GetErrorMessage(r)); + + __pEventManager = pEventManager; + __pEvent = pEvent; + + __pGMainLoop = g_main_loop_new(pGMainContext, FALSE); + + __pEventDispatcher = new (std::nothrow) _EventDispatcher(); + __pEventDispatcher->Construct(pGMainContext); + + return E_SUCCESS; + +CATCH: + g_main_context_unref(pGMainContext); + + delete pEvent; + + delete pEventManager; + + _ThreadImpl::Finalize(); + + return r; +} + +result +_EventDrivenThreadImpl::SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs) +{ + result r = E_SUCCESS; + _EventDrivenThreadEventArg* pEventArg = null; + + pEventArg = new (std::nothrow) _EventDrivenThreadEventArg(EVENT_DRIVEN_THREAD_EVENT_TYPE_USER_EVENT, requestId, pArgs); + + if (__pEvent) + { + r = __pEvent->FireAsync(*pEventArg); + } + else + { + __pendingEvents.Add(pEventArg); + } + + return r; +} + +void +_EventDrivenThreadImpl::OnUserEventReceivedN(RequestId reqId, IList* pArgs) +{ + if (_pThread != null) + { + _pThread->OnUserEventReceivedN(reqId, pArgs); + } +} + +void +_EventDrivenThreadImpl::OnStop(void) +{ + if (__pGMainLoop != null) + { + g_main_loop_quit(__pGMainLoop); + } +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_EventDrivenThreadImpl.h b/src/base/runtime/FBaseRt_EventDrivenThreadImpl.h new file mode 100644 index 0000000..1c5ed05 --- /dev/null +++ b/src/base/runtime/FBaseRt_EventDrivenThreadImpl.h @@ -0,0 +1,77 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventDrivenThreadImpl.h + * @brief This is the header file for the _EventDrivenThreadImpl class. + * + * This file contains the declarations of _EventDrivenThreadImpl. + */ + +#ifndef _FRT_THREAD_INTERNAL_EVENTDRIVEN_THREAD_IMPL_H_ +#define _FRT_THREAD_INTERNAL_EVENTDRIVEN_THREAD_IMPL_H_ + +#include + +#include + +#include "FBaseRt_EventDispatcher.h" +#include "FBaseRt_ThreadImpl.h" +#include "FBaseRt_EventDrivenThreadEvent.h" +#include "FBaseRt_EventDrivenThreadEventArg.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _EventDrivenThreadImpl + : public _ThreadImpl + , public _IEventDrivenThreadEventListener +{ +public: + _EventDrivenThreadImpl(Thread& thread, const String& name, long stackSize, ThreadPriority priority); + + virtual ~_EventDrivenThreadImpl(void); + + virtual result Stop(void); + + virtual Tizen::Base::Object* Run(void); + + virtual result Initialize(void); + + virtual result SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs); + + virtual void OnUserEventReceivedN(RequestId reqId, Tizen::Base::Collection::IList* pArgs); + + virtual void OnStop(void); + +private: + _EventDrivenThreadImpl(const _EventDrivenThreadImpl& value); + + _EventDrivenThreadImpl& operator =(const _EventDrivenThreadImpl& value); + +private: + GMainLoop* __pGMainLoop; + _EventDispatcher* __pEventDispatcher; + _EventManager* __pEventManager; + _EventDrivenThreadEvent* __pEvent; + Tizen::Base::Collection::LinkedListT <_EventDrivenThreadEventArg*> __pendingEvents; +}; + +} } } // Tizen::Base::Runtime + +#endif // _FRT_THREAD_INTERNAL_EVENTDRIVEN_THREAD_H_ diff --git a/src/base/runtime/FBaseRt_EventImpl.cpp b/src/base/runtime/FBaseRt_EventImpl.cpp new file mode 100644 index 0000000..a4d5137 --- /dev/null +++ b/src/base/runtime/FBaseRt_EventImpl.cpp @@ -0,0 +1,52 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventImpl.cpp + * @brief This is the implementation file for the Event class. + * + */ + +#include +#include +#include +#include "FBaseRt_EventImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime +{ + +_EventImpl::_EventImpl(Event& event) + :__pEvent(&event) +{ + Initialize(); +} + +_EventImpl::~_EventImpl(void) +{ + +} + +void +_EventImpl::FireImpl(IEventListener& listener, const IEventArg& arg) +{ + __pEvent->FireImpl(listener, arg); +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_EventImpl.h b/src/base/runtime/FBaseRt_EventImpl.h new file mode 100644 index 0000000..f0dd8fa --- /dev/null +++ b/src/base/runtime/FBaseRt_EventImpl.h @@ -0,0 +1,80 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventImpl.h + * @brief This is the header file for the %_EventImpl class. + * + * This file contains the declarations of the %_EventImpl class. + */ + +#ifndef _FBASE_RT_INTERNAL_EVENTIMPL_H_ +#define _FBASE_RT_INTERNAL_EVENTIMPL_H_ + +#include "FBaseRt_Event.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +class Event; +class IEventArg; +class IEventListener; + +/** +* @class _EventImpl +* @brief This class provides methods for delivering an event with an argument synchronously and asynchronously. +* @since 2.0 +*/ +class _EventImpl + : public Tizen::Base::Runtime::_Event +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _EventImpl(Event& event); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_EventImpl(void); + +protected: + /** + * Implement to call the corresponding event listener's method. + * + * @since 2.0 + * + * @param[in] listener The listener instance which is currently processing + * @param[in] arg The event argument that is fired + * + * @remark A derived class must override this method. + */ + virtual void FireImpl(IEventListener& listener, const IEventArg& arg); + +private: + Event* __pEvent; + +}; // _EventImpl + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_EVENTIMPL_H_ diff --git a/src/base/runtime/FBaseRt_EventManager.cpp b/src/base/runtime/FBaseRt_EventManager.cpp new file mode 100644 index 0000000..5f49426 --- /dev/null +++ b/src/base/runtime/FBaseRt_EventManager.cpp @@ -0,0 +1,420 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventManager.cpp + * @brief This is the implementation file for the _EventManager class. + * + */ + +#include +#include +#include +#include +#include +#include + +#include +#include "FBaseRt_Event.h" +#include "FBaseRt_ThreadManager.h" +#include "FBaseRt_ThreadImpl.h" +#include "FBaseRt_EventManager.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime +{ +bool +_EventManager::_EventMessage::operator ==(const _EventMessage& rhs) const +{ + if (id == rhs.id) + { + return true; + } + + return false; +} + +bool +_EventManager::_EventMessage::operator !=(const _EventMessage& rhs) const +{ + if (id != rhs.id) + { + return true; + } + + return false; +} + +_EventManager::_EventMessage& +_EventManager::_EventMessage::operator =(const _EventMessage& rhs) +{ + if (this != &rhs) + { + id = rhs.id; + type = rhs.type; + event = rhs.event; + arg = *const_cast< std::tr1::shared_ptr< IEventArg >* >(&rhs.arg); + listener = rhs.listener; + } + + return *this; +} + +_EventManager::_EventManager(void) + : __pMutex(null) + , __pSource(null) + , __pChannel(null) + , __pGmainContext(null) + , __pActive(null) + , __pReady(null) +{ + +} + +_EventManager::~_EventManager(void) +{ + GetEventManagerObjectManager().Unregister(__handle); + + if (__pSource) + { + g_source_destroy(__pSource); + g_source_unref(__pSource); + } + + if (__pChannel) + { + g_io_channel_unref(__pChannel); + } + + delete __pMutex; +} + +result +_EventManager::Construct(GMainContext* pGmainContext) +{ + result r = E_SUCCESS; + GError* pGError = null; + GIOChannel* pChannel = null; + GSource* pSource = null; + Mutex* pMutex = null; + + int eventFd = eventfd(0, 0); + SysTryReturnResult(NID_BASE_RT, eventFd != -1, E_SYSTEM, "Failed to open eventfd."); + + pChannel = g_io_channel_unix_new(eventFd); + SysTryCatch(NID_BASE_RT, pChannel != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a channel for eventfd."); + + g_io_channel_set_encoding(pChannel, null, &pGError); + g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError); + + g_io_channel_set_close_on_unref(pChannel, TRUE); + eventFd = -1; + + pSource = g_io_create_watch(pChannel, G_IO_IN); + SysTryCatch(NID_BASE_RT, pSource != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a gsource for a channel."); + + g_source_set_callback(pSource, (GSourceFunc) _EventManager::OnEventReceived, this, null); + g_source_attach(pSource, pGmainContext); + + pMutex = new (std::nothrow) Mutex(); + SysTryCatch(NID_BASE_RT, pMutex != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + r = pMutex->Create(); + SysTryCatch(NID_BASE_RT, !IsFailed(r), , r, "[%s] Failed to create mutex.", GetErrorMessage(r)); + + __handle = GetEventManagerObjectManager().Register(*this); + + __pChannel = pChannel; + __pSource = pSource; + __pMutex = pMutex; + __pGmainContext = pGmainContext; + + __pActive = &__messages1; + __pReady = &__messages2; + + return E_SUCCESS; + +CATCH: + delete pMutex; + + if (pSource) + { + g_source_destroy(pSource); + g_source_unref(pSource); + } + + if (pChannel) + { + g_io_channel_unref(pChannel); + } + + if (eventFd != -1) + { + close(eventFd); + } + + return r; +} + +result +_EventManager::CallListenerAsync(const _HandleT< _Event >& event, std::tr1::shared_ptr< IEventArg > arg, const _HandleT< IEventListener >& listener) +{ + SysTryReturn(NID_BASE_RT, __pGmainContext != null, E_INVALID_STATE, E_INVALID_STATE, "[E_INVALID_STATE] Not constructed."); + + _EventMessage message; + + message.type = MESSAGE_TYPE_CALL_LISTENER; + message.event = event; + message.arg = arg; + message.listener = listener; + + __pMutex->Acquire(); + + __pActive->Add(message); + + __pMutex->Release(); + + uint64_t count = 1; + gsize writtenSize = 0; + + g_io_channel_write(__pChannel, (const gchar*) &count, sizeof(count), &writtenSize); + + return E_SUCCESS; +} + +result +_EventManager::FireEventAsync(const _HandleT< _Event >& event, std::tr1::shared_ptr< IEventArg > arg) +{ + SysTryReturnResult(NID_BASE_RT, __pGmainContext != null, E_INVALID_STATE, "Not constructed."); + + _EventMessage message; + + message.type = MESSAGE_TYPE_FIRE_EVENT; + message.event = event; + message.arg = arg; + + __pMutex->Acquire(); + + __pActive->Add(message); + + __pMutex->Release(); + + uint64_t count = 1; + gsize writtenSize = 0; + + g_io_channel_write(__pChannel, (const gchar*) &count, sizeof(count), &writtenSize); + + return E_SUCCESS; +} + +gboolean +_EventManager::OnEventReceived(GIOChannel* pGIOChannel, GIOCondition condition, gpointer data) +{ + _EventManager* pEventManager = (_EventManager*) data; + + if (condition & G_IO_IN) + { + uint64_t tmp = 0; + gsize readSize = 0; + + g_io_channel_read(pGIOChannel, (gchar*) &tmp, sizeof(tmp), &readSize); + + if (readSize == 0) + { + return TRUE; + } + + pEventManager->__pMutex->Acquire(); + + ArrayListT< _EventMessage >* pMessages = pEventManager->__pActive; + + pEventManager->__pActive = pEventManager->__pReady; + pEventManager->__pReady = pMessages; + + pEventManager->__pMutex->Release(); + + IEnumeratorT< _EventMessage >* pEnum = pMessages->GetEnumeratorN(); + _Event* pEvent = null; + IEventListener* pEventListener = null; + _EventMessage message; + + while (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetCurrent(message); + + pEvent = GetEventObjectManager().GetObject(message.event); + + if (pEvent != null) + { + if (message.type == MESSAGE_TYPE_FIRE_EVENT) + { + pEvent->Fire(message.arg); + } + else + { + pEventListener = GetEventListenerObjectManager().GetObject(message.listener); + if (pEventListener != null) + { + pEvent->FireImpl(*pEventListener, *message.arg); + } + } + } + } + + delete pEnum; + pMessages->RemoveAll(); + } + + return TRUE; +} + +_EventManager* +_EventManager::GetCurrentEventManager(void) +{ + _ThreadImpl* pThreadImpl = _ThreadImpl::GetCurrentThreadImpl(); + SysTryReturn(NID_BASE_RT, pThreadImpl != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] This is not OSP thread."); + + ThreadType threadType = pThreadImpl->GetThreadType(); + SysTryReturn(NID_BASE_RT, threadType != THREAD_TYPE_WORKER, null, E_INVALID_OPERATION, + "[E_INVALID_OPERATION] This is a worker thread."); + + _EventManager* pEventManager = pThreadImpl->GetEventManager(); + SysTryReturn(NID_BASE_RT, pEventManager != null, null, E_INVALID_STATE, "[E_INVALID_STATE] Event manager is not initialized."); + + return pEventManager; +} + +result +_EventManager::RegisterEvent(const _HandleT< _Event >& event) +{ + SysTryReturnResult(NID_BASE_RT, __pGmainContext != null, E_INVALID_STATE, "Not constructed."); + + result r = E_SUCCESS; + bool exist = false; + + exist = __events.Contains(event); + SysTryReturnResult(NID_BASE_RT, !exist, E_OBJ_ALREADY_EXIST, "_Event already exist."); + + r = __events.Add(event); + SysTryReturn(NID_BASE_RT, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_EventManager::UnregisterEvent(const _HandleT< _Event >& event) +{ + SysTryReturnResult(NID_BASE_RT, __pGmainContext != null, E_INVALID_STATE, "Not constructed."); + + result r = E_SUCCESS; + + r = __events.Remove(event); + SysTryReturnResult(NID_BASE_RT, !IsFailed(r), E_OBJ_NOT_FOUND, "Listener not found."); + + ClearAllPendingEventMessages(event); + + return E_SUCCESS; +} + +void +_EventManager::ClearAllPendingEventMessages(const _HandleT< _Event >& event) +{ + ArrayListT< _EventMessage > messages; + _EventMessage message; + + __pMutex->Acquire(); + + IEnumeratorT< _EventMessage >* pEnum = __pActive->GetEnumeratorN(); + while (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetCurrent(message); + if (message.event != event) + { + messages.Add(message); + } + } + + delete pEnum; + pEnum = null; + + __pActive->RemoveAll(); + __pActive->AddItems(messages); + messages.RemoveAll(); + + pEnum = __pReady->GetEnumeratorN(); + while (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetCurrent(message); + if (message.event != event) + { + messages.Add(message); + } + } + + delete pEnum; + + __pReady->RemoveAll(); + __pReady->AddItems(messages); + messages.RemoveAll(); + + __pMutex->Release(); +} + +_HandleT< _EventManager > +_EventManager::GetHandle(void) const +{ + return __handle; +} + +_EventManager* +_EventManager::GetEventManagerByHandle(const _HandleT< _EventManager >& handle) +{ + _EventManager* pEventManager = GetEventManagerObjectManager().GetObject(handle); + SysTryReturn(NID_BASE_RT, pEventManager != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND]"); + + return pEventManager; +} + +_ObjectManagerT< _EventManager >& +_EventManager::GetEventManagerObjectManager(void) +{ + static _ObjectManagerT< _EventManager > objectManager; + + return objectManager; +} + +_ObjectManagerT< _Event >& +_EventManager::GetEventObjectManager(void) +{ + static _ObjectManagerT< _Event > objectManager; + + return objectManager; +} + +_ObjectManagerT< IEventListener >& +_EventManager::GetEventListenerObjectManager(void) +{ + static _ObjectManagerT< IEventListener > objectManager; + + return objectManager; +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_EventManager.h b/src/base/runtime/FBaseRt_EventManager.h new file mode 100644 index 0000000..9590a29 --- /dev/null +++ b/src/base/runtime/FBaseRt_EventManager.h @@ -0,0 +1,240 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventManager.h + * @brief This is the header file for the _EventManager class. + * + * This file contains the declarations of _EventManager. + */ + +#ifndef _FBASE_RT_INTERNAL_EVENT_MANAGER_H_ +#define _FBASE_RT_INTERNAL_EVENT_MANAGER_H_ + +#include +#include + +#include +#include +#include +#include +#include + +#include "FBase_HandleT.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +class Mutex; +class _Event; +class IEventArg; +class IEventListener; + +/** +* @class _EventManager +* @brief This class provides methods for managingasynchronous event. +* @since 2.0 +* +* This class provides methods for managing asynchronous event. +*/ +class _EventManager + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * value. + * + * @since 2.0 + */ + _EventManager(void); + + /** + * This is the destructor for this class + * @since 2.0 + */ + virtual ~_EventManager(void); + + /** + * Initializes this instanc of %_EventManager. + * + * @since 2.0 + * + * @return An error code + * @param[in] pGmainContext A GMainLoopContext + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + */ + result Construct(GMainContext* pGmainContext); + + /** + * Registers an event. + * + * @since 2.0 + * @return An error code + * @param[in] event The handle of an event to register + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_ALREADY_EXIST The event has already been registered. + * @exception E_SYSTEM A system error has occurred. + */ + result RegisterEvent(const _HandleT< _Event >& event); + + /** + * Unregisters an event. + * + * @since 2.0 + * + * @return An error code + * @param[in] event The handle of an event to unregister + * @exception E_SUCCESS The method is successful. + * @exception E_OBJ_NOT_FOUND The event has not been registered. + */ + result UnregisterEvent(const _HandleT< _Event >& event); + + /** + * Returns the %_EventManager of current thread. + * + * @since 2.0 + * + * @return The pointer to _EventManager + * + * @remark null will be returned if this is called by a worker thread. + */ + static _EventManager* GetCurrentEventManager(void); + + /** + * Sends an event asynchronously. + * + * @since 2.0 + * + * @return An error code + * @param[in] event The event to send + * @param[in] arg The event arg + * @exception E_SUCCESS The method is successful. + * @remark This takes ownership of the arg. Therefore the caller must not delete the arg instance. + */ + result FireEventAsync(const _HandleT< _Event >& event, std::tr1::shared_ptr< IEventArg > arg); + + /** + * Calls a listener added to an event asynchronously. + * + * @since 2.0 + * + * @return An error code + * @param[in] event The event + * @param[in] arg The event arg + * @param[in] listener The listener to call + * @exception E_SUCCESS The method is successful. + * @remark This takes ownership of the arg. Therefore the caller must not delete the arg instance. + */ + result CallListenerAsync(const _HandleT< _Event >& event, std::tr1::shared_ptr< IEventArg > arg, const _HandleT< IEventListener >& listener); + + /** + * Clears all pending event messages of an event. + * + * @since 2.0 + * @param[in] event The event to clear + */ + void ClearAllPendingEventMessages(const _HandleT< _Event >& event); + + /** + * Returns the handle + * + * @since 2.0 + * @param[in] event The event to clear + */ + _HandleT< _EventManager > GetHandle(void) const; + + /** + * Gets _EventManager using given handle + * + * @since 2.0 + * + * @param[in] handle The handle of _EventManager + */ + static _EventManager* GetEventManagerByHandle(const _HandleT< _EventManager >& handle); + + /** + * Gets object manager for _EventManager + * + * @since 2.0 + */ + static _ObjectManagerT< _EventManager >& GetEventManagerObjectManager(void); + + /** + * Gets object manager for _Event + * + * @since 2.0 + */ + static _ObjectManagerT< _Event >& GetEventObjectManager(void); + + /** + * Gets object manager for IEventListener + * + * @since 2.0 + */ + static _ObjectManagerT< IEventListener >& GetEventListenerObjectManager(void); + +private: + _EventManager(const _EventManager& rhs); + _EventManager& operator =(const _EventManager& rhs); + + static gboolean OnEventReceived(GIOChannel* pChannel, GIOCondition condition, gpointer data); + +private: + enum _MessageType + { + MESSAGE_TYPE_FIRE_EVENT, + MESSAGE_TYPE_CALL_LISTENER + }; + + struct _EventMessage + { + _EventMessage(void) + : id(0) + , type(MESSAGE_TYPE_FIRE_EVENT) + { + } + + int id; + _MessageType type; + _HandleT< _Event > event; + std::tr1::shared_ptr< IEventArg > arg; + _HandleT< IEventListener > listener; + + bool operator ==(const _EventMessage& rhs) const; + bool operator !=(const _EventMessage& rhs) const; + + _EventMessage& operator =(const _EventMessage& rhs); + }; + +private: + Mutex* __pMutex; + GSource* __pSource; + GIOChannel* __pChannel; + GMainContext* __pGmainContext; + _HandleT< _EventManager > __handle; + Tizen::Base::Collection::LinkedListT< _HandleT< _Event > > __events; + Tizen::Base::Collection::ArrayListT< _EventMessage > __messages1; + Tizen::Base::Collection::ArrayListT< _EventMessage > __messages2; + Tizen::Base::Collection::ArrayListT< _EventMessage >* __pActive; + Tizen::Base::Collection::ArrayListT< _EventMessage >* __pReady; +}; + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_EVENT_MANAGER_H_ diff --git a/src/base/runtime/FBaseRt_EventPendingOperationManager.cpp b/src/base/runtime/FBaseRt_EventPendingOperationManager.cpp new file mode 100644 index 0000000..031b30c --- /dev/null +++ b/src/base/runtime/FBaseRt_EventPendingOperationManager.cpp @@ -0,0 +1,103 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventPendingOperationManager.cpp + * @brief This is the implementation file for the _EventPendingOperationManager class. + * + */ + +#include + +#include + +#include "FBaseRtEvent.h" +#include +#include "FBaseRt_EventPendingOperationManager.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Base { namespace Runtime +{ + +_EventPendingOperationManager::_EventPendingOperationManager(void) +{ + +} + +result +_EventPendingOperationManager::AddFilter(const IEventFilter& filter) +{ + result r = E_SUCCESS; + + _EventPendingOperation* pPendingOperation = new (std::nothrow) _EventPendingOperation; + + pPendingOperation->opType = EVENT_OPERATION_ADD_FILTER; + pPendingOperation->pFilter = &filter; + + r = __operations.Add(*pPendingOperation); + + return r; +} + +result +_EventPendingOperationManager::RemoveFilter(const IEventFilter& filter) +{ + result r = E_SUCCESS; + + _EventPendingOperation* pPendingOperation = new (std::nothrow) _EventPendingOperation; + + pPendingOperation->opType = EVENT_OPERATION_REMOVE_FILTER; + pPendingOperation->pFilter = &filter; + + r = __operations.Add(*pPendingOperation); + + return r; +} + +result +_EventPendingOperationManager::AddListener(const IEventListener& listener) +{ + _EventPendingOperation* pPendingOperation = new (std::nothrow) _EventPendingOperation; + + pPendingOperation->opType = EVENT_OPERATION_ADD_LISTENER; + pPendingOperation->pListener = &listener; + + result r = __operations.Add(*pPendingOperation); + + return r; +} + +result +_EventPendingOperationManager::RemoveListener(const IEventListener& listener) +{ + result r = E_SUCCESS; + + _EventPendingOperation* pPendingOperation = new (std::nothrow) _EventPendingOperation; + + pPendingOperation->opType = EVENT_OPERATION_REMOVE_LISTENER; + pPendingOperation->pListener = &listener; + + r = __operations.Add(*pPendingOperation); + + return r; +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRt_EventPendingOperationManager.h b/src/base/runtime/FBaseRt_EventPendingOperationManager.h new file mode 100644 index 0000000..4e1a1be --- /dev/null +++ b/src/base/runtime/FBaseRt_EventPendingOperationManager.h @@ -0,0 +1,136 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_EventPendingOperationManager.h + * @brief This is the header file of __EventPendingOperationManager class. + */ + +#ifndef _FRT_INTERNAL_EVENT_PENDING_OPERATION_MANAGER_H_ +#define _FRT_INTERNAL_EVENT_PENDING_OPERATION_MANAGER_H_ + + +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ + + +// forward declaration +class Event; +class IEventFilter; +class IEventListener; + +enum EventPendingOperationType +{ + EVENT_OPERATION_REMOVE_FILTER, + EVENT_OPERATION_ADD_FILTER, + EVENT_OPERATION_REMOVE_LISTENER, + EVENT_OPERATION_ADD_LISTENER, + +}; + + +// +// @class _EventPendingOperationManager +// This class manages the pending operation of the Event class. +// Pending operations are the collection related operations because the collection does not permit +// the add/remove operation when it is traversing. +// +// Event class makes an add/remove filter/listener a pending operations while they are executed in the filter or the listener. +// +class _EventPendingOperationManager + : public Tizen::Base::Object +{ +public: + /** + * Is a default constructor. + */ + _EventPendingOperationManager(void); + + /** + * This methods completes the pending operation to add filters. + * + * @param[in] pFilter The pointer of filters to add. + * @return The error code. + * @exception E_SUCCESS + */ + result AddFilter(const IEventFilter& filter); + + + /** + * This methods completes the pending operation to remove filters. + * + * @param[in] pFilter The pointer of filters to remove. + * @return The error code. + * @exception E_SUCCESS + */ + result RemoveFilter(const IEventFilter& filter); + + + /** + * This methods completes the pending operation to add listeners. + * + * @param[in] pListener The pointer of listeners to add. + * @return The error code. + * @exception E_SUCCESS + */ + result AddListener(const IEventListener& listener); + + + /** + * This methods completes the pending operation to remove listeners. + * + * @param[in] pListener The pointer of listeners to remove. + * @return The error code. + * @exception E_SUCCESS + */ + result RemoveListener(const IEventListener& listener); + + +private: + class _EventPendingOperation + : public Tizen::Base::Object + { +public: + _EventPendingOperation(void) + : opType(EVENT_OPERATION_ADD_LISTENER) + , pFilter(null) + , pListener(null) + { + + } + + virtual ~_EventPendingOperation(void) + { + + } + + EventPendingOperationType opType; + const IEventFilter* pFilter; + const IEventListener* pListener; + }; + + Tizen::Base::Collection::LinkedList __operations; + +}; + +} } } // Tizen::Runtime + +#endif // _FRT_INTERNAL_EVENT_PENDING_OPERATION_MANAGER_H_ diff --git a/src/base/runtime/FBaseRt_FilterInfo.h b/src/base/runtime/FBaseRt_FilterInfo.h new file mode 100644 index 0000000..603fad0 --- /dev/null +++ b/src/base/runtime/FBaseRt_FilterInfo.h @@ -0,0 +1,49 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_FilterInfo.h + * @brief This is the header file of _FilterInfo. + */ + +#ifndef _FBASE_RT_INTERNAL_FILTER_INFO_H_ +#define _FBASE_RT_INTERNAL_FILTER_INFO_H_ + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _FilterInfo + : public Tizen::Base::Object +{ +public: + _FilterInfo(void) + : pFilter(null) + { + } + + virtual ~_FilterInfo(void) + { + } + +public: + const IEventFilter* pFilter; +}; + +} } } // Tizen::Runtime + + +#endif // _FBASE_RT_INTERNAL_FILTER_INFO_H_ diff --git a/src/base/runtime/FBaseRt_IEventDrivenThreadEventListener.h b/src/base/runtime/FBaseRt_IEventDrivenThreadEventListener.h new file mode 100644 index 0000000..ac44278 --- /dev/null +++ b/src/base/runtime/FBaseRt_IEventDrivenThreadEventListener.h @@ -0,0 +1,51 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_IEventDrivenThreadEventListener.h + * @brief This is the header file for the _IEventDrivenThreadEventListener class. + * + * This file contains the declarations of ClassName. + */ + + +#ifndef _FBASERT_INTERNAL_IEVENT_DRIVEN_THREAD_EVENT_LISTENER_H_ +#define _FBASERT_INTERNAL_IEVENT_DRIVEN_THREAD_EVENT_LISTENER_H_ + +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _IEventDrivenThreadEventListener + : public IEventListener +{ +public: + virtual ~_IEventDrivenThreadEventListener(void){} + + virtual void OnUserEventReceivedN(RequestId reqId, Tizen::Base::Collection::IList* pArgs) = 0; + + virtual void OnStop(void) = 0; +}; + + +} } } // Tizen::Runtime + + +#endif diff --git a/src/base/runtime/FBaseRt_ITask.cpp b/src/base/runtime/FBaseRt_ITask.cpp new file mode 100644 index 0000000..9ed5731 --- /dev/null +++ b/src/base/runtime/FBaseRt_ITask.cpp @@ -0,0 +1,34 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_ITask.cpp + * @brief This is the implementation file for the _ITask class. + * + */ + + +#include "FBaseRt_ITask.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +_ITask::~_ITask(void) +{ +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_LibraryImpl.cpp b/src/base/runtime/FBaseRt_LibraryImpl.cpp new file mode 100644 index 0000000..2d0873f --- /dev/null +++ b/src/base/runtime/FBaseRt_LibraryImpl.cpp @@ -0,0 +1,144 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_LibraryImpl.cpp + * @brief This is the implementation file for the _LibraryImpl class. + * + */ + +#include +#include +#include +#include +#include +#include "FBase_StringConverter.h" +#include "FBaseRt_LibraryImpl.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +_LibraryImpl::_LibraryImpl(void) + : __pHandle(null) +{ +} + +_LibraryImpl::~_LibraryImpl(void) +{ + if (__pHandle != null) + { + dlclose(__pHandle); + } +} + +result +_LibraryImpl::Construct(const Tizen::Base::String& dllPath, unsigned long option) +{ + result r = E_SUCCESS; + char* pLibPath = null; + int flag = -1; + + SysTryReturnResult(NID_BASE_RT, __pHandle == null, E_INVALID_STATE, + "Library has already has been loaded."); + + SysTryReturnResult(NID_BASE_RT, !dllPath.IsEmpty(), E_INVALID_ARG, "Specified path is null string."); + + if (option & _LIBRARY_LOAD_OPTION_LAZY) + { + flag = RTLD_LAZY; + } + + if (option & _LIBRARY_LOAD_OPTION_NOW) + { + SysTryReturnResult(NID_BASE_RT, flag != RTLD_LAZY, E_INVALID_ARG, + "_LIBRARY_LOAD_OPTION_LAZY and _LIBRARY_LOAD_OPTION_NOW must be included exclusively."); + + flag = RTLD_NOW; + } + + SysTryReturnResult(NID_BASE_RT, flag != -1, E_INVALID_ARG, + "One of _LIBRARY_LOAD_OPTION_LAZY or _LIBRARY_LOAD_OPTION_NOW must be included."); + + if (option & _LIBRARY_LOAD_OPTION_GLOBAL) + { + flag |= RTLD_GLOBAL; + } + + if (option & _LIBRARY_LOAD_OPTION_LOCAL) + { + SysTryReturnResult(NID_BASE_RT, (option & _LIBRARY_LOAD_OPTION_GLOBAL) == 0, E_INVALID_ARG, + "_LIBRARY_LOAD_OPTION_LAZY and _LIBRARY_LOAD_OPTION_NOW must be included exclusively."); + + flag |= RTLD_LOCAL; + } + + if (option & _LIBRARY_LOAD_OPTION_NODELETE) + { + flag |= RTLD_NODELETE; + } + + pLibPath = _StringConverter::CopyToCharArrayN(dllPath); + SysTryReturnResult(NID_BASE_RT, pLibPath != null, E_OUT_OF_MEMORY, "Not enough memroy."); + + __pHandle = dlopen(pLibPath, flag); + SysTryCatch(NID_BASE_RT, __pHandle != null, r = E_LIBRARY_NOT_FOUND, E_LIBRARY_NOT_FOUND, + "[E_LIBRARY_NOT_FOUND] Failed to load the library with reason: %s", + dlerror()); + + delete[] pLibPath; + + return E_SUCCESS; + +CATCH: + delete[] pLibPath; + + return r; +} + +void* +_LibraryImpl::GetProcAddress(const Tizen::Base::String& symbol) +{ + result r = E_SUCCESS; + char* pSymName = null; + void* pSymAddr = null; + + SysTryReturn(NID_BASE_RT, __pHandle != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Library is not loaded."); + SysTryReturn(NID_BASE_RT, !symbol.IsEmpty(), null, E_INVALID_ARG, + "[E_INVALID_ARG] Specified path is null."); + + pSymName = _StringConverter::CopyToCharArrayN(symbol); + SysTryCatch(NID_BASE_RT, pSymName != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + pSymAddr = dlsym(__pHandle, pSymName); + SysTryCatch(NID_BASE_RT, pSymAddr != null, , E_SYMBOL_NOT_FOUND, + "[E_SYMBOL_NOT_FOUND] Failed to get a symbol address with reason : %s", + dlerror()); + + delete[] pSymName; + + return pSymAddr; + +CATCH: + SetLastResult(r); + + delete[] pSymName; + + return null; +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRt_ListenerInfo.h b/src/base/runtime/FBaseRt_ListenerInfo.h new file mode 100644 index 0000000..0d9a9b0 --- /dev/null +++ b/src/base/runtime/FBaseRt_ListenerInfo.h @@ -0,0 +1,52 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_ListenerInfo.h + * @brief This is the header file of _ListenerInfo. + */ + +#ifndef _FBASE_RT_INTERNAL_LISTENER_INFO_H_ +#define _FBASE_RT_INTERNAL_LISTENER_INFO_H_ + + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _ListenerInfo + : public Tizen::Base::Object +{ +public: + _ListenerInfo(void) + : pListener(null) + , pDispatcher(null) + { + } + + virtual ~_ListenerInfo(void) + { + } + +public: + const IEventListener* pListener; + const _EventDispatcher* pDispatcher; +}; // _ListenerInfo + + +} } } // Tizen::Runtime + +#endif // _FBASE_RT_INTERNAL_LISTENER_INFO_H_ diff --git a/src/base/runtime/FBaseRt_MainLoop.cpp b/src/base/runtime/FBaseRt_MainLoop.cpp new file mode 100644 index 0000000..4133af8 --- /dev/null +++ b/src/base/runtime/FBaseRt_MainLoop.cpp @@ -0,0 +1,256 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_MainLoop.cpp + * @brief This is the implementation file for the _MainLoop class. + * + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include "FBaseRt_MainLoop.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Base { namespace Runtime +{ +__thread _MainLoop* pCurrentMainLoop = null; + +bool +_MainLoop::_Message::operator==(const _Message& rhs) const +{ + if (requestId == rhs.requestId && pArgs == rhs.pArgs) + { + return true; + } + + return false; +} + +bool +_MainLoop::_Message::operator!=(const _Message& rhs) const +{ + if (requestId != rhs.requestId || pArgs != rhs.pArgs) + { + return true; + } + + return false; +} + +_MainLoop::_MainLoop(void) + : __pGmainLoop(null) + , __pGmainContext(null) + , __pChannel(null) + , __pSource(null) + , __pMutex(null) + , __pListener(null) + , __pActive(null) + , __pReady(null) +{ + +} + +_MainLoop::~_MainLoop(void) +{ + + delete __pMutex; + __pMutex = null; + + if (__pSource) + { + g_source_unref(__pSource); + __pSource = null; + } + + if (__pChannel) + { + g_io_channel_unref(__pChannel); + __pChannel = null; + } +} + +result +_MainLoop::Construct(GMainLoop* pGmainLoop, GMainContext* pGmainContext) +{ + result r = E_SUCCESS; + GError* pGError = null; + + __pGmainContext = pGmainContext; + g_main_context_ref(__pGmainContext); + + int eventFd = eventfd(0, 0); + SysTryCatch(NID_BASE_RT, -1 != eventFd, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open eventfd."); + + + __pChannel = g_io_channel_unix_new(eventFd); + SysTryCatch(NID_BASE_RT, __pChannel != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a channel for eventfd."); + + g_io_channel_set_encoding(__pChannel, null, &pGError); + g_io_channel_set_flags(__pChannel, G_IO_FLAG_NONBLOCK, &pGError); + + __pSource = g_io_create_watch(__pChannel, G_IO_IN); + SysTryCatch(NID_BASE_RT, __pSource != null, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to create a gsource for a channel."); + + g_source_set_callback(__pSource, (GSourceFunc)OnMessageArrived, this, null); + g_source_attach(__pSource, __pGmainContext); + + __pMutex = new (std::nothrow) Mutex(); + SysTryCatch(NID_BASE_RT, __pMutex != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + r = __pMutex->Create(); + SysTryCatch(NID_BASE_RT, !IsFailed(r), , r, "[%s] Failed to create mutex.", GetErrorMessage(r)); + + pCurrentMainLoop = this; + + __pActive = &__messages1; + __pReady = &__messages2; + + + return E_SUCCESS; + +CATCH: + + delete __pMutex; + __pMutex = null; + + if (__pSource) + { + g_source_unref(__pSource); + __pSource = null; + } + + if (__pChannel) + { + g_io_channel_unref(__pChannel); + __pChannel = null; + } + + return r; +} + +result +_MainLoop::SendUserEvent(RequestId requestId, const IList* pArgs) +{ + SysTryReturnResult(NID_BASE_RT, __pGmainContext != null, E_INVALID_STATE, "Main loop is not constructed."); + + _Message message; + + message.requestId = requestId; + message.pArgs = pArgs; + + __pMutex->Acquire(); + + __pActive->Add(message); + + __pMutex->Release(); + + gsize writtenSize = 0; + uint64_t count = 1; + + g_io_channel_write(__pChannel, (const gchar*) &count, sizeof(count), &writtenSize); + + return E_SUCCESS; +} + +void +_MainLoop::SetMainLoopEventListener(_IMainLoopEventListener* pListener) +{ + __pListener = pListener; +} + +gboolean +_MainLoop::OnMessageArrived(GIOChannel* pChannel, GIOCondition condition, gpointer data) +{ + _MainLoop* pMainLoop = (_MainLoop*) data; + + uint64_t count = 0; + gsize readSize = 0; + + ArrayListT<_Message>* pMessages = null; + + pMainLoop->__pMutex->Acquire(); + + pMessages = pMainLoop->__pActive; + pMainLoop->__pActive = pMainLoop->__pReady; + pMainLoop->__pReady = pMessages; + + pMainLoop->__pMutex->Release(); + + if (condition & G_IO_IN) + { + g_io_channel_read(pChannel, (gchar*) &count, sizeof(count), &readSize); + + if (readSize == 0) + { + return TRUE; + } + + if (pMainLoop->__pListener) + { + _Message message; + IEnumeratorT<_Message>* pEnum = pMessages->GetEnumeratorN();; + SysTryReturn(NID_BASE_RT, pEnum, TRUE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + pEnum->GetCurrent(message); + } + } + + pMessages->RemoveAll(); + } + + count = pMainLoop->__pActive->GetCount(); + if (count > 0) + { + gsize writtenSize = 0; + g_io_channel_write(pChannel, (const gchar*) &count, sizeof(count), &writtenSize); + } + + return TRUE; +} + +_MainLoop* +_MainLoop::GetCurrentMainLoop(void) +{ + SysTryReturn(NID_BASE_RT, pCurrentMainLoop != null, null, E_INVALID_STATE, "[E_INVALID_STATE] Main loop is exist."); + + return pCurrentMainLoop; +} + +GMainContext* +_MainLoop::GetGmainContext(void) const +{ + SysTryReturn(NID_BASE_RT, __pGmainContext != null, null, E_INVALID_STATE, "[E_INVALID_STATE] Main loop is not constructed.."); + + return __pGmainContext; +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_MainThreadImpl.cpp b/src/base/runtime/FBaseRt_MainThreadImpl.cpp new file mode 100644 index 0000000..98c46c6 --- /dev/null +++ b/src/base/runtime/FBaseRt_MainThreadImpl.cpp @@ -0,0 +1,109 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_MainThreadImpl.cpp + * @brief This is the implementation file for the _MainThreadImpl class. + * + */ + +#include +#include +#include + +#include +#include "FBaseRt_EventDispatcher.h" +#include "FBase_NativeError.h" +#include "FBaseRt_MainThreadImpl.h" +#include "FBaseRt_EventManager.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +_MainThreadImpl::_MainThreadImpl(Thread& thread, const String& name) + : _ThreadImpl(thread, name, Thread::DEFAULT_STACK_SIZE, THREAD_PRIORITY_HIGH, THREAD_TYPE_MAIN) + , __pEventDispatcher(null) + , __pEventManager(null) +{ + +} + +_MainThreadImpl::~_MainThreadImpl(void) +{ + delete __pEventDispatcher; + delete __pEventManager; +} + +result +_MainThreadImpl::Start(void) +{ + Run(); + + return E_SUCCESS; +} + +Object* +_MainThreadImpl::Run(void) +{ + SetNativeThread(pthread_self()); + + Initialize(); + + return null; +} + +result +_MainThreadImpl::Initialize(void) +{ + result r = E_SUCCESS; + _EventManager* pEventManager = null; + _EventDispatcher* pEventDispatcher = null; + + GMainContext* pGMainContext = g_main_context_default(); + SysTryReturnResult(NID_BASE_RT, pGMainContext != null, E_INVALID_STATE, "Failed to get GMainContext."); + + pEventManager = new (std::nothrow) _EventManager; + SysTryReturnResult(NID_BASE_RT, pEventManager != null, E_OUT_OF_MEMORY, "Not enough memory."); + + r = pEventManager->Construct(pGMainContext); + SysTryCatch(NID_BASE_RT, !IsFailed(r), , r, "[%s] Failed to initialize event manager.", GetErrorMessage(r)); + + _ThreadImpl::SetEventManager(pEventManager); + __pEventManager = pEventManager; + + pEventDispatcher = new (std::nothrow) _EventDispatcher; + SysTryCatch(NID_BASE_RT, pEventDispatcher!= null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + r = pEventDispatcher->Construct(pGMainContext); + SysTryCatch(NID_BASE_RT, !IsFailed(r), , r, "[%s] Propagating.", GetErrorMessage(r)); + + _ThreadImpl::Initialize(); + + __pEventDispatcher = pEventDispatcher; + + return E_SUCCESS; + +CATCH: + delete pEventDispatcher; + + delete pEventManager; + + return r; +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_MainThreadImpl.h b/src/base/runtime/FBaseRt_MainThreadImpl.h new file mode 100644 index 0000000..bd02743 --- /dev/null +++ b/src/base/runtime/FBaseRt_MainThreadImpl.h @@ -0,0 +1,61 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_MainThreadImpl.h + * @brief This is the header file for the _MainThreadImpl class. + * + * This file contains the declarations of _MainThreadImpl. + */ + +#ifndef _FRT_THREAD_INTERNAL_MAIN_THREAD_IMPL_H_ +#define _FRT_THREAD_INTERNAL_MAIN_THREAD_IMPL_H_ + +#include "FBaseRt_ThreadImpl.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _EventDispatcher; + +class _MainThreadImpl + : public _ThreadImpl +{ +public: + _MainThreadImpl(Thread& thread, const String& name); + + virtual ~_MainThreadImpl(void); + + virtual result Start(void); + + virtual result Initialize(void); + + virtual Object* Run(void); + +public: + _MainThreadImpl(const _MainThreadImpl& value); + _MainThreadImpl& operator =(const _MainThreadImpl& value); + +private: + _EventDispatcher* __pEventDispatcher; + _EventManager* __pEventManager; +}; + + +} } } // Tizen::Base::Runtime + +#endif // _FRT_THREAD_INTERNAL_MAIN_THREAD_H_ diff --git a/src/base/runtime/FBaseRt_MonitorImpl.cpp b/src/base/runtime/FBaseRt_MonitorImpl.cpp new file mode 100644 index 0000000..a941739 --- /dev/null +++ b/src/base/runtime/FBaseRt_MonitorImpl.cpp @@ -0,0 +1,116 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_MonitorImpl.cpp + * @brief This is the implementation file for the _MonitorImpl class. + * + */ + +#include +#include "FBaseRt_MonitorImpl.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +_MonitorImpl::_MonitorImpl(void) + : __initialized(false) +{ + +} + +_MonitorImpl::~_MonitorImpl(void) +{ + if (__initialized) + { + pthread_cond_destroy(&__cond); + pthread_mutex_destroy(&__lock); + } +} + +result +_MonitorImpl::Construct(void) +{ + int ret = 0; + + ret = pthread_mutex_init(&__lock, null); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "[E_SYSTEM] System error has occurred."); + + ret = pthread_cond_init(&__cond, null); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "[E_SYSTEM] System error has occurred."); + + __initialized = true; + + return E_SUCCESS; +} + +result +_MonitorImpl::Enter(void) +{ + int ret = 0; + + ret = pthread_mutex_lock(&__lock); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "[E_SYSTEM] System error has occurred."); + + return E_SUCCESS; +} + +result +_MonitorImpl::Exit(void) +{ + int ret = 0; + + ret = pthread_mutex_unlock(&__lock); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "[E_SYSTEM] System error has occurred."); + + return E_SUCCESS; +} + +result +_MonitorImpl::Wait(void) +{ + int ret = 0; + + ret = pthread_cond_wait(&__cond, &__lock); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "[E_SYSTEM] System error has occurred."); + + return E_SUCCESS; +} + +result +_MonitorImpl::Notify(void) +{ + int ret = 0; + + ret = pthread_cond_signal(&__cond); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "[E_SYSTEM] System error has occured."); + + return E_SUCCESS; +} + +result +_MonitorImpl::NotifyAll(void) +{ + int ret = 0; + + ret = pthread_cond_broadcast(&__cond); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "[E_SYSTEM] System error has occurred."); + + return E_SUCCESS; +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRt_MonitorImpl.h b/src/base/runtime/FBaseRt_MonitorImpl.h new file mode 100644 index 0000000..4364548 --- /dev/null +++ b/src/base/runtime/FBaseRt_MonitorImpl.h @@ -0,0 +1,149 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_MonitorImpl.h + * @brief This is the header file for the %_Monitor class. + * + * This file contains the declarations of the %_Monitor class. + */ + +#ifndef _FBASE_RT_INTERNAL_MONITOR_IMPL_H_ +#define _FBASE_RT_INTERNAL_MONITOR_IMPL_H_ + +#include + +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** + * @class _MonitorImpl + * @brief This is one of the synchronization mechanisms. It not only provides acquire/release semantics + * (by Enter/Exit), but also wait/notify semantics (by Wait/Notify/NotifyAll). + * @since 2.0 + * + */ + +class _MonitorImpl + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * @remarks After creating an instance of this class, you must explicitly call one of the + * Construct() methods to initialize the instance. + */ + _MonitorImpl(void); + + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + ~_MonitorImpl(void); + + + /** + * Creates the monitor instance. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM An unknown operating system error occurred. + */ + result Construct(void); + +public: + /** + * Acquires a lock for a monitor. @n + * Semantically, this method declares the beginning of the critical region for a monitor. This region is + * ended with the Exit() method. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. @n + * It was successful in acquiring the lock. + * @see Exit() + */ + result Enter(void); + + + /** + * Releases a lock for a monitor. @n + * Semantically, it declares the ending of the critical region for the monitor which begins by + * the Enter() method. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. @n + * It was successful in releasing the lock. + * @exception E_INVALID_STATE The current thread has not entered the monitor. + * @see Enter() + */ + result Exit(void); + + /** + * Releases the lock for the monitor and waits for the other thread's notification. @n + * After receiving the notification, it tries to acquire the lock. @n + * Semantically, it waits until the other thread notifies it. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @see Notify(), NotifyAll() + */ + result Wait(void); + + /** + * Notifies one of the waiting threads. @n + * The selection of the notified thread is dependent on the underlying OS. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @see NotifyAll(), Wait() + */ + result Notify(void); + + + /** + * Notifies all waiting threads. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @see Notify(), Wait() + */ + result NotifyAll(void); + +private: + bool __initialized; + pthread_mutex_t __lock; + pthread_cond_t __cond; + +}; // _MonitorImpl + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_MONITOR_IMPL_H_ diff --git a/src/base/runtime/FBaseRt_MutexImpl.cpp b/src/base/runtime/FBaseRt_MutexImpl.cpp new file mode 100644 index 0000000..6e9b76b --- /dev/null +++ b/src/base/runtime/FBaseRt_MutexImpl.cpp @@ -0,0 +1,178 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_MutexImpl.cpp + * @brief This is the implementation file for the _MutexImpl class. + * + */ + +#include +#include +#include + +#include +#include "FBase_NativeError.h" +#include "FBaseRt_MutexImpl.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +_MutexImpl::_MutexImpl(void) + : __pMutex(null) +{ + +} + +_MutexImpl::~_MutexImpl(void) +{ + if (__pMutex != null) + { + pthread_mutex_destroy(__pMutex); + free(__pMutex); + __pMutex = null; + } +} + +result +_MutexImpl::Create(void) +{ + return Create(L""); +} + +result +_MutexImpl::Create(const Tizen::Base::String& name) +{ + result r = E_SUCCESS; + pthread_mutex_t* pMutex = null; + + int ret = -1; + pthread_mutexattr_t mutexAttr; + // create mutex + pMutex = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)); + SysTryReturnResult(NID_BASE_RT, pMutex != null, E_OUT_OF_MEMORY, + "Mutex memory allocation failed.") + + // set mutex attributes + pthread_mutexattr_init(&mutexAttr); + pthread_mutexattr_setpshared(&mutexAttr, PTHREAD_PROCESS_PRIVATE); + pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE_NP); + + // intialize the mutex + ret = pthread_mutex_init(pMutex, &mutexAttr); + SysTryCatch(NID_BASE_RT, ret == 0, r = E_SYSTEM, E_SYSTEM, + "[%s] Mutex intialization failed.", __ConvertNativeErrorToMessage(ret)); + + // destroy the attributes + pthread_mutexattr_destroy(&mutexAttr); + + __name = name; + __pMutex = pMutex; + + return E_SUCCESS; + +CATCH: + if (pMutex != null) + { + free(pMutex); + } + + return r; +} + +result +_MutexImpl::Acquire(void) +{ + return Acquire(INFINITE); +} + +result +_MutexImpl::Acquire(long timeout) +{ + SysTryReturnResult(NID_BASE_RT, __pMutex != null, E_INVALID_STATE, "Mutex is not initialized."); + + if (timeout == (long) INFINITE) + { + int rval = pthread_mutex_lock((pthread_mutex_t*) __pMutex); + SysTryReturnResult(NID_BASE_RT, rval == 0, E_SYSTEM, "[%s] Mutex acquire failed.", __ConvertNativeErrorToMessage(rval)); + } + else + { + struct timespec tm; + + int rval = clock_gettime(CLOCK_REALTIME, &tm); + SysTryReturn(NID_BASE_RT, rval == 0, E_SYSTEM, E_SYSTEM, + "[%s] Mutex acquire timeout setting failed.", __ConvertNativeErrorToMessage(errno)); + + tm.tv_sec += timeout / 1000; // convert ms to s + tm.tv_nsec += (timeout % 1000) * (1000 * 1000); // convert ms to ns + + rval = pthread_mutex_timedlock((pthread_mutex_t*) __pMutex, &tm); + if (rval == 0) + { + return E_SUCCESS; + } + + switch (rval) + { + case ETIMEDOUT: + SysLogException(NID_BASE_RT, E_SYSTEM, "[E_SYSTEM] Mutex acquire failed due to timedout"); + return E_SYSTEM; + default: + SysLogException(NID_BASE_RT, E_SYSTEM, "[E_SYSTEM] Mutex acquire failed : [%s].", __ConvertNativeErrorToMessage(rval)); + return E_SYSTEM; + } + } + + return E_SUCCESS; +} + +result +_MutexImpl::TryToAcquire(void) +{ + SysTryReturnResult(NID_BASE_RT, __pMutex != null, E_INVALID_STATE, "Mutex is not initialized."); + + int rval = pthread_mutex_trylock((pthread_mutex_t*) __pMutex); + if (rval == 0) + { + return E_SUCCESS; + } + + switch (rval) + { + case EBUSY: + SysLogException(NID_BASE_RT, E_OBJECT_LOCKED, "[E_OBJECT_LOCKED] Mutex acquire failed."); + return E_OBJECT_LOCKED; + default: + SysLogException(NID_BASE_RT, E_SYSTEM, "[E_SYSTEM] Mutex acquire failed : [%s].", __ConvertNativeErrorToMessage(rval)); + return E_SYSTEM; + } +} + +result +_MutexImpl::Release(void) +{ + SysTryReturnResult(NID_BASE_RT, __pMutex != null, E_INVALID_STATE, "Mutex is not initialized."); + + int rval = pthread_mutex_unlock((pthread_mutex_t*) __pMutex); + SysTryReturnResult(NID_BASE_RT, rval == 0, E_SYSTEM, + "Mutex release failed : [%s]", __ConvertNativeErrorToMessage(rval)); + + return E_SUCCESS; +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRt_MutexImpl.h b/src/base/runtime/FBaseRt_MutexImpl.h new file mode 100644 index 0000000..ab6ad8b --- /dev/null +++ b/src/base/runtime/FBaseRt_MutexImpl.h @@ -0,0 +1,169 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_MutexImpl.h + * @brief This is the implementation file for the _MutexImpl class. + * + */ + +#ifndef _FTHREAD_INTERNAL_MUTEX_IMPL_H_ +#define _FTHREAD_INTERNAL_MUTEX_IMPL_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ + +/** + * @class _MutexImpl + * @brief This class represents a mutex; one type of synchronization mechanism. + * + * It is a binary semaphore. Only one thread can acquire the Mutex. + * + * @code + * #include + * + * using namespace Tizen::Base; + * using namespace Tizen::Base::Runtime; + * + * result + * MyApp::AddRef(void) + * { + * __pMutex->Acqure(); + * + * __count++; + * + * __pMutex->Release(); + * } + * + * @endcode + * + * + * @see Semaphore, Thread + */ + +class _MutexImpl + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * @remarks After creating an instance of this class, you must explicitly call one of + * the Create() methods to initialize the instance. + */ + _MutexImpl(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_MutexImpl(void); + + /** + * Creates an unnamed Mutex. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM An unknown operating system error occurred. + */ + result Create(void); + + /** + * Creates a named Mutex. @n + * If there is already a Mutex with the specified name, this creates a Mutex which references that particular Mutex. + * + * @since 2.0 + * @return An error code + * @param[in] name The name of the Mutex + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM An unknown operating system error occurred. + */ + result Create(const Tizen::Base::String& name); + + /** + * Acquires the Mutex if it is not acquired. @n + * If the Mutex is already acquired by another thread, + * the current thread is blocked until the Mutex is released. + * + * @since 2.0 + * @return An error code + * @param[in] timeout The period during which the thread tries to acquire the mutex + * @exception E_SUCCESS The method was successful. + * @exception E_TIMEOUT The operation could not be completed within the specified time period. @n + * @exception E_SYSTEM An unknown operating system error occurred. @n + * Failed to acquire the Mutex because an OS failure occurred. + */ + result Acquire(long timeout); + + /** + * Releases the Mutex. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM An unknown operating system error occurred. @n + * Failed to acquire the Mutex because an OS failure occurred. + */ + result Release(void); + + /** + * Acquires the Mutex if it is not acquired. @n + * If the Mutex is already acquired by another thread, + * the current thread is blocked until the Mutex is released. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM An unknown operating system error occurred. @n + * Failed to acquire the Mutex because an OS failure occurred. + */ + result Acquire(void); + + /** + * Acquires the mutex if it is not acquired. @n + * If the mutex is already acquired by another thread, E_OBJECT_LOCKED is returned. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OBJECT_LOCKED The mutex is already locked. + * @exception E_INVALID_STATE The mutex has not been initialized as yet. + * @exception E_SYSTEM A system error has occurred. + */ + result TryToAcquire(void); + +private: + pthread_mutex_t* __pMutex; + Tizen::Base::String __name; + +}; + + +//} +} } } // Tizen::Runtime + + +#endif diff --git a/src/base/runtime/FBaseRt_Process.cpp b/src/base/runtime/FBaseRt_Process.cpp new file mode 100644 index 0000000..27beb0c --- /dev/null +++ b/src/base/runtime/FBaseRt_Process.cpp @@ -0,0 +1,37 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_Process.cpp + * @brief This is the implementation file for the _Process class. + * + */ + +#include + +#include "FBaseRt_Process.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +void +_Process::Exit(int exitCode) +{ + _exit(exitCode); +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_SemaphoreImpl.cpp b/src/base/runtime/FBaseRt_SemaphoreImpl.cpp new file mode 100644 index 0000000..ad12248 --- /dev/null +++ b/src/base/runtime/FBaseRt_SemaphoreImpl.cpp @@ -0,0 +1,187 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_SemaphoreImpl.cpp + * @brief This is the implementation file for the _SemaphoreImpl class. + * + */ + +#include +#include +#include +#include + +#include "FBase_NativeError.h" +#include +#include "FBaseRt_SemaphoreImpl.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +_SemaphoreImpl::_SemaphoreImpl(void) + : __pSemaphore(null) + , __name("") + , __count(0) +{ + +} + +_SemaphoreImpl::~_SemaphoreImpl(void) +{ + if (__pSemaphore != null) + { + sem_destroy(__pSemaphore); + free(__pSemaphore); + + __pSemaphore = null; + } +} + +result +_SemaphoreImpl::Create(int count) +{ + return Create(L"", count); +} + +result +_SemaphoreImpl::Create(const Tizen::Base::String& name, int count) +{ + int ret = 0; + result r = E_SUCCESS; + sem_t* pSemaphore = null; + + SysTryReturnResult(NID_BASE_RT, count >= 0, E_INVALID_ARG, + "The count(%d) MUST be greater than or equal to 0.", count); + + pSemaphore = (sem_t*) malloc(sizeof(sem_t)); + SysTryReturnResult(NID_BASE_RT, pSemaphore != null, E_OUT_OF_MEMORY, + "Semaphore memory allocation failed."); + + ret = sem_init(pSemaphore, 0, count); + SysTryCatch(NID_BASE_RT, ret == 0, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Semaphore intialization failed : [%s]", __ConvertNativeErrorToMessage(errno)); + + if (name.GetLength() > 0) + { + __name = name; + } + + __count = count; + __pSemaphore = pSemaphore; + + return E_SUCCESS; + +CATCH: + free(pSemaphore); + + return r; +} + +result +_SemaphoreImpl::Acquire(long timeout) +{ + SysTryReturnResult(NID_BASE_RT, __pSemaphore != null, E_INVALID_STATE, + "Sempahore is not initialized."); + + while (1) + { + int rval = 0; + + if (timeout == (long) INFINITE) + { + rval = sem_wait((sem_t*) __pSemaphore); + } + else + { + struct timespec tm; + + rval = clock_gettime(CLOCK_REALTIME, &tm); + SysTryReturn(NID_BASE_RT, rval == 0, E_SYSTEM, E_SYSTEM, + "[%s] Sempahore acquire timeout setting failed.", __ConvertNativeErrorToMessage(errno)); + + tm.tv_sec += timeout / 1000; // convert ms to s + tm.tv_nsec += (timeout % 1000) * (1000 * 1000); // convert ms to ns + + rval = sem_timedwait((sem_t*) __pSemaphore, &tm); + } + + if (rval == 0) + { + return E_SUCCESS; + } + + switch (errno) + { + case EINTR: + continue; // interrupted due to some signal, continue wait + + case ETIMEDOUT: + SysLogException(NID_BASE_RT, E_TIMEOUT, "[E_TIMEOUT] Semaphore acquire timedout"); + return E_TIMEOUT; + + default: + SysLogException(NID_BASE_RT, E_SYSTEM, "[E_SYSTEM] Semaphore acquire failed due to system error."); + return E_SYSTEM; + } + } +} + +result +_SemaphoreImpl::TryToAcquire(void) +{ + int rval = 0; + + while (true) + { + rval = sem_trywait((sem_t*) __pSemaphore); + + if (rval == 0) + { + return E_SUCCESS; + } + + switch (errno) + { + case EINTR: + continue; // interrupted due to some signal, continue wait + + case EAGAIN: + SysLogException(NID_BASE_RT, E_OBJECT_LOCKED, "[E_OBJECT_LOCKED] Semaphore is already locked"); + return E_OBJECT_LOCKED; + + default: + SysLogException(NID_BASE_RT, E_SYSTEM, "[E_SYSTEM] Semaphore acquire failed : [%s]", __ConvertNativeErrorToMessage(errno)); + return E_SYSTEM; + } + } + +} +result +_SemaphoreImpl::Release(void) +{ + SysTryReturnResult(NID_BASE_RT, __pSemaphore != null, E_INVALID_STATE, + "Sempahore is not initialized."); + + int rval = sem_post((sem_t*) __pSemaphore); + SysTryReturnResult(NID_BASE_RT, rval == 0, E_SYSTEM, + "Sempahore release failed : [%s]", __ConvertNativeErrorToMessage(errno)); + + return E_SUCCESS; +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRt_SemaphoreImpl.h b/src/base/runtime/FBaseRt_SemaphoreImpl.h new file mode 100644 index 0000000..c8d5aba --- /dev/null +++ b/src/base/runtime/FBaseRt_SemaphoreImpl.h @@ -0,0 +1,146 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_SemaphoreImpl.h + * @brief This is the header file for the _SemaphoreImpl class. + * + * This file contains the declarations of _SemaphoreImpl. + */ + +#ifndef _FTHREAD_INTERNAL_SEMAPHORE_IMPL_H_ +#define _FTHREAD_INTERNAl_SEMAPHORE_IMPL_H_ + +#include + +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ +/** + * @class _SemaphoreImpl + * @brief This class represents semaphore, a type of synchronization mechanisms. It can provide the acquiring semantics. @n + * @since 2.0 + * + * The semaphore allows that N threads can acquire the semaphore simultaneously. This can be used + * for accessing the shared resources which has a limitation of the access. + * For example, N printers are attached in one + * printer server, then the printer server can serve N printing tasks simultaneously. + */ +class _SemaphoreImpl +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + * @remarks After creating an instance of this class, you must explicitly call one of + * the Create() methods to initialize the instance. + */ + _SemaphoreImpl(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + ~_SemaphoreImpl(void); + + + /** + * Creates an unnamed Semaphore. + * + * @since 2.0 + * @param[in] count The number of threads which can acquire the semaphore simultaneously @n + * If the count is 1, then it is the same as a Mutex + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The specified @c count is less than 0. + * @exception E_SYSTEM An unknown operating system error occurred. + */ + result Create(int count = 1); + + + /** + * Creates a named Semaphore. @n + * If there is already a Semaphore with the specified name, this creates a Semaphore which references that particular Semaphore. + * + * @since 2.0 + * @return An error code + * @param[in] name The name of the Semaphore + * @param[in] count The number of threads which can acquire the Semaphore simultaneously + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The specified @c count is less than @c 0. + * @exception E_SYSTEM An unknown operating system error occurred. + */ + result Create(const Tizen::Base::String& name, int count = 1); + + /** + * Acquires the Semaphore if it is not acquired. @n + * If the Semaphore is already acquired, the current thread is blocked until the Semaphore is released. + * + * @since 2.0 + * @return An error code + * @param[in] timeout The period during which the thread tries to acquire the semaphore + * @exception E_SUCCESS The method was successful. + * @exception E_TIMEOUT The operation could not be completed within the specified time period. @n + * Failed to acquire because the given time has elapsed. + * @exception E_SYSTEM An unknown operating system error occurred. @n + * Failed to acquire because an OS failure occurred. + */ + result Acquire(long timeout = INFINITE); + + /** + * Tries to acquire the semaphore. @n + * If the semaphore is already acquired by another thread, E_OBJECT_LOCKED is returned. + * + * @since 2.0 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_OBJECT_LOCKED The semaphore is already locked. + * @exception E_INVALID_STATE The semaphore has not been initialized as yet. + * @exception E_SYSTEM A system error has occurred. + */ + result TryToAcquire(void); + + /** + * Releases the semaphore. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM An unknown operating system error occurred. @n + * Failed to acquire because an OS failure occurred. + */ + result Release(void); + + +private: + sem_t* __pSemaphore; + Tizen::Base::String __name; + int __count; +}; + + +//} +} } } // Tizen::Runtime + + +#endif diff --git a/src/base/runtime/FBaseRt_ThreadImpl.cpp b/src/base/runtime/FBaseRt_ThreadImpl.cpp new file mode 100644 index 0000000..0852e0f --- /dev/null +++ b/src/base/runtime/FBaseRt_ThreadImpl.cpp @@ -0,0 +1,294 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_ThreadImpl.cpp + * @brief This is the implementation file for the _ThreadImpl class. + * + */ + +#include +#include + +#include +#include +#include + +#include "FBase_NativeError.h" +#include +#include "FBaseRt_ThreadImpl.h" +#include "FBaseRt_EventManager.h" +#include "FBaseRt_ThreadManager.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +__thread Thread* pCurrentThread = null; + +_ThreadImpl* +_ThreadImpl::GetCurrentThreadImpl(void) +{ + if (pCurrentThread != null) + { + return pCurrentThread->__pThreadImpl; + } + + return null; +} + +void +_ThreadImpl::Exit(int exitCode) +{ + _ThreadImpl* pThreadImpl = GetCurrentThreadImpl(); + if (pThreadImpl != null) + { + pThreadImpl->__exitCode = exitCode; + } + + pthread_exit(null); +} + +result +_ThreadImpl::Sleep(long milliSeconds) +{ + if (milliSeconds > 0) + { + struct timespec tspec = { milliSeconds / 1000, (milliSeconds % 1000) * (1000 * 1000) }; + + while (nanosleep(&tspec, &tspec) == -1) + { + if (errno == EINTR) + { + continue; + } + else if (errno == EINVAL) + { + return E_INVALID_ARG;} + else + { + return E_SYSTEM; + } + } + + return E_SUCCESS; + } + else if (milliSeconds == 0) + { + return Yield(); + } + else + { + return E_INVALID_ARG; + } +} + +result +_ThreadImpl::Yield(void) +{ + int ret = pthread_yield(); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "Yield has failed due to a system error."); + + return E_SUCCESS; +} + +Thread* +_ThreadImpl::GetCurrentThread(void) +{ + static Thread dummy; + + if (pCurrentThread == null) + { + return &dummy; + } + + return pCurrentThread; +} + +_ThreadImpl::_ThreadImpl(Thread& thread, const String& name, long stackSize, ThreadPriority priority, ThreadType threadType) + : _pThread(&thread) + , __name(name) + , __stackSize(stackSize) + , __priority(priority) + , __threadType(threadType) + , __nativeThread(0) + , __exitCode(0x0) + , __pEventManager(null) +{ + +} + +_ThreadImpl::~_ThreadImpl(void) +{ + +} + +result +_ThreadImpl::Join(void) +{ + int ret = pthread_join(__nativeThread, null); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "Thread join operation failed"); + + return E_SUCCESS; +} + +result +_ThreadImpl::GetExitCode(int& exitCode) const +{ + exitCode = __exitCode; + + return E_SUCCESS; +} + +const Tizen::Base::String& +_ThreadImpl::GetName(void) const +{ + return __name; +} + +result +_ThreadImpl::Start(void) +{ + pthread_attr_t attr; + struct sched_param schedParam; + + int ret = pthread_attr_init(&attr); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_OUT_OF_MEMORY, "Not enough memory."); + + int maxPriority = sched_get_priority_max(SCHED_FIFO); + int minPriority = sched_get_priority_min(SCHED_FIFO); + + schedParam.sched_priority = (3 - (int) __priority) * ((maxPriority - minPriority + 1) / 3); + + ret = pthread_create(&__nativeThread, &attr, _ThreadImpl::ThreadProc, this); + SysTryReturnResult(NID_BASE_RT, ret == 0, E_SYSTEM, "Create a thread has failed due to system error."); + + pthread_attr_destroy(&attr); + + return E_SUCCESS; +} + +result +_ThreadImpl::Stop(void) +{ + return E_SUCCESS; +} + +Tizen::Base::Object* +_ThreadImpl::Run(void) +{ + return null; +} + +result +_ThreadImpl::Initialize(void) +{ + pCurrentThread = _pThread; + + return E_SUCCESS; +} + +result +_ThreadImpl::Finalize(void) +{ + pCurrentThread = null; + + return E_SUCCESS; +} + +result +_ThreadImpl::SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs) +{ + return E_INVALID_OPERATION; +} + +const Thread* +_ThreadImpl::GetThread(void) const +{ + return _pThread; +} + +void +_ThreadImpl::SetThread(Thread* pThread) +{ + _pThread = pThread; +} + +void +_ThreadImpl::SetNativeThread(pthread_t nativeThread) +{ + __nativeThread = nativeThread; +} + +const ThreadPriority +_ThreadImpl::GetPriority(void) const +{ + return __priority; +} + +ThreadType +_ThreadImpl::GetThreadType(void) const +{ + return __threadType; +} + +void* +_ThreadImpl::ThreadProc(void* params) +{ + _ThreadImpl* pSelf = (_ThreadImpl*) params; + if (pSelf == null) + { + return null; + } + + Thread* pThread = pSelf->_pThread; + if (pThread == null) + { + return null; + } + + result r = pSelf->Initialize(); + if (IsFailed(r)) + { + return null; + } + + if (pThread->OnStart()) + { + pSelf->Run(); + } + + pThread->OnStop(); + + pSelf->Finalize(); + + return null; +} + +void +_ThreadImpl::SetEventManager(_EventManager* pEventManager) +{ + __pEventManager = pEventManager; +} + +_EventManager* +_ThreadImpl::GetEventManager(void) +{ + return __pEventManager; +} + + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_ThreadImpl.h b/src/base/runtime/FBaseRt_ThreadImpl.h new file mode 100644 index 0000000..5242996 --- /dev/null +++ b/src/base/runtime/FBaseRt_ThreadImpl.h @@ -0,0 +1,107 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_ThreadImpl.h + * @brief This is the header file for the %_ThreadImpl class. + * + * This file contains the declarations of the %_ThreadImpl class. + */ + +#ifndef _FBASE_RT_INTERNAL_THREAD_IMPL_H_ +#define _FBASE_RT_INTERNAL_THREAD_IMPL_H_ + +#include + +#include +#include "FBaseRt_EventManager.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _OSP_EXPORT_ _ThreadImpl + : public Tizen::Base::Object + , public Tizen::Base::Runtime::IRunnable +{ +public: + _ThreadImpl(Thread& thread, const Tizen::Base::String& name, long stackSize + , ThreadPriority priority, ThreadType threadType); + + virtual ~_ThreadImpl(void); + + virtual result Start(void); + + virtual result Stop(void); + + virtual result SendUserEvent(RequestId requestId, const Tizen::Base::Collection::IList* pArgs); + + result Join(void); + + result GetExitCode(int& exitCode) const; + + const Tizen::Base::String& GetName(void) const; + + ThreadType GetThreadType(void) const; + + void SetEventManager(_EventManager* pEventManager); + + _EventManager* GetEventManager(void); + + virtual Tizen::Base::Object* Run(void); + + static void Exit(int exitCode); + + static result Sleep(long milliSeconds); + + static result Yield(void); + + static Thread* GetCurrentThread(void); + + static _ThreadImpl* GetCurrentThreadImpl(void); + +protected: + virtual result Initialize(void); + + virtual result Finalize(void); + + const Thread* GetThread(void) const; + + const ThreadPriority GetPriority(void) const; + + void SetThread(Thread* pThread); + + void SetNativeThread(pthread_t nativeThread); + +private: + static void* ThreadProc(void* pParam); + +protected: + Thread* _pThread; + +private: + String __name; + long __stackSize; + ThreadPriority __priority; + ThreadType __threadType; + pthread_t __nativeThread; + int __exitCode; + _EventManager* __pEventManager; +}; // _ThreadImpl + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_THREAD_IMPL_H_ diff --git a/src/base/runtime/FBaseRt_ThreadManager.cpp b/src/base/runtime/FBaseRt_ThreadManager.cpp new file mode 100644 index 0000000..174b305 --- /dev/null +++ b/src/base/runtime/FBaseRt_ThreadManager.cpp @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_ThreadManager.cpp + * @brief This is the implementation file for the _ThreadManager class. + * + */ + +#include +#include +#include + +#include + +#include +#include "FBaseRt_ThreadManager.h" +#include "FBaseRt_ThreadImpl.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +Thread* _ThreadManager::__pMainThread = null; + +result +_ThreadManager::Initialize(void) +{ + __pMainThread = new (std::nothrow) Thread; + SysTryLog(NID_BASE_RT, __pMainThread != null, "[E_OUT_OF_MEMORY] Unable to create Thread object"); + + result r = __pMainThread->Construct(L"MainThread", THREAD_TYPE_MAIN); + SysTryLog(NID_BASE_RT, !IsFailed(r), "[%s] Propagating.", GetErrorMessage(r)); + + __pMainThread->Start(); + + return E_SUCCESS; +} + +result +_ThreadManager::Finalize(void) +{ + delete __pMainThread; + __pMainThread = null; + return E_SUCCESS; +} + +_ThreadManager::_ThreadManager(void) +{ +} + +_ThreadManager::~_ThreadManager(void) +{ +} + +} } } //Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_ThreadManager.h b/src/base/runtime/FBaseRt_ThreadManager.h new file mode 100644 index 0000000..781f714 --- /dev/null +++ b/src/base/runtime/FBaseRt_ThreadManager.h @@ -0,0 +1,58 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_ThreadManager.h + * @brief This is the header file for the %_ThreadManager class. + * + * This file contains the declarations of the %_ThreadManager class. + */ + +#ifndef _FBASE_RT_INTERNAL_THREAD_MANAGER_H_ +#define _FBASE_RT_INTERNAL_THREAD_MANAGER_H_ + +#include +#include + +#include + +namespace Tizen { namespace Base { namespace Runtime +{ +class Thread; +class _ThreadImpl; +class _EventDispatcher; + +class _ThreadManager +{ +public: + _ThreadManager(void); + + ~_ThreadManager(void); + + static result Initialize(void); + + static result Finalize(void); + +private: + static Thread* __pMainThread; + + friend class _ThreadImpl; +}; // _ThreadManager + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_THREAD_MANAGER_H_ diff --git a/src/base/runtime/FBaseRt_TimerImpl.cpp b/src/base/runtime/FBaseRt_TimerImpl.cpp new file mode 100644 index 0000000..5552a37 --- /dev/null +++ b/src/base/runtime/FBaseRt_TimerImpl.cpp @@ -0,0 +1,254 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_TimerImpl.cpp + * @brief This is the implementation file for the _TimerImpl class. + * + */ + +#include +#include +#include +#include +#include + +#include + +#include "FApp_AppInfo.h" +#include +#include "FBaseRt_EventDispatcher.h" +#include "FBaseRt_TimerImpl.h" + + +namespace Tizen { namespace Base { namespace Runtime +{ + +_TimerImpl::_TimerImpl(void) + : __pTimer(null) + , __timerFd(-1) + , __pTimerIo(null) + , __pTimerSource(null) + , __pTimerEventListener(null) + , __status(TIMER_STATUS_NOT_ACTIVATED) +{ + +} + +_TimerImpl::~_TimerImpl(void) +{ + if (__pTimerSource != null) + { + g_source_destroy(__pTimerSource); + g_source_unref(__pTimerSource); + } + + if (__pTimerIo != null) + { + g_io_channel_unref(__pTimerIo); + } +} + +result +_TimerImpl::Construct(const Timer& timer, ITimerEventListener& listener) +{ + result r = E_SUCCESS; + int timerFd = -1; + GIOChannel* pGIOChannel = null; + GSource* pGSource = null; + _EventDispatcher* pEventDispatcher = null; + GMainContext* pGMainContext = null; + + pEventDispatcher = _EventDispatcher::GetCurrentEventDispatcher(); + SysTryReturnResult(NID_BASE_RT, pEventDispatcher != null, E_SYSTEM, + "Called by a worker thread."); + + pGMainContext = pEventDispatcher->GetGMainContext(); + SysTryReturnResult(NID_BASE_RT, pGMainContext != null, E_SYSTEM, + "Can't get GMainContext."); + + timerFd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + SysTryReturnResult(NID_BASE_RT, timerFd != -1, E_SYSTEM, "failed to create a timerfd."); + + pGIOChannel = g_io_channel_unix_new(timerFd); + SysTryCatch(NID_BASE_RT, pGIOChannel != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a GIOChannel for timerfd."); + + g_io_channel_set_close_on_unref(pGIOChannel, TRUE); + __timerFd = timerFd; + timerFd = -1; + + pGSource = g_io_create_watch(pGIOChannel, G_IO_IN); + SysTryCatch(NID_BASE_RT, pGSource != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a GSource for timerfd."); + + g_source_set_callback(pGSource, (GSourceFunc) _TimerImpl::OnTimerExpired, this, null); + g_source_attach(pGSource, pGMainContext); + + __pTimerIo = pGIOChannel; + __pTimerSource = pGSource; + + __pTimer = const_cast (&timer); + __pTimerEventListener = &listener; + + return E_SUCCESS; + +CATCH: + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (timerFd != -1) + { + close(timerFd); + } + + return r; +} + +result +_TimerImpl::Construct(const Timer& timer, ITimerEventListener& listener, bool awake) +{ + return Construct(timer, listener); +} + +gboolean +_TimerImpl::OnTimerExpired(GIOChannel* pGIOChannel, GIOCondition condition, gpointer data) +{ + uint64_t exp = 0; + _TimerImpl* pTimerImpl = (_TimerImpl*) data; + + if (condition & G_IO_IN) + { + ssize_t ret = read(pTimerImpl->__timerFd, &exp, sizeof(uint64_t)); + SysTryLog(NID_BASE_RT, ret >= 0, "Timer read failure : %s.", strerror(errno)); + + if (pTimerImpl->__status != TIMER_STATUS_ACTIVATED_REPEATABLE) + { + pTimerImpl->__status = TIMER_STATUS_EXPIRED; + } + else + { + pTimerImpl->__status = TIMER_STATUS_ACTIVATED_REPEATABLE; + } + pTimerImpl->__pTimerEventListener->OnTimerExpired(*pTimerImpl->__pTimer); + } + + return TRUE; +} + +result +_TimerImpl::Start(int timeout) +{ + int ret = -1; + struct timespec now; + struct itimerspec newTimeout; + + SysTryReturnResult(NID_BASE_RT, (__status != TIMER_STATUS_ACTIVATED) && (__status != TIMER_STATUS_ACTIVATED_REPEATABLE), E_INVALID_STATE, "Timer is already started."); + SysTryReturnResult(NID_BASE_RT, __pTimerEventListener != null, E_INVALID_STATE, "not initialized."); + + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + SysTryReturnResult(NID_BASE_RT, timeout > 0, E_INVALID_ARG, "timeout should be greater than 0."); + } + else + { + SysTryReturnResult(NID_BASE_RT, (timeout > 0) || (timeout == 0), E_INVALID_ARG, "timeout should not be less than 0."); + } + + clock_gettime(CLOCK_MONOTONIC, &now); + + if (timeout != 0) + { + newTimeout.it_value.tv_sec = now.tv_sec + timeout / 1000; + newTimeout.it_value.tv_nsec = now.tv_nsec + (timeout % 1000) * 1000000; + } + else + { + newTimeout.it_value.tv_sec = now.tv_sec; + newTimeout.it_value.tv_nsec = now.tv_nsec + 1; + } + + if (newTimeout.it_value.tv_nsec >= 1000000000) + { + newTimeout.it_value.tv_sec += 1; + newTimeout.it_value.tv_nsec -= 1000000000; + } + + newTimeout.it_interval.tv_sec = 0; + newTimeout.it_interval.tv_nsec = 0; + + ret = timerfd_settime(__timerFd, TFD_TIMER_ABSTIME, &newTimeout, null); + SysTryReturnResult(NID_BASE_RT, ret != -1, E_SYSTEM, "Failed to set timeout."); + + __status = TIMER_STATUS_ACTIVATED; + + return E_SUCCESS; +} + +result +_TimerImpl::StartAsRepeatable(int interval) +{ + int ret = -1; + struct timespec now; + struct itimerspec newTimeout; + + SysTryReturnResult(NID_BASE_RT, (__status != TIMER_STATUS_ACTIVATED) && (__status != TIMER_STATUS_ACTIVATED_REPEATABLE), E_INVALID_STATE, "Timer is already started."); + SysTryReturnResult(NID_BASE_RT, interval > 0, E_INVALID_ARG, "interval should greater than 0."); + SysTryReturnResult(NID_BASE_RT, __pTimerEventListener != null, E_INVALID_STATE, "not initialized."); + + clock_gettime(CLOCK_MONOTONIC, &now); + + newTimeout.it_value.tv_sec = now.tv_sec + interval / 1000; + newTimeout.it_value.tv_nsec = now.tv_nsec + (interval % 1000) * 1000000; + if (newTimeout.it_value.tv_nsec >= 1000000000) + { + newTimeout.it_value.tv_sec += 1; + newTimeout.it_value.tv_nsec -= 1000000000; + } + + newTimeout.it_interval.tv_sec = interval / 1000; + newTimeout.it_interval.tv_nsec = (interval % 1000)*1000000; + + ret = timerfd_settime(__timerFd, TFD_TIMER_ABSTIME, &newTimeout, null); + SysTryReturnResult(NID_BASE_RT, ret != -1, E_SYSTEM, "Failed to set interval."); + + __status = TIMER_STATUS_ACTIVATED_REPEATABLE; + + return E_SUCCESS; +} + +result +_TimerImpl::Cancel(void) +{ + int ret = -1; + struct itimerspec newTimeout; + SysTryReturnResult(NID_BASE_RT, (__status == TIMER_STATUS_ACTIVATED) || (__status == TIMER_STATUS_ACTIVATED_REPEATABLE), E_INVALID_STATE, "Timer is not started."); + + newTimeout.it_value.tv_sec = 0; + newTimeout.it_value.tv_nsec = 0; + newTimeout.it_interval.tv_sec = 0; + newTimeout.it_interval.tv_nsec = 0; + + ret = timerfd_settime(__timerFd, TFD_TIMER_ABSTIME, &newTimeout, null); + SysTryReturnResult(NID_BASE_RT, ret != -1, E_SYSTEM, "Failed to unset timeout."); + + __status = TIMER_STATUS_CANCELED; + + return E_SUCCESS; +} + +} } } // Tizen::Runtime diff --git a/src/base/runtime/FBaseRt_TimerImpl.h b/src/base/runtime/FBaseRt_TimerImpl.h new file mode 100644 index 0000000..8737f8a --- /dev/null +++ b/src/base/runtime/FBaseRt_TimerImpl.h @@ -0,0 +1,150 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_TimerImpl.h + * @brief This is the header file for the _TimerImpl class. + * + * This file contains the declarations of _TimerImpl. + */ + + +#ifndef _FBASE_RT_INTERNAL_TIMER_IMPL_H_ +#define _FBASE_RT_INTERNAL_TIMER_IMPL_H_ + +#include + +#include +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +class Timer; +class ITimerEventListener; + +class _TimerImpl + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * + * @since 2.0 + */ + _TimerImpl(void); + + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_TimerImpl(void); + + /** + * Initializes the time instance. + * + * @since 2.0 + * @return An error code + * @param[in] listener The event listener + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + */ + result Construct(const Timer& timer, ITimerEventListener& listener); + + /** + * Initializes the time instance. + * + * since 2.1 + * + * @return An error code + * @param[in] listener The event listener + * @param[in] awake Set to @c true, if the timer continues to run even if the system enters sleep mode + * @c false, if the timer stops running when the system enters sleep mode. + * + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * + * @exception E_PRIVILEGE_DENIED The application does not have the privilege to call this method. + * + * @endif + */ + result Construct(const Timer& timer, ITimerEventListener& listener, bool awake); + + /** + * Starts the timer. + * + * @since 2.0 + * @return An error code + * @param[in] timeout A timeout interval in milliseconds + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_INVALID_STATE The state of the timer is not a valid state. @n + The timer might be in the TIMER_STATUS_ACTIVATED state. + * @remark Once it has been started, it cannot be started again until it expires. @n + * You must cancel it if you want to re-start the timer. + * @see Cancel() + */ + result Start(int timeout); + + + /** + * Cancels the timer. + * + * @since 2.0 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_STATE The state of the timer is not a valid state. @n + The timer might be in the TIMER_STATUS_NOT_ACTIVATED state. + * @remark The timer cannot be canceled if it is not started. + */ + result Cancel(void); + + /** + * Starts the timer. The timer is expired repeatedly until it is canceled. + * + * @since 2.0 + * @return An error code + * @param[in] interval A interval in milliseconds + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM A system error has occurred. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_INVALID_STATE The state of the timer is not a valid state. @n + * The timer might be in the TIMER_STATUS_ACTIVATED state. + * @see Cancel() + */ + result StartAsRepeatable(int interval); + +private: + static gboolean OnTimerExpired(GIOChannel* pGIOChannel, GIOCondition condition, gpointer data); + +private: + Timer* __pTimer; + int __timerFd; + GIOChannel* __pTimerIo; + GSource* __pTimerSource; + ITimerEventListener* __pTimerEventListener; + TimerStatus __status; +}; + + +} } } // Tizen::Base::Runtime + + +#endif // _FBASE_RT_INTERNAL_TIMER_IMPL_H_ diff --git a/src/base/runtime/FBaseRt_WaitingLoopImpl.cpp b/src/base/runtime/FBaseRt_WaitingLoopImpl.cpp new file mode 100755 index 0000000..7ec514e --- /dev/null +++ b/src/base/runtime/FBaseRt_WaitingLoopImpl.cpp @@ -0,0 +1,332 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_WaitingLoopImpl.cpp + * @brief This is the implementation for the %_WaitingLoopImpl class. + * + */ + +#include +#include +#include +#include +#include "FBaseRt_ThreadImpl.h" +#include "FBaseRt_EventDispatcher.h" +#include "FBaseRt_WaitingLoopImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Base { namespace Runtime +{ + + +static int __sleepTime = 10; +static int __waitingCount = 10; +static int __waitingRepeatableTime = 100; + +_WaitingLoopImpl::_WaitingLoopImpl(void) + : __pTimer(null) + , __timeout(false) + , __notifyWait(true) + , __threadType(THREAD_TYPE_MAIN) + , __pGmainContext(null) + , __waitType(WAIT_DEFAULT) + , __waitStatus(WAIT_OFF) + , __pWaitingLoopCondition(null) + , __timerCalledCount(0) + , __MaxTimeout(10000) +{ + +} + +_WaitingLoopImpl::~_WaitingLoopImpl(void) +{ + __pTimer->Cancel(); + delete __pTimer; +} + +result +_WaitingLoopImpl::Construct(void) +{ + _ThreadImpl* pThreadImpl = _ThreadImpl::GetCurrentThreadImpl(); + SysTryReturnResult(NID_BASE_RT, pThreadImpl != null, E_OBJ_NOT_FOUND,"This is not a OSP thread."); + + ThreadType threadType = pThreadImpl->GetThreadType(); + + if(threadType == THREAD_TYPE_MAIN) + { + SysLog(NID_BASE_RT, "This is a the main thread which supports the waiting loop using ecore."); + } + else if(threadType == THREAD_TYPE_EVENT_DRIVEN) + { + SysLog(NID_BASE_RT, "This is a a event driven thread which supports the waiting loop using glib."); + + _EventDispatcher* pEventDispatcher = _EventDispatcher::GetCurrentEventDispatcher(); + if (pEventDispatcher != null) + { + __pGmainContext = pEventDispatcher->GetGMainContext(); + SysLog(NID_BASE_RT, "This thread already has the gmaincontext."); + } + else + { + SysLog(NID_BASE_RT, "This thread does not create the gmaincontext."); + } + } + else + { + SysLog(NID_BASE_RT, "This ia a worker thread which does not support the waiting loop."); + return E_INVALID_OPERATION; + } + __threadType = threadType; + + std::unique_ptr< Timer > pTimer(new (std::nothrow) Timer()); + SysTryReturnResult(NID_BASE_RT, pThreadImpl != null, E_OUT_OF_MEMORY,"Fail to create a timer instance."); + + result r = pTimer->Construct(*this); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, null, r,"[%s]Fail to create a timer instance.", GetErrorMessage(r)); + + __pTimer = pTimer.release(); + return r; +} + +WaitingLoop* +_WaitingLoopImpl::GetInstanceN(void) +{ + std::unique_ptr< _WaitingLoopImpl > pWaitingLoopImpl(new (std::nothrow) _WaitingLoopImpl()); + SysTryReturn(NID_APP, pWaitingLoopImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]Fail to create a _WaitingLoopImpl instance."); + + result r = pWaitingLoopImpl->Construct(); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, null, r,"[%s]Fail to create a _WaitingLoopImpl instance.", GetErrorMessage(r)); + + WaitingLoop* pWaitingLoop = new WaitingLoop(); + SysTryReturn(NID_BASE_RT, pWaitingLoop != null, null, E_OUT_OF_MEMORY,"[E_OUT_OF_MEMORY]Fail to create a WaitingLoop instance."); + + pWaitingLoop->__pWaitingLoopImpl = pWaitingLoopImpl.release(); + + return pWaitingLoop; +} + +result +_WaitingLoopImpl::Wait(int timeout) +{ + SysTryReturnResult(NID_BASE_RT, __waitStatus == WAIT_OFF, E_INVALID_STATE, "The waiting loop is waiting on a thread."); + + __timeout = false; + __waitType = WAIT_TIMEOUT; + result r = __pTimer->Start(timeout); + + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r,"[%s]Timer does not start.", GetErrorMessage(r)); + + __waitStatus = WAIT_ON; + if (__threadType == THREAD_TYPE_MAIN) + { + ecore_main_loop_begin(); + SysLog(NID_BASE_RT, "The waiting loop(ecore) is stopped."); + } + else + { + while(!__timeout && __notifyWait) + { + g_main_context_iteration(__pGmainContext, TRUE); + Thread::Sleep(__sleepTime); + } + SysLog(NID_BASE_RT, "The waiting loop(glib) is stopped."); + } + __pTimer->Cancel(); + __waitStatus = WAIT_OFF; + + SysTryReturn(NID_BASE_RT, __timeout != true, E_TIMEOUT, E_TIMEOUT, "[E_TIMEOUT]The time is expired."); + + return E_SUCCESS; +} + +result +_WaitingLoopImpl::Wait(IWaitingLoopCondition& condition) +{ + SysTryReturnResult(NID_BASE_RT, __waitStatus == WAIT_OFF, E_INVALID_STATE, "[E_INVALID_STATUS]The waiting loop is waiting on a thread."); + + __timeout = false; + __waitType = WAIT_CONDITION; + __pWaitingLoopCondition = &condition; + + if (__threadType == THREAD_TYPE_MAIN) + { + result r = __pTimer->StartAsRepeatable(__waitingRepeatableTime); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r, "[%s]Timer does not start.", GetErrorMessage(r)); + + __waitStatus = WAIT_ON; + ecore_main_loop_begin(); + SysLog(NID_BASE_RT, "The waiting loop(ecore) is stopped."); + + __pTimer->Cancel(); + } + else + { + __waitStatus = WAIT_ON; + while(!__pWaitingLoopCondition->IsMet() && __notifyWait) + { + g_main_context_iteration(__pGmainContext, FALSE); + Thread::Sleep(__sleepTime); + } + SysLog(NID_BASE_RT, "The waiting loop(glib) is stopped."); + } + __waitStatus = WAIT_OFF; + + return E_SUCCESS; +} + +result +_WaitingLoopImpl::Wait(int timeout, IWaitingLoopCondition& condition) +{ + SysTryReturnResult(NID_BASE_RT, __waitStatus == WAIT_OFF, E_INVALID_STATE, "[E_INVALID_STATUS]The waiting loop is waiting on a thread."); + + __timeout = false; + __timerCalledCount = 0; + __waitType = WAIT_TIMEOUT_CONDITION; + __pWaitingLoopCondition = &condition; + + if (timeout < __waitingRepeatableTime) + { + result r = __pTimer->StartAsRepeatable(__waitingRepeatableTime); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r, "[%s]Timer does not start.", GetErrorMessage(r)); + } + else + { + result r = __pTimer->StartAsRepeatable(timeout/10); + SysTryReturn(NID_BASE_RT, r == E_SUCCESS, r, r, "[%s]Timer does not start.", GetErrorMessage(r)); + } + __waitStatus = WAIT_ON; + if (__threadType == THREAD_TYPE_MAIN) + { + ecore_main_loop_begin(); + SysLog(NID_BASE_RT, "The waiting loop(ecore) is stopped."); + } + else + { + while(!__pWaitingLoopCondition->IsMet() && __timeout && __notifyWait) + { + g_main_context_iteration(__pGmainContext, TRUE); + Thread::Sleep(__sleepTime); + } + SysLog(NID_BASE_RT, "The waiting loop(glib) is stopped."); + } + + __pTimer->Cancel(); + __waitStatus = WAIT_OFF; + + SysTryReturn(NID_BASE_RT, __timeout != true, E_TIMEOUT, E_TIMEOUT, "[E_TIMEOUT]The time is expired."); + + return E_SUCCESS; +} + +void +_WaitingLoopImpl::Notify(void) +{ + SysTryReturnVoidResult(NID_BASE_RT, __waitStatus == WAIT_ON, E_INVALID_STATE, "[E_INVALID_STATUS]The waiting loop is not waiting on a thread."); + __notifyWait = false; + + SysLog(NID_BASE_RT, "The waiting loop would be stopped from Notifying."); + + if (__threadType == THREAD_TYPE_MAIN) + { + ecore_main_loop_quit(); + } +} + +void +_WaitingLoopImpl::SetMaxTimeoutForWaiting(int timeout) +{ + __MaxTimeout = timeout; +} + +void +_WaitingLoopImpl::OnTimerExpired(Timer& timer) +{ + if (__threadType == THREAD_TYPE_MAIN) + { + if (__waitType == WAIT_TIMEOUT) + { + ecore_main_loop_quit(); + SysLog(NID_BASE_RT, "The waiting loop is stopped from time out."); + __timeout = true; + } + else if ((__waitType == WAIT_CONDITION) && __pWaitingLoopCondition->IsMet()) + { + ecore_main_loop_quit(); + SysLog(NID_BASE_RT, "The waiting loop is stopped from firing condition."); + } + else if (__waitType == WAIT_TIMEOUT_CONDITION) + { + __timerCalledCount++; + if (__timerCalledCount == __waitingCount) + { + ecore_main_loop_quit(); + SysLog(NID_BASE_RT, "The waiting loop is stopped from time out."); + __timeout = true; + } + else + { + if (__pWaitingLoopCondition->IsMet()) + { + ecore_main_loop_quit(); + SysLog(NID_BASE_RT, "The waiting loop is stopped from firing condition."); + } + } + } + } + else + { + if (__waitType == WAIT_TIMEOUT) + { + __timeout = true; + SysLog(NID_BASE_RT, "The waiting loop is stopped from time out."); + } + else if (__waitType == WAIT_TIMEOUT_CONDITION) + { + __timerCalledCount++; + if (__timerCalledCount == __waitingCount) + { + __timeout = true; + SysLog(NID_BASE_RT, "The waiting loop is stopped from time out."); + } + } + } +} + +bool +_WaitingLoopImpl::IsSameThread(void) +{ + _ThreadImpl* pThreadImpl = _ThreadImpl::GetCurrentThreadImpl(); + SysTryReturn(NID_BASE_RT, pThreadImpl != null, false, E_OBJ_NOT_FOUND,"This is not a OSP thread."); + + ThreadType threadType = pThreadImpl->GetThreadType(); + + if (__threadType == threadType) + { + SysLog(NID_BASE_RT, "The waiting loop is working on the current thread."); + return true; + } + else + { + SysLog(NID_BASE_RT, "The waiting loop is working on another thread."); + return false; + } +} + +} } } // Tizen::Base::Runtime + diff --git a/src/base/runtime/FBaseRt_WaitingLoopImpl.h b/src/base/runtime/FBaseRt_WaitingLoopImpl.h new file mode 100755 index 0000000..4e0b54b --- /dev/null +++ b/src/base/runtime/FBaseRt_WaitingLoopImpl.h @@ -0,0 +1,206 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_WaitingLoopImpl.h + * @brief This is the header file for the %_WaitingLoopImpl class. + * + * This file contains the declarations of the %_WaitingLoopImpl class. + */ + +#ifndef _FBASE_RT_INTERNAL_WAITING_LOOP_IMPL_H_ +#define _FBASE_RT_INTERNAL_WAITING_LOOP_IMPL_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ + +class WaitingLoop; +class IWaitingLoopCondition; +/* + * @class _WaitingLoopImpl + * @brief This class allows developers to make the current thread wait for callback events. This class should be used only for test codes and don't use this class for commercial applications + * @since 2.0 + * + * @final This class is not intended for extension. + */ +class _OSP_EXPORT_ _WaitingLoopImpl + : public Tizen::Base::Object + , public Tizen::Base::Runtime::ITimerEventListener +{ +public: + /* + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_WaitingLoopImpl(void); + + /* + * Gets the WaitingLoop instance. + * + * @since 2.0 + * + * @return A pointer to the WaitingLoop instance, @n + * else @c null if it fails + */ + static WaitingLoop* GetInstanceN(void); + + /* + * Starts the waiting loop and Waits until the time is expired. + * + * @since 2.0 + * + * @param[in] timeout The timeout period in milliseconds + * @exception E_SUCCESS The method is successful. + * @exception E_TIMEOUT The time is expired. + * @exception E_INVALID_STATE The waiting loop has already been waiting on a callback event. In order to wait again, you must quit the waiting loop. + * @remarks The timeout set to min(timeout, maximum), where the maximum is set using SetMaxTimeoutForWaiting(). + * @see Notify(), SetMaxTimoutForWaiting() + */ + result Wait(int timeout); + + /* + * Starts the waiting loop and Waits until the expiring condition occurs. + * + * @since 2.0 + * + * @param[in] condition The expiring condition + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE The waiting loop has already been waiting on a callback event. In order to wait again, you must quit the waiting loop. + * @remarks In order to use this method correctly, you have to implement a class inheriting from %IWaitingLoopCondition. + */ + result Wait(IWaitingLoopCondition& condition); + + /* + * Starts the waiting loop and Waits until either the expiring condition occurs or the time is expired. + * + * @since 2.0 + * + * @param[in] timeout The timeout period in milliseconds + * @param[in] condition The expiring condition + * @exception E_TIMEOUT The time is expired. + * @exception E_INVALID_STATE The waiting loop is waiting on a thread. In order to wait again, you must quit the waiting loop. + * @remarks If the timeout is over the maximum, the expired time goes together with the maximum timeout. In order to use this method correctly, you have to implement a class inheriting from %IWaitingLoopCondition interface + */ + result Wait(int timeout, IWaitingLoopCondition& condition); + + /* + * Notify the waiting thread that the related callback has completed the job. + * + * @since 2.0 + * + * @remarks This method is recommended to use when the waiting condition is not explicitly specified with Wait(). + */ + void Notify(void); + + /* + * Called when the timer is expired. + * + * @since 2.0 + * + * @param[in] timer The expired timer instance + */ + virtual void OnTimerExpired(Timer& timer); + + /* + * This default constructor is intentionally declared as private to implement the %Singleton semantic. + * + * @since 2.0 + * + * @return A boolean value + */ + bool IsSameThread(void); + + /* + * Sets the maximum timeout for waiting. + * + * @since 2.0 + * + * @param[in] timeout The timeout period in milliseconds + * else @c false + * @remarks If the timeout is considered as a small number, it will be replaced with the specified number provided by platform. + */ + void SetMaxTimeoutForWaiting(int timeout); + +private: + // + // This default constructor is intentionally declared as private to implement the %Singleton semantic. + // + // @since 2.0 + // + _WaitingLoopImpl(void); + + // + // The implementation of this copy constructor is intentionally blank and declared as private to prohibit copying of objects. + // + // @since 2.0 + // + _WaitingLoopImpl(const _WaitingLoopImpl& rhs); + + // + // The implementation of this copy assignment operator is intentionally blank and delcared as private to prohibit copying of objects. + // + // @since 2.0 + // + _WaitingLoopImpl& operator =(const _WaitingLoopImpl& rhs); + + // + // Constructs the instance of this class. + // + // @since 2.0 + // + // @return An error code + // @exception E_SUCCESS The method is successful. + // + result Construct(void); + + enum WaitType + { + WAIT_DEFAULT = 0, + WAIT_TIMEOUT, + WAIT_CONDITION, + WAIT_TIMEOUT_CONDITION + }; + + enum WaitStatus + { + WAIT_ON = 0, + WAIT_OFF + }; + + Tizen::Base::Runtime::Timer* __pTimer; + bool __timeout; + bool __notifyWait; + Tizen::Base::Runtime::ThreadType __threadType; + GMainContext* __pGmainContext; + WaitType __waitType; + WaitStatus __waitStatus; + IWaitingLoopCondition* __pWaitingLoopCondition; + int __timerCalledCount; + int __MaxTimeout; + +}; // _WaitingLoopImpl + +} } } // Tizen::Base::Runtime + +#endif // _FBASE_RT_INTERNAL_WAITING_LOOP_IMPL_H_ diff --git a/src/base/runtime/FBaseRt_WorkerThreadImpl.cpp b/src/base/runtime/FBaseRt_WorkerThreadImpl.cpp new file mode 100644 index 0000000..f910f57 --- /dev/null +++ b/src/base/runtime/FBaseRt_WorkerThreadImpl.cpp @@ -0,0 +1,60 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_WorkerThreadImpl.cpp + * @brief This is the implementation file for the _WorkerThreadImpl class. + * + */ + +#include "FBaseRt_WorkerThreadImpl.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +_WorkerThreadImpl::_WorkerThreadImpl(Thread& thread, IRunnable* pIRunnable, const String& name, long stackSize, ThreadPriority priority) + : _ThreadImpl(thread, name, stackSize, priority, THREAD_TYPE_WORKER) + , __pIRunnable(pIRunnable) +{ + +} + +_WorkerThreadImpl::~_WorkerThreadImpl(void) +{ + +} + +Tizen::Base::Object* +_WorkerThreadImpl::Run(void) +{ + if (__pIRunnable) + { + return __pIRunnable->Run(); + } + else + { + Thread* pThread = const_cast (GetThread()); + if (pThread != null) + { + pThread->Run(); + } + } + + return null; +} + +} } } // Tizen::Base::Runtime diff --git a/src/base/runtime/FBaseRt_WorkerThreadImpl.h b/src/base/runtime/FBaseRt_WorkerThreadImpl.h new file mode 100644 index 0000000..2b11db3 --- /dev/null +++ b/src/base/runtime/FBaseRt_WorkerThreadImpl.h @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseRt_WorkerThreadImpl.h + * @brief This is the header file for the _WorkerThreadImpl class. + * + * This file contains the declarations of _WorkerThreadImpl. + */ + + +#ifndef _FRT_THREAD_INTERNAL_WORKER_THREAD_IMPL_H_ +#define _FRT_THREAD_INTERNAL_WORKER_THREAD_IMPL_H_ + +#include "FBaseRt_ThreadImpl.h" + +namespace Tizen { namespace Base { namespace Runtime +{ + +class _WorkerThreadImpl + : public _ThreadImpl +{ +public: + _WorkerThreadImpl(Thread& thread, IRunnable* pIRunnable, const String& name, long stackSize, ThreadPriority priority); + + virtual ~_WorkerThreadImpl(void); + + virtual Tizen::Base::Object* Run(void); + +private: + _WorkerThreadImpl(const _WorkerThreadImpl& rhs); + _WorkerThreadImpl& operator= (const _WorkerThreadImpl& rhs); + +private: + IRunnable* __pIRunnable; +}; + + +} } } // Tizen::Base::Runtime + +#endif // _FRT_THREAD_INTERNAL_WORKER_THREAD_H_ diff --git a/src/base/utility/FBaseUtilDeflator.cpp b/src/base/utility/FBaseUtilDeflator.cpp new file mode 100644 index 0000000..ac5d017 --- /dev/null +++ b/src/base/utility/FBaseUtilDeflator.cpp @@ -0,0 +1,172 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilDeflator.cpp + * @brief This is the implementation file for Deflator class. + */ + +// Includes +#include +#include +#include +#include +#include +#include +#include "zlib.h" + + +namespace Tizen { namespace Base { namespace Utility +{ + +struct FreeCustomDeleter +{ + void operator ()(Byte* p) + { + if (p != null) + { + free(p); + } + } +}; + +/////////////////////////////////////////////////////////////////////////////// +/// Deflator class lifecycle + +Deflator::Deflator(void) +{ +} + + +Deflator::~Deflator(void) +{ +} + + +/////////////////////////////////////////////////////////////////////////////// +/// Deflator class Operations + +ByteBuffer* +Deflator::DeflateN(const ByteBuffer& src, int byteCount, CompressionLevel level) +{ + // Input value validation + SysTryReturn(NID_BASE_UTIL, byteCount > 0 && (byteCount + src.GetPosition()) <= src.GetLimit(), null, E_INVALID_ARG, "[%s] Invalid argument is used. Invalid byteCount value.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_BASE_UTIL, !((level != BEST_SPEED) && (level != BEST_COMPRESSION) && (level != DEFAULT_COMPRESSION)), null, E_INVALID_ARG, "[%s] Invalid argument is used. Invalid compression level.", GetErrorMessage(E_INVALID_ARG)); + + int outputSize = 0; + Byte* pInArray = null; + z_stream stream; + uLong outSize = 0; + int compLevel = Z_DEFAULT_COMPRESSION; + + switch (level) + { + case BEST_SPEED: + compLevel = Z_BEST_SPEED; + break; + + case BEST_COMPRESSION: + compLevel = Z_BEST_COMPRESSION; + break; + + default: + compLevel = Z_DEFAULT_COMPRESSION; + } + pInArray = const_cast < Byte* >(src.GetPointer() + src.GetPosition()); + + stream.zalloc = (alloc_func) 0; + stream.zfree = (free_func) 0; + stream.opaque = (voidpf) 0; + + SysTryReturn(NID_BASE_UTIL, pInArray != null, null, E_SYSTEM, "[%s] pInArray is null.", GetErrorMessage(E_SYSTEM)); + + // Initializing zlib variables + int err = deflateInit(&stream, compLevel); + SysTryReturn(NID_BASE_UTIL, err == Z_OK, null, E_SYSTEM, "[%s] Error in deflate initialization.", GetErrorMessage(E_SYSTEM)); + + // deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. + outSize = deflateBound(&stream, (uLong) byteCount); + SysTryReturn(NID_BASE_UTIL, outSize > 0, null, E_SYSTEM, "[%s] Upper bound of compressed size = %l.", GetErrorMessage(E_SYSTEM), outSize); + + Bytef* pOutPutArray = static_cast< Bytef* >(malloc(outSize)); + SysTryReturn(NID_BASE_UTIL, pOutPutArray != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + stream.next_in = static_cast< Bytef* >(pInArray); + stream.avail_in = static_cast< uInt >(byteCount); + stream.next_out = static_cast< Bytef* >(pOutPutArray); + stream.avail_out = static_cast< uInt >(outSize); + + // Check for source > 64K on 16-bit machine + if ((stream.avail_in != static_cast< uInt >(byteCount)) || (stream.avail_out != static_cast< uInt >(outSize))) + { + SysLogException(NID_BASE_UTIL, E_SYSTEM, "Deflate not supported for this source size, avail_in = %l, avail_out = %l, count = %l", stream.avail_in, stream.avail_out, byteCount); + SetLastResult(E_SYSTEM); + return null; + } + + // Deflating input buffer + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) + { + SysLogException(NID_BASE_UTIL, E_SYSTEM, "[%s] A system error has occurred while deflating.", GetErrorMessage(E_SYSTEM)); + SetLastResult(E_SYSTEM); + return null; + } + + if (static_cast< uLong >(stream.total_out) > outSize) + { + SysLogException(NID_BASE_UTIL, E_SYSTEM, "total out [%l] is not less than outputSize [%l]", stream.total_out, outSize); + SetLastResult(E_SYSTEM); + return null; + } + + // releasing zlib resources + err = deflateEnd(&stream); + if (err != Z_OK) + { + SysLogException(NID_BASE_UTIL, E_SYSTEM, "[%s] A system error has occurred in deflateEnd.", GetErrorMessage(E_SYSTEM)); + SetLastResult(E_SYSTEM); + return null; + } + + std::unique_ptr< Byte, FreeCustomDeleter> pOutArray(static_cast< Byte* >(pOutPutArray)); + + outputSize = stream.total_out; + + // copying deflated output to byte buffer + std::unique_ptr< ByteBuffer > pOutBuf(new (std::nothrow) ByteBuffer()); + result r = pOutBuf->Construct(outputSize); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = pOutBuf->SetArray(pOutArray.get(), 0, outputSize); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + pOutBuf->Flip(); + + SetLastResult(E_SUCCESS); + return pOutBuf.release(); +} + + +ByteBuffer* +Deflator::DeflateN(const ByteBuffer& src, CompressionLevel level) +{ + int byteCount = src.GetRemaining(); + return DeflateN(src, byteCount, level); +} + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilFileUnzipper.cpp b/src/base/utility/FBaseUtilFileUnzipper.cpp new file mode 100644 index 0000000..282f755 --- /dev/null +++ b/src/base/utility/FBaseUtilFileUnzipper.cpp @@ -0,0 +1,143 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @File : FBaseUtilFileUnzipper.cpp + * @brief : Implementation for FileUnzipper Class + */ + +#include +#include + +#include +#include +#include +#include "FBaseUtil_ZipEntryInfo.h" +#include "FBaseUtil_FileUnzipperImpl.h" + + +namespace Tizen {namespace Base {namespace Utility +{ + + +#define UNZ_COMP_CASE_SENSITIVE 1 +#define UNZ_COMP_NO_CASE_SENSITIVE 2 + +#define UNZ_WRITE_BUF_LEN 4096 \ + // _BADA_SLP_FIXME : TODO - Select an optimal value for this. + + +FileUnzipper::FileUnzipper(void) + : __pFileUnzipperImpl(null) +{ +} + + +FileUnzipper::~FileUnzipper(void) +{ + delete __pFileUnzipperImpl; +} + + +result +FileUnzipper::Construct(const String& filePath) +{ + SysAssertf(__pFileUnzipperImpl == null, "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_BASE_UTIL, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, "Invalid argument was passed. Given file name length is not correct!"); + SysTryReturnResult(NID_BASE_UTIL, !filePath.EndsWith(L"/"), E_INVALID_ARG, "Invalid argument was passed. Given file name is not correct! - ends with '/'"); + + std::unique_ptr< _FileUnzipperImpl > pFileUnzipperImpl(new (std::nothrow) _FileUnzipperImpl()); + SysTryReturnResult(NID_BASE_UTIL, pFileUnzipperImpl != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = pFileUnzipperImpl->Construct(filePath); + SysTryReturnResult(NID_BASE_UTIL, !IsFailed(r), r, "[%s] Propagating.", GetErrorMessage(r)); + + __pFileUnzipperImpl = pFileUnzipperImpl.release(); + + return r; +} + + +result +FileUnzipper::UnzipTo(const String& dirPath) const +{ + SysAssertf(__pFileUnzipperImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_BASE_UTIL, dirPath.GetLength() > 0 && dirPath.GetLength() <= PATH_MAX, E_INVALID_ARG, "Invalid argument was passed. Given dir path length is not correct!"); + + return __pFileUnzipperImpl->UnzipTo(dirPath); +} + + +result +FileUnzipper::UnzipTo(const String& dirPath, const String& zipEntryName) const +{ + SysAssertf(__pFileUnzipperImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_BASE_UTIL, dirPath.GetLength() > 0 && dirPath.GetLength() <= PATH_MAX, E_INVALID_ARG, "Invalid argument was passed. Given dir path length is not correct!"); + SysTryReturnResult(NID_BASE_UTIL, zipEntryName.GetLength() > 0 && zipEntryName.GetLength() <= PATH_MAX, E_INVALID_ARG, "Invalid argument was passed. Given file path length is not correct!"); + + return __pFileUnzipperImpl->UnzipTo(dirPath, zipEntryName); +} + + +int +FileUnzipper::GetEntryCount(void) const +{ + SysAssertf(__pFileUnzipperImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pFileUnzipperImpl->GetEntryCount(); +} + + +int +FileUnzipper::GetFileCount(void) const +{ + SysAssertf(__pFileUnzipperImpl != null, "Not yet constructed! Construct() should be called before us."); + + return __pFileUnzipperImpl->GetFileCount(); +} + + +int +FileUnzipper::GetDirectoryCount(void) const +{ + SysAssertf(__pFileUnzipperImpl != null, "Not yet constructed! Construct() should be called before use."); + + return __pFileUnzipperImpl->GetDirectoryCount(); +} + + +result +FileUnzipper::GetEntry(const String& zipEntryName, ZipEntry& entry) const +{ + SysAssertf(__pFileUnzipperImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_BASE_UTIL, zipEntryName.GetLength() > 0 && zipEntryName.GetLength() <= PATH_MAX, E_INVALID_ARG, "Invalid argument was passed. Given zip entry path length is not correct!"); + + return __pFileUnzipperImpl->GetEntry(zipEntryName, entry); +} + + +result +FileUnzipper::GetEntry(int index, ZipEntry& entry) const +{ + SysAssertf(__pFileUnzipperImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_BASE_UTIL, index >= 0, E_INVALID_ARG, "File path passed is invalid."); + SysTryReturnResult(NID_BASE_UTIL, (unsigned long) index <= __pFileUnzipperImpl->GetEntryCount(), E_INVALID_ARG, "File path passed is invalid."); + + return __pFileUnzipperImpl->GetEntry(index, entry); +} + + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilFileZipper.cpp b/src/base/utility/FBaseUtilFileZipper.cpp new file mode 100644 index 0000000..66812b7 --- /dev/null +++ b/src/base/utility/FBaseUtilFileZipper.cpp @@ -0,0 +1,101 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @File : FBaseUtilFileZipper.cpp + * @brief : Implementation for FileZipper Class + */ + +#include +#include + +#include +#include +#include +#include "FBaseUtil_FileZipperImpl.h" + + +using namespace Tizen::Io; + +namespace Tizen { namespace Base { namespace Utility +{ + +FileZipper::FileZipper(void) + : __pFileZipperImpl(null) +{ +} + +FileZipper::~FileZipper(void) +{ + delete __pFileZipperImpl; +} + +result +FileZipper::Construct(const String& filePath) +{ + SysAssertf(__pFileZipperImpl == null, "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + SysTryReturnResult(NID_BASE_UTIL, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "Invalid argument was passed. Given file name length is not correct!"); + SysTryReturnResult(NID_BASE_UTIL, !filePath.EndsWith(L"/"), E_INVALID_ARG, + "Invalid argument was passed. Given file name is not correct! - ends with '/'"); + + std::unique_ptr< _FileZipperImpl > pFileZipperImpl(new (std::nothrow) _FileZipperImpl()); + SysTryReturnResult(NID_BASE_UTIL, pFileZipperImpl != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = pFileZipperImpl->Construct(filePath); + SysTryReturnResult(NID_BASE_UTIL, !IsFailed(r), r, "Propagating."); + + __pFileZipperImpl = pFileZipperImpl.release(); + + return r; +} + +result +FileZipper::AddToZip(const String& filePath, bool excludePath, CompressionLevel level) +{ + SysAssertf(__pFileZipperImpl != null, "Not yet constructed! Construct() should be called before use"); + SysTryReturnResult(NID_BASE_UTIL, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "Invalid argument was passed. Given file name length is not correct!"); + SysTryReturnResult(NID_BASE_UTIL, !filePath.EndsWith(L"/"), E_INVALID_ARG, + "Invalid argument was passed. Given file name is not correct! - ends with '/'"); + + return __pFileZipperImpl->AddToZip(filePath, excludePath, level); +} + +bool +FileZipper::GetOverwriteFlag(void) const +{ + if (__pFileZipperImpl) + { + return __pFileZipperImpl->GetOverwriteFlag(); + } + else + { + return false; + } +} + +void +FileZipper::SetOverwriteFlag(bool flag) +{ + if (__pFileZipperImpl) + { + __pFileZipperImpl->SetOverwriteFlag(flag); + } +} + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilInflator.cpp b/src/base/utility/FBaseUtilInflator.cpp new file mode 100644 index 0000000..829187c --- /dev/null +++ b/src/base/utility/FBaseUtilInflator.cpp @@ -0,0 +1,173 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilInflator.cpp + * @brief This is the implementation file for Inflator class. + */ + +// Includes +#include +#include +#include +#include +#include +#include +#include "zlib.h" + + +namespace Tizen { namespace Base { namespace Utility +{ + +struct FreeCustomDeleter +{ + void operator ()(Bytef* p) + { + if (p != null) + { + free(p); + } + } +}; + +/////////////////////////////////////////////////////////////////////////////// +/// Inflator class lifecycle + +Inflator::Inflator(void) +{ +} + + +Inflator::~Inflator(void) +{ +} + + +ByteBuffer* +Inflator::InflateN(const ByteBuffer& src, int byteCount) +{ + SysTryReturn(NID_BASE_UTIL, byteCount > 0 && (byteCount + src.GetPosition()) <= src.GetLimit(), null, E_INVALID_ARG, "[%s] Invalid argument is used. Invalid byteCount value", GetErrorMessage(E_INVALID_ARG)); + + int outputSize = 0; + z_stream stream; + uLong outSize = 0; + uLong totalSize = 0; + + Byte* pInArray = const_cast< Byte* >(src.GetPointer() + src.GetPosition()); + + stream.zalloc = (alloc_func) 0; + stream.zfree = (free_func) 0; + stream.opaque = (voidpf) 0; + + // Input value validation + SysTryReturn(NID_BASE_UTIL, pInArray != null, null, E_SYSTEM, "[%s] pInArray is null.", GetErrorMessage(E_SYSTEM)); + + // Initializing zlib variables + int err = inflateInit(&stream); + SysTryReturn(NID_BASE_UTIL, err == Z_OK, null, E_SYSTEM, "[%s] Error in deflate initialization.", GetErrorMessage(E_SYSTEM)); + + outSize = byteCount * Z_BEST_COMPRESSION; + + std::unique_ptr< Bytef, FreeCustomDeleter > pOutArray(static_cast< Bytef* >(malloc(outSize))); + SysTryReturn(NID_BASE_UTIL, pOutArray != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + totalSize = outSize; + + stream.next_in = static_cast< Bytef* >(pInArray); + stream.avail_in = static_cast< uInt >(byteCount); + stream.next_out = static_cast< Bytef* >(pOutArray.get()); + stream.avail_out = static_cast< uInt >(outSize); + + // Check for source > 64K on 16-bit machine + if ((stream.avail_in != static_cast< uInt >(byteCount)) || (static_cast< uLong >(stream.avail_out) != static_cast< uInt >(outSize))) + { + SysLogException(NID_BASE_UTIL, E_SYSTEM, "Inflate not supported for this source size, avail_in = %l, avail_out = %l, count = %l", stream.avail_in, stream.avail_out, byteCount); + SetLastResult(E_SYSTEM); + return null; + } + + // inflating input buffer + do + { + err = inflate(&stream, Z_NO_FLUSH); + if (err != Z_STREAM_END && !(err == Z_OK && stream.avail_out == 0)) + { + SysLogException(NID_BASE_UTIL, E_SYSTEM, "[%s] A system error has occurred while inflating.", GetErrorMessage(E_SYSTEM)); + SetLastResult(E_SYSTEM); + return null; + } + + if (err == Z_OK) + { + Bytef* pOutArrayNew = static_cast< Bytef* >(malloc(outSize + totalSize)); + SysTryReturn(NID_BASE_UTIL, pOutArrayNew != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + memcpy(pOutArrayNew, pOutArray.get(), totalSize); + pOutArray.reset(pOutArrayNew); + pOutArrayNew = null; + + stream.next_out = static_cast< Bytef* >(pOutArray.get() + totalSize); + stream.avail_out = static_cast< uInt >(outSize); + + totalSize = totalSize + outSize; + } + } + while (err != Z_STREAM_END); + + if ((static_cast< uLong >(stream.total_out)) > totalSize) + { + SysLogException(NID_BASE_UTIL, E_SYSTEM, "[%s] total out [%l] is not less than outSize [%l].", GetErrorMessage(E_SYSTEM), stream.total_out, outSize); + SetLastResult(E_SYSTEM); + return null; + } + + // releasing zlib resources + err = inflateEnd(&stream); + if (err != Z_OK) + { + SysLogException(NID_BASE_UTIL, E_SYSTEM, "[%s] A system error has occurred in inflateEnd.", GetErrorMessage(E_SYSTEM)); + SetLastResult(E_SYSTEM); + return null; + } + + // Success + Byte* pOutPutArray = static_cast< Byte* >(pOutArray.get()); + + outputSize = stream.total_out; + + // copying deflated output to byte buffer + std::unique_ptr< ByteBuffer > pOutBuf(new (std::nothrow) ByteBuffer()); + result r = pOutBuf->Construct(outputSize); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = pOutBuf->SetArray(pOutPutArray, 0, outputSize); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + pOutBuf->Flip(); + + SetLastResult(E_SUCCESS); + return pOutBuf.release(); +} + + +ByteBuffer* +Inflator::InflateN(const ByteBuffer& src) +{ + return InflateN(src, src.GetRemaining()); +} + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilLinkInfo.cpp b/src/base/utility/FBaseUtilLinkInfo.cpp new file mode 100644 index 0000000..f68c8c7 --- /dev/null +++ b/src/base/utility/FBaseUtilLinkInfo.cpp @@ -0,0 +1,129 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilLinkInfo.cpp + * @brief This is the implementation file for the LinkeInfo class. + * + */ + + +//Includes +#include + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Base { namespace Utility +{ + +LinkInfo::LinkInfo(void) + : __linkType(LINK_TYPE_NONE) + , __pLinkInfoImpl(null) +{ +} + + +LinkInfo::LinkInfo(const LinkInfo& value) + : __pLinkInfoImpl(null) +{ + __linkType = value.__linkType; + __link = value.__link; + __text = value.__text; +} + + +LinkInfo::LinkInfo(LinkType linkType, const String& link) + : __linkType(linkType) + , __link(link) + , __text(link) + , __pLinkInfoImpl(null) +{ +} + + +LinkInfo::LinkInfo(LinkType linkType, const String& link, const String& text) + : __linkType(linkType) + , __link(link) + , __text(text) + , __pLinkInfoImpl(null) +{ +} + + +LinkInfo::~LinkInfo(void) +{ +} + + +LinkInfo& +LinkInfo::operator =(const LinkInfo& rhs) +{ + if (&rhs != this) + { + __linkType = rhs.__linkType; + __link = rhs.__link; + __text = rhs.__text; + } + return(*this); +} + + +void +LinkInfo::SetLink(const String& link) +{ + __link = link; +} + + +String +LinkInfo::GetLink(void) const +{ + return __link; +} + + +void +LinkInfo::SetLinkType(LinkType linkType) +{ + __linkType = linkType; +} + + +LinkType +LinkInfo::GetLinkType(void) const +{ + return __linkType; +} + + +void +LinkInfo::SetText(const String& text) +{ + __text = text; +} + + +String +LinkInfo::GetText(void) const +{ + return __text; +} + + +}}} diff --git a/src/base/utility/FBaseUtilMath.cpp b/src/base/utility/FBaseUtilMath.cpp new file mode 100644 index 0000000..c987707 --- /dev/null +++ b/src/base/utility/FBaseUtilMath.cpp @@ -0,0 +1,272 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilMath.cpp + * @brief This is the implementation file for Math class. + */ + +// Includes +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + + +/////////////////////////////////////////////////////////////////////////////// +/// Math class lifecycle + +Math::Math(void) +{ +} + + +Math::~Math(void) +{ +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Math class operations + +int +Math::Abs(int x) +{ + return abs(x); +} + + +double +Math::Asin(double x) +{ + return asin(x); +} + + +double +Math::Acos(double x) +{ + return acos(x); +} + + +double +Math::Atan(double x) +{ + return atan(x); +} + + +double +Math::Ceiling(double x) +{ + return ceil(x); +} + + +double +Math::Cos(double x) +{ + return cos(x); +} + + +double +Math::Cosh(double x) +{ + return cosh(x); +} + + +double +Math::Exp(double x) +{ + static const double huge = 1.0e+300; + static const double twom1000 = 9.33263618503218878990e-302; // 2**-1000=0x01700000,0 + static const double o_threshold = 7.09782712893383973096e+02; // 0x40862E42, 0xFEFA39EF + static const double u_threshold = -7.45133219101941108420e+02; // 0xc0874910, 0xD52D3051 + + if (x > o_threshold) // overflow + { + return huge * huge; + } + if (x < u_threshold) // underflow + { + return twom1000 * twom1000; + } + + return exp(x); +} + + +double +Math::Floor(double x) +{ + return floor(x); +} + + +double +Math::Log(double x) +{ + return log(x); +} + + +double +Math::Log10(double x) +{ + return log10(x); +} + + +int +Math::Max(int x, int y) +{ + return (x >= y) ? x : y; +} + + +double +Math::Max(double x, double y) +{ + // x is NaN + if (isnan(x) == 1) + { + return x; + } + + // y is NaN + if (isnan(y) == 1) + { + return y; + } + + return (x >= y) ? x : y; +} + + +int +Math::Min(int x, int y) +{ + return (x <= y) ? x : y; +} + + +double +Math::Min(double x, double y) +{ + // x is NaN + if (isnan(x) == 1) + { + return x; + } + + // y is NaN + if (isnan(y) == 1) + { + return y; + } + + return (x <= y) ? x : y; +} + + +double +Math::Pow(double x, double y) +{ + return pow(x, y); +} + + +double +Math::Round(double x) +{ + return round(x); +} + + +double +Math::Sin(double x) +{ + return sin(x); +} + + +double +Math::Sinh(double x) +{ + return sinh(x); +} + + +double +Math::Sqrt(double x) +{ + return sqrt(x); +} + + +double +Math::Tan(double x) +{ + return tan(x); +} + + +double +Math::Tanh(double x) +{ + return tanh(x); +} + + +void +Math::Srand(unsigned int seed) +{ + srand(seed); +} + + +int +Math::Rand(void) +{ + return rand() % (RAND_VALUE_MAX + 1); +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Math class accessors + +const double +Math::GetE(void) +{ + return M_E; +} + + +const double +Math::GetPi(void) +{ + return M_PI; +} + + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilRegularExpression.cpp b/src/base/utility/FBaseUtilRegularExpression.cpp new file mode 100644 index 0000000..c45f14d --- /dev/null +++ b/src/base/utility/FBaseUtilRegularExpression.cpp @@ -0,0 +1,183 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @File : FBaseUtilRegularExpression.cpp + * @brief : Implementation for RegularExpression Class + */ + +//Includes +//#include "FBaseSysInternal.h" +#include +#include +#include +#include +#include "FBaseUtil_RegularExpressionImpl.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Base { namespace Utility +{ + +RegularExpression::RegularExpression() + : __pRegularExpressionImpl(null) +{ +} + +RegularExpression::~RegularExpression() +{ + if (__pRegularExpressionImpl) + { + __pRegularExpressionImpl->Cleanup(); + } + + delete __pRegularExpressionImpl; +} + +result +RegularExpression::Construct(const String& pattern, unsigned long options) +{ + SysAssertf(__pRegularExpressionImpl == null, "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_BASE_UTIL, !pattern.IsEmpty(), E_INVALID_ARG, "Invalid argument is used. The length of the pattern is zero."); + + std::unique_ptr< _RegularExpressionImpl > pRegularExpressionImpl(new (std::nothrow) _RegularExpressionImpl()); + SysTryReturnResult(NID_BASE_UTIL, pRegularExpressionImpl != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = pRegularExpressionImpl->Construct(pattern, options); + SysTryReturnResult(NID_BASE_UTIL, r == E_SUCCESS, r, "Propagating."); + + __pRegularExpressionImpl = pRegularExpressionImpl.release(); + + return r; +} + + +bool +RegularExpression::Match(const Tizen::Base::String& text, bool fullMatch, IList* pMatchedString) const +{ + bool r = true; + SysAssertf(__pRegularExpressionImpl != null, "Not yet constructed! Construct() should be called before use"); + SysTryReturn(NID_BASE_UTIL, !text.IsEmpty(), r = false, E_INVALID_ARG, "[%s] Invalid argument is used. The length of the text is zero.", GetErrorMessage(E_INVALID_ARG)); + return __pRegularExpressionImpl->Match(text, fullMatch, pMatchedString); + +} + + +bool +RegularExpression::Consume(String& text, IList* pMatchedString) const +{ + bool r = true; + SysAssertf(__pRegularExpressionImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_BASE_UTIL, !text.IsEmpty(), r = false, E_INVALID_ARG, "[%s] Invalid argument is used. The length of the text is zero.", GetErrorMessage(E_INVALID_ARG)); + return __pRegularExpressionImpl->Consume(text, pMatchedString); + +} + + +bool +RegularExpression::FindAndConsume(String& text, IList* pMatchedString) const +{ + bool r = true; + SysAssertf(__pRegularExpressionImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_BASE_UTIL, !text.IsEmpty(), r = false, E_INVALID_ARG, "[%s] Invalid argument is used. The length of the text is zero.", GetErrorMessage(E_INVALID_ARG)); + return __pRegularExpressionImpl->FindAndConsume(text, pMatchedString); + +} + +bool +RegularExpression::Replace(String& text, const String& rewrite, bool globalReplace, int startPos) const +{ + bool r = true; + SysAssertf(__pRegularExpressionImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_BASE_UTIL, !text.IsEmpty(), r = false, E_INVALID_ARG, "[%s] The length of the text is zero.", GetErrorMessage(E_INVALID_ARG)); + return __pRegularExpressionImpl->Replace(text, rewrite, globalReplace, startPos); +} + + +bool +RegularExpression::Extract(const String& text, const String& rewrite, String& out) const +{ + bool r = true; + SysAssertf(__pRegularExpressionImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_BASE_UTIL, !text.IsEmpty(), r = false, E_INVALID_ARG, "[%s] Invalid argument is used. The length of the text is zero.", GetErrorMessage(E_INVALID_ARG)); + return __pRegularExpressionImpl->Extract(text, rewrite, out); +} + +String +RegularExpression::GetPattern() const +{ + SysAssertf(__pRegularExpressionImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pRegularExpressionImpl->GetPattern(); +} + + +unsigned long +RegularExpression::GetOptions(void) const +{ + SysAssertf(__pRegularExpressionImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pRegularExpressionImpl->GetOptions(); +} + +result +RegularExpression::SetOptions(unsigned long options) +{ + SysAssertf(__pRegularExpressionImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pRegularExpressionImpl->SetOptions(options); +} + + +bool +RegularExpression::Equals(const Tizen::Base::Object& obj) const +{ + const RegularExpression* pOther = static_cast (&obj); + + if ((__pRegularExpressionImpl != null) && (pOther->__pRegularExpressionImpl != null)) + { + if (__pRegularExpressionImpl->GetPattern() != pOther->__pRegularExpressionImpl->GetPattern()) + { + return false; + } + if (__pRegularExpressionImpl->GetOptions() != pOther->__pRegularExpressionImpl->GetOptions()) + { + return false; + } + } + else + { + if (__pRegularExpressionImpl != pOther->__pRegularExpressionImpl) + { + return false; + } + } + + return true; +} + +int +RegularExpression::GetHashCode(void) const +{ + if (__pRegularExpressionImpl == null) + { + return String("").GetHashCode(); + } + return __pRegularExpressionImpl->__pattern.GetHashCode(); +} + + +}}} diff --git a/src/base/utility/FBaseUtilStringTokenizer.cpp b/src/base/utility/FBaseUtilStringTokenizer.cpp new file mode 100644 index 0000000..162f548 --- /dev/null +++ b/src/base/utility/FBaseUtilStringTokenizer.cpp @@ -0,0 +1,251 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilStringTokenizer.cpp + * @brief This is the implementation file for StringTokenizer class. + * @see String class + */ + +// Includes +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + + +///////////////////////////////////////////////////////////////////////////// +// StringTokenizer class lifecycle + +StringTokenizer::StringTokenizer(const String& value, const String& delimiters, bool isToken) + : __curPosition(0) + , __newPosition(0) + , __isToken(isToken) + , __isDelimChanged(false) + , __pStringTokenizerImpl(null) +{ + __string = value; + __delimiters = delimiters; + + __maxStrLen = __string.GetLength(); + __maxDelimChar = SetMaxDelimChar(); +} + + +StringTokenizer::~StringTokenizer(void) +{ +} + + +///////////////////////////////////////////////////////////////////////////////////// +// StringTokenizer class operations + +int +StringTokenizer::GetTokenCount(void) +{ + int count = 0; + int tmpPosition = __curPosition; + + while (tmpPosition < __maxStrLen) + { + tmpPosition = SkipDelimiters(tmpPosition); + + if (tmpPosition >= __maxStrLen) + { + break; + } + + tmpPosition = ScanToken(tmpPosition); + count++; + } + return count; +} + + +bool +StringTokenizer::HasMoreTokens(void) +{ + __newPosition = SkipDelimiters(__curPosition); + + if (__newPosition >= __maxStrLen) + { + return false; + } + + return true; +} + + +result +StringTokenizer::GetNextToken(String& token) +{ + int startPosition = 0; + int length = 0; + + String tmpToken; + + result r = E_UNKNOWN; + + if (__newPosition >= 0 && __isDelimChanged) + { + __curPosition = __newPosition; + } + else + { + __curPosition = SkipDelimiters(__curPosition); + } + + // Reset anyway + __newPosition = -1; + __isDelimChanged = false; + + if (__curPosition >= __maxStrLen) + { + // Do not log the E_OUT_OF_RANGE, because it's normal or trivial in most cases. + r = E_OUT_OF_RANGE; + goto CATCH; + } + + startPosition = __curPosition; + __curPosition = ScanToken(__curPosition); + + length = __curPosition - startPosition; // the length of token(sub-string) + r = __string.SubString(startPosition, length, tmpToken); + SysTryCatch(NID_BASE_UTIL, r == E_SUCCESS, , r, "[%s] Propagating.", GetErrorMessage(r)); + + token = tmpToken; + return E_SUCCESS; + +CATCH: + return r; +} + + +result +StringTokenizer::SetDelimiters(const String& delimiters) +{ + SysTryReturn(NID_BASE_UTIL, delimiters.GetLength() > 0, E_INVALID_ARG, E_INVALID_ARG, "[%s] Invalid argument is used. The delimiters is an empty string.", GetErrorMessage(E_INVALID_ARG)); + + __isDelimChanged = true; + __delimiters = delimiters; + + __maxDelimChar = SetMaxDelimChar(); + + return E_SUCCESS; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// StringTokenizer class private methods + +wchar_t +StringTokenizer::SetMaxDelimChar(void) +{ + wchar_t mc = 0; + wchar_t maxChar = 0; + + int length = __delimiters.GetLength(); + + if (length <= 0) + { + goto CATCH; + } + + for (int i = 0; i < length; i++) + { + mc = __delimiters[i]; + if (mc > maxChar) + { + maxChar = mc; + } + } + + return maxChar; + +CATCH: + return maxChar; +} + + +int +StringTokenizer::SkipDelimiters(int position) +{ + result r = E_SUCCESS; + int indexOf = 0; + wchar_t mc = 0x00; + int tmpPosition = position; + + // skip delimiters + while ((!__isToken) && (tmpPosition < __maxStrLen)) + { + mc = __string[tmpPosition]; + r = __delimiters.IndexOf(mc, 0, indexOf); + + if ((mc > __maxDelimChar) || (r == E_OBJ_NOT_FOUND)) // mc is not a delimiter. + { + break; + } + + tmpPosition++; + } + + return tmpPosition; +} + + +int +StringTokenizer::ScanToken(int position) +{ + result r = E_SUCCESS; + int tmpPosition = position; + int indexOf = 0; + wchar_t mc = 0x00; + + while (tmpPosition < __maxStrLen) + { + mc = __string[tmpPosition]; + r = __delimiters.IndexOf(mc, 0, indexOf); + + if ((mc <= __maxDelimChar) && (r != E_OBJ_NOT_FOUND)) // mc is a delimiter + { + break; + } + + tmpPosition++; + } + + if (__isToken && tmpPosition == position) // mc is regarded as a token + { + mc = __string[tmpPosition]; + + r = __delimiters.IndexOf(mc, 0, indexOf); + + if ((mc <= __maxDelimChar) && (r != E_OBJ_NOT_FOUND)) // mc is a delimiter + { + tmpPosition++; + } + } + + return tmpPosition; +} + + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilStringUtil.cpp b/src/base/utility/FBaseUtilStringUtil.cpp new file mode 100644 index 0000000..42dcbc0 --- /dev/null +++ b/src/base/utility/FBaseUtilStringUtil.cpp @@ -0,0 +1,466 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilStringUtil.cpp + * @brief This is the implementation file for StringUtil class. + */ + +// Includes +#include +#include +#include +#include +#include +#include +#include "FBase_NativeError.h" +#include "FBase_StringConverter.h" +#include "FBaseUtil_IcuConverter.h" + + +// Base64 Encoding Table +static const char Base64EncodingTable[] = +{ + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', + '4', '5', '6', '7', '8', '9', '+', '/' +}; + + +// Base64 Decoding Table +static int Base64DecodingTable[256] = +{ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0F + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1F + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, // 20-2F + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 30-3F + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40-4F + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, // 50-5F + -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60-6F + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, // 70-7F + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 80-8F + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 90-9F + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // A0-AF + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // B0-BF + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // C0-CF + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // D0-DF + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // E0-EF + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 // F0-FF +}; + + +namespace Tizen { namespace Base { namespace Utility +{ + +StringUtil::StringUtil(void) +{ +} + +StringUtil::~StringUtil(void) +{ +} + +result +StringUtil::MbToString(const McharBuffer& mb, String& str) +{ + int length = GetStringLengthInMb(mb); + SysTryReturnResult(NID_BASE_UTIL,length >= 0, E_INVALID_ARG, "Invalid argument is used. null character does not exist between position and limit."); + ClearLastResult(); + + result r = E_SUCCESS; + int position = mb.GetPosition(); + + std::unique_ptr< mchar[] > pMc(new (std::nothrow) mchar[length + 1]); + SysTryReturnResult(NID_BASE_UTIL, pMc != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + wcsncpy(pMc.get(), (mb.GetPointer() + position), length); + pMc[length] = 0; + + str = pMc.get(); + + return r; +} + +result +StringUtil::WcharBufferToString(const WcharBuffer& wb, String& str) +{ + int length = GetStringLengthInMb(wb); + SysTryReturnResult(NID_BASE_UTIL, length >= 0, E_INVALID_ARG, "Invalid argument is used. null character does not exist between position and limit."); + ClearLastResult(); + + result r = E_SUCCESS; + int position = wb.GetPosition(); + + std::unique_ptr< wchar_t[] > pWc(new (std::nothrow) wchar_t[length + 1]); + SysTryReturnResult(NID_BASE_UTIL, pWc != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + wcsncpy(pWc.get(), (wb.GetPointer() + position), length); + pWc[length] = 0; + + str = pWc.get(); + + return r; +} + +McharBuffer* +StringUtil::StringToMbN(const String& str) +{ + SysTryReturn(NID_BASE_UTIL, !str.IsEmpty(), null, E_INVALID_ARG, "[%s] Invalid argument is used. The str is an empty string.", GetErrorMessage(E_INVALID_ARG)); + ClearLastResult(); + + int strLen = str.GetLength(); + int size = str.GetLength() + 1; + + std::unique_ptr< McharBuffer > pBuf(new (std::nothrow) McharBuffer()); + SysTryReturn(NID_BASE_UTIL, pBuf != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + result r = pBuf->Construct(size); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < strLen; i++) + { + pBuf->Set(str[i]); + } + + pBuf->Set(L'\0'); + pBuf->Flip(); + + return pBuf.release(); +} + +WcharBuffer* +StringUtil::StringToWcharBufferN(const String& str) +{ + SysTryReturn(NID_BASE_UTIL, !str.IsEmpty(), null, E_INVALID_ARG, "[%s] Invalid argument is used. The str is an empty string.", GetErrorMessage(E_INVALID_ARG)); + ClearLastResult(); + + int strLen = str.GetLength(); + int size = str.GetLength() + 1; + + std::unique_ptr< WcharBuffer > pBuf(new (std::nothrow) WcharBuffer()); + SysTryReturn(NID_BASE_UTIL, pBuf != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + result r = pBuf->Construct(size); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = 0; i < strLen; i++) + { + pBuf->Set(str[i]); + } + + pBuf->Set(L'\0'); + pBuf->Flip(); + + return pBuf.release(); +} + +McharBuffer* +StringUtil::StringToMbN(const String& str, int index, int length) +{ + SysTryReturn(NID_BASE_UTIL, !str.IsEmpty(), null, E_INVALID_ARG, "[%s] Invalid argument is used. The str is an empty string.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_BASE_UTIL, (index <= str.GetLength()) && (length <= (str.GetLength() - index)), null, E_OUT_OF_RANGE, "[%s] The index(%d) + length(%d) MUST be less than or equal to the length of str(%d).", GetErrorMessage(E_OUT_OF_RANGE), index, length, str.GetLength()); + SysTryReturn(NID_BASE_UTIL, index >= 0 && length >= 0, null, E_OUT_OF_RANGE, "[%s] The index(%d) and length(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), index, length); + ClearLastResult(); + + int size = str.GetLength() + 1; + + std::unique_ptr< McharBuffer > pBuf(new (std::nothrow) McharBuffer()); + SysTryReturn(NID_BASE_UTIL, pBuf != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + result r = pBuf->Construct(size); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = index; i < length; i++) + { + pBuf->Set(str[i]); + } + + pBuf->Set(L'\0'); + pBuf->Flip(); + + return pBuf.release(); +} + +WcharBuffer* +StringUtil::StringToWcharBufferN(const String& str, int index, int length) +{ + SysTryReturn(NID_BASE_UTIL, !str.IsEmpty(), null, E_INVALID_ARG, "[%s] Invalid argument is used. The str is an empty string.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_BASE_UTIL, (index <= str.GetLength()) && (length <= (str.GetLength() - index)), null, E_OUT_OF_RANGE, "[%s] The index(%d) + length(%d) MUST be less than or equal to the length of str(%d).", GetErrorMessage(E_OUT_OF_RANGE), index, length, str.GetLength()); + SysTryReturn(NID_BASE_UTIL, index >= 0 && length >= 0, null, E_OUT_OF_RANGE, "[%s] The index(%d) and length(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_OUT_OF_RANGE), index, length); + ClearLastResult(); + + int size = str.GetLength() + 1; + + std::unique_ptr< WcharBuffer > pBuf(new (std::nothrow) WcharBuffer()); + SysTryReturn(NID_BASE_UTIL, pBuf != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + result r = pBuf->Construct(size); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + for (int i = index; i < length; i++) + { + pBuf->Set(str[i]); + } + + pBuf->Set(L'\0'); + pBuf->Flip(); + + return pBuf.release(); +} + +int +StringUtil::GetStringLengthInMb(const McharBuffer& mb) +{ + int pBufferLimit = mb.GetLimit(); + for (int i = mb.GetPosition(); i < pBufferLimit; i++) + { + if (L'\0' == mb[i]) + { + return i - mb.GetPosition(); + } + } + return -1; +} + +int +StringUtil::GetStringLengthInWcharBuffer(const WcharBuffer& wb) +{ + int bufferLimit = wb.GetLimit(); + for (int i = wb.GetPosition(); i < bufferLimit; i++) + { + if (wb[i] == L'\0') + { + return i - wb.GetPosition(); + } + } + return -1; +} + +ByteBuffer* +StringUtil::StringToUtf8N(const String& unicodeString) +{ + SysTryReturn(NID_BASE_UTIL, !unicodeString.IsEmpty(), null, E_INVALID_ARG, "[%s] Invalid argument is used. The unicodeString is an empty string.", GetErrorMessage(E_INVALID_ARG)); + + _ICUConverter converter; + bool converted = converter.OpenConverter(L"UTF-8"); + SysTryReturn(NID_BASE_UTIL, converted, null, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + const wchar_t* pIn = unicodeString.GetPointer(); + int inpStrLen = unicodeString.GetLength(); + const wchar_t* pTmpBytePtr = pIn; + int retLength = 0; + + std::unique_ptr< char[] > pOutBuf(converter.ConvertFromUcharN(pTmpBytePtr, inpStrLen, retLength)); + result r = GetLastResult(); + SysTryReturn(NID_BASE_UTIL, pOutBuf != null, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + // allocate large enough outbuffer + std::unique_ptr< ByteBuffer > pEncodedBuf(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_BASE_UTIL, pEncodedBuf != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pEncodedBuf->Construct(retLength + 1); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = pEncodedBuf->SetArray(reinterpret_cast< const byte* >(pOutBuf.get()), 0, retLength + 1); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = pEncodedBuf->SetLimit(retLength + 1); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = pEncodedBuf->SetPosition(0); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, null, r, "[%s] Propagating.", GetErrorMessage(r)); + + SetLastResult(r); + converter.CloseConverter(); + + return pEncodedBuf.release(); +} + + +result +StringUtil::Utf8ToString(const char* pUtf8String, String& unicodeString) +{ + SysTryReturnResult(NID_BASE_UTIL, pUtf8String != null, E_INVALID_ARG, "The pUtf8String is null."); + ClearLastResult(); + + _ICUConverter converter; + + bool converted = converter.OpenConverter(L"UTF-8"); + SysTryReturnResult(NID_BASE_UTIL, converted, GetLastResult(), "Propagating."); + + int srcLen = strlen(pUtf8String); + std::unique_ptr< wchar_t[] > pDst(converter.ConvertToUcharN(pUtf8String, srcLen)); + result r = GetLastResult(); + SysTryReturnResult(NID_BASE_UTIL, pDst != null, r, "Propagating."); + unicodeString.Clear(); + unicodeString.Append(pDst.get()); + return r; +} + + +ByteBuffer* +StringUtil::DecodeBase64StringN(const String& base64String) +{ + SysTryReturn(NID_BASE_UTIL, !base64String.IsEmpty(), null, E_INVALID_ARG, "[%s] Invalid argument is used. The base64String is an empty string.", GetErrorMessage(E_INVALID_ARG)); + ClearLastResult(); + + const char* pPos = null; + unsigned char c = 0x0; + byte* pByte = null; + int prevTableValue = 0; + size_t mblen = 0; + int index = 0; + int tableValue = 0; + int paddingCnt = 0; + int phase = 0; + + char decBuf[base64String.GetLength() * sizeof(wchar_t)]; + mblen = wcstombs(decBuf, (wchar_t*) base64String.GetPointer(), base64String.GetLength() * sizeof(wchar_t)); + if (mblen == (size_t) -1) + { + SetLastResult(E_INVALID_ARG); + return null; + } + + int decLen = ((mblen + 3) / 4) * 3; + SysTryReturn(NID_BASE_UTIL, decLen >= 0, null, E_INVALID_ARG, "[%s] decLen must be greater than 0.", GetErrorMessage(E_INVALID_ARG)); + + std::unique_ptr< char[] > pOutBuf((char*) new (std::nothrow) char[decLen + 1]); + SysTryReturn(NID_BASE_UTIL, pOutBuf != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + for (pPos = decBuf; *pPos != '\0'; ++pPos) + { + tableValue = Base64DecodingTable[(int) *pPos]; + + if (*pPos == '=') + { + paddingCnt++; + } + if (tableValue != -1) + { + switch (phase) + { + case 0: + ++phase; + break; + + case 1: + c = ((prevTableValue << 2) | ((tableValue & 0x30) >> 4)); + pOutBuf[index++] = c; + ++phase; + break; + + case 2: + c = (((prevTableValue & 0xf) << 4) | ((tableValue & 0x3c) >> 2)); + pOutBuf[index++] = c; + ++phase; + break; + + case 3: + c = (((prevTableValue & 0x03) << 6) | tableValue); + pOutBuf[index++] = c; + phase = 0; + break; + } + prevTableValue = tableValue; + } + } + pOutBuf[index] = '\0'; + + paddingCnt += (index % 3); + if ((paddingCnt % 3) != 0) + { + SetLastResult(E_INVALID_ARG); + return null; + } + pByte = (byte*) pOutBuf.get(); + + std::unique_ptr< ByteBuffer > pBuffer(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_BASE_UTIL, pBuffer != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = pBuffer->Construct(index + 1); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), null, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = pBuffer->SetArray(pByte, 0, index); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), null, r, "[%s] Propagating.", GetErrorMessage(r)); + + pBuffer->Flip(); + + SetLastResult(r); + return pBuffer.release(); +} + + +result +StringUtil::EncodeToBase64String(const ByteBuffer& buffer, String& encodedString) +{ + ClearLastResult(); + + unsigned char input[3] = {0, 0, 0}; + unsigned char output[4] = {0, 0, 0, 0}; + wchar_t* pEncodedBuf = null; + char* pCurPos = null; + char* pLen = null; + byte* pBuf = null; + int stringCnt = 0; + int loopCnt = 0; + int index = 0; + + int size = buffer.GetRemaining(); + SysTryReturnResult(NID_BASE_UTIL, size > 0, E_INVALID_ARG, "The buffer is empty."); + pBuf = (byte*) (buffer.GetPointer() + buffer.GetPosition()); + + //move to the last character + pLen = (char*) pBuf + size - 1; + + int encLen = (4 * (size / 3)) + (size % 3 ? 4 : 0); + SysTryReturnResult(NID_BASE_UTIL, encLen >= 0, E_INVALID_ARG, "encLen must be greater than 0."); + + result r = encodedString.SetLength(encLen); + if (!IsFailed(r)) + { + pEncodedBuf = (wchar_t*) encodedString.GetPointer(); + + for (loopCnt = 0, pCurPos = (char*) pBuf; pCurPos <= pLen; loopCnt++, pCurPos++) + { + index = loopCnt % 3; + input[index] = *pCurPos; + + if (index == 2 || pCurPos == pLen) + { + output[0] = ((input[0] & 0xFC) >> 2); + output[1] = ((input[0] & 0x3) << 4) | ((input[1] & 0xF0) >> 4); + output[2] = ((input[1] & 0xF) << 2) | ((input[2] & 0xC0) >> 6); + output[3] = (input[2] & 0x3F); + + pEncodedBuf[stringCnt++] = Base64EncodingTable[output[0]]; + pEncodedBuf[stringCnt++] = Base64EncodingTable[output[1]]; + pEncodedBuf[stringCnt++] = index == 0 ? '=' : Base64EncodingTable[output[2]]; + pEncodedBuf[stringCnt++] = index < 2 ? '=' : Base64EncodingTable[output[3]]; + + input[0] = 0; + input[1] = 0; + input[2] = 0; + } + } + pEncodedBuf[stringCnt] = L'\0'; + } + + return r; +} +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilUri.cpp b/src/base/utility/FBaseUtilUri.cpp new file mode 100644 index 0000000..87d6d37 --- /dev/null +++ b/src/base/utility/FBaseUtilUri.cpp @@ -0,0 +1,3648 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilUri.cpp + * @brief This is the implementation file for Uri class. + */ + +// Includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +static const wchar_t HEX_DIGITS[] = {L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7', L'8', L'9', L'A', L'B', L'C', L'D', L'E', L'F'}; + + +///////////////////////////////////////////////////////////////////////////////// +// Life-cycle + +Uri::Uri(void) + : __port(-1) + , __hasScheme(false) + , __ipv6ByteCount(0) + , __pUriImpl(null) +{ +} + + +Uri::Uri(const Uri& uri) + : __pUriImpl(null) +{ + SetUri(uri); +} + + +Uri::~Uri(void) +{ + Clear(); +} + + +void +Uri::SetUri(const Uri& uri) +{ + __scheme = uri.__scheme; + __ssp = uri.__ssp; + __authority = uri.__authority; + __host = uri.__host; + __fragment = uri.__fragment; + __path = uri.__path; + __userInfo = uri.__userInfo; + __query = uri.__query; + __ipv4 = uri.__ipv4; + __ipv6 = uri.__ipv6; + + __encodedAuth = uri.__encodedAuth; + __encodedFragment = uri.__encodedFragment; + __encodedPath = uri.__encodedPath; + __encodedQuery = uri.__encodedQuery; + __encodedSsp = uri.__encodedSsp; + __encodedUserInfo = uri.__encodedUserInfo; + + __port = uri.__port; + __hasScheme = uri.__hasScheme; + __ipv6ByteCount = uri.__ipv6ByteCount; +} + + +result +Uri::SetUri(const Tizen::Base::String& str) +{ + SysTryReturn(NID_BASE_UTIL, str.GetLength() > 0, E_INVALID_ARG, E_INVALID_ARG, "[%s] Invalid argument is used. An empty String.", GetErrorMessage(E_INVALID_ARG)); + + Clear(); + + result r = ParseUri(str); + if (IsFailed(r)) + { + return r; + } + + return E_SUCCESS; +} + + +result +Uri::SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& ssp, const Tizen::Base::String& fragment) +{ + String empty; + + // scheme, ssp(opaquePart), authority, user-info, host, port, path, query, fragment + return SetUri(scheme, ssp, empty, empty, empty, -1, empty, empty, fragment); +} + + +result +Uri::SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& userInfo, const Tizen::Base::String& host, int port, + const Tizen::Base::String& path, const Tizen::Base::String& query, + const Tizen::Base::String& fragment) +{ + String empty; + + // scheme, ssp(opaquePart), authority, user-info, host, port, path, query, fragment + return SetUri(scheme, empty, empty, userInfo, host, port, path, query, fragment); +} + + +result +Uri::SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& host, const Tizen::Base::String& path, + const Tizen::Base::String& fragment) +{ + String empty; + + // scheme, ssp(opaquePart), authority, user-info, host, port, path, query, fragment + return SetUri(scheme, empty, empty, empty, host, -1, path, L"", fragment); +} + + +result +Uri::SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& authority, const Tizen::Base::String& path, + const Tizen::Base::String& query, + const Tizen::Base::String& fragment) +{ + String empty; + + // scheme, ssp(opaquePart), authority, user-info, host, port, path, query, fragment + return SetUri(scheme, empty, authority, empty, empty, -1, path, query, fragment); +} + + +//////////////////////////////////////////////////////////////////////////////// +/// Operator + +Uri& +Uri::operator =(const Uri& rhs) +{ + if (&rhs != this) + { + SetUri(rhs); + } + return *this; +} + + +//////////////////////////////////////////////////////////////////////////////// +// Accessor + +Tizen::Base::String +Uri::GetAuthority(void) const +{ + return __authority; +} + + +Tizen::Base::String +Uri::GetFragment(void) const +{ + return __fragment; +} + + +Tizen::Base::String +Uri::GetHost(void) const +{ + return __host; +} + + +Tizen::Base::String +Uri::GetPath(void) const +{ + return __path; +} + + +int +Uri::GetPort(void) const +{ + return __port; +} + + +Tizen::Base::String +Uri::GetQuery(void) const +{ + return __query; +} + + +Tizen::Base::String +Uri::GetScheme(void) const +{ + return __scheme; +} + + +Tizen::Base::String +Uri::GetSchemeSpecificPart(void) const +{ + return __ssp; +} + + +Tizen::Base::String +Uri::GetUserInfo(void) const +{ + return __userInfo; +} + + +Tizen::Base::String +Uri::GetEncodedAuthority(void) const +{ + return __encodedAuth; +} + + +Tizen::Base::String +Uri::GetEncodedFragment(void) const +{ + return __encodedFragment; +} + + +Tizen::Base::String +Uri::GetEncodedPath(void) const +{ + return __encodedPath; +} + + +Tizen::Base::String +Uri::GetEncodedQuery(void) const +{ + return __encodedQuery; +} + + +Tizen::Base::String +Uri::GetEncodedSchemeSpecificPart(void) const +{ + return __encodedSsp; +} + + +Tizen::Base::String +Uri::GetEncodedUserInfo(void) const +{ + return __encodedUserInfo; +} + + +bool +Uri::IsAbsolute(void) const +{ + // If the URI has a scheme, then it is an absolute URI. + if (__hasScheme) + { + return true; + } + else + { + return false; + } +} + + +bool +Uri::IsOpaque(void) const +{ + String scheme = GetScheme(); + String ssp = GetSchemeSpecificPart(); + + if (scheme.IsEmpty()) + { + return false; + } + + if (!ssp.IsEmpty()) + { + if (ssp[0] == L'/') + { + return false; + } + else + { + return true; + } + } + else + { + return false; + } +} + + +Tizen::Base::String +Uri::GetEncodedString(void) const +{ + String strbuf; + + // Scheme + if (!__scheme.IsEmpty()) + { + strbuf.Append(__scheme); + strbuf.Append(L':'); + } + + //AppendSchemeSpecificPart(strbuf, __encodedSsp, __encodedAuth, __encodedUserInfo, __host, __port, __encodedPath, __encodedQuery); + if (!__encodedSsp.IsEmpty()) + { + strbuf.Append(__encodedSsp); + } + else + { + //r = AppendAuthority(strbuf, __authority, __userInfo, __host, __port); + if (!__host.IsEmpty()) + { + // Check the Host + strbuf.Append(L"//"); + + // Check the Userinfo + if (!__encodedUserInfo.IsEmpty()) + { + strbuf.Append(__encodedUserInfo); + strbuf.Append(L'@'); + } + + int indexOf = 0; + result re = E_SUCCESS; + re = __host.IndexOf(L':', 0, indexOf); + + String openBracket(L"["); + String closeBracket(L"]"); + + bool start = __host.StartsWith(openBracket, 0); + bool end = __host.EndsWith(closeBracket); + + bool needBracket = false; + if (!start && !end && re == E_SUCCESS) + { + needBracket = true; + } + else + { + needBracket = false; + } + + if (needBracket) + { + strbuf.Append(L'['); + } + + strbuf.Append(__host); + + if (needBracket) + { + strbuf.Append(L']'); + } + + // Check the port + if (__port >= 0) + { + strbuf.Append(L':'); + strbuf.Append(__port); + } + } + else if (!__encodedAuth.IsEmpty()) + { + strbuf.Append(L"//"); + strbuf.Append(__encodedAuth); + } + // AppendAuthority end + + + if (!__encodedPath.IsEmpty()) + { + strbuf.Append(__encodedPath); + } + + if (!__encodedQuery.IsEmpty()) + { + strbuf.Append(L'?'); + strbuf.Append(__encodedQuery); + } + } + // AppendSchemeSpecificPart end + + + //AppendFragment(strbuf, __encodedFragment); + if (!__encodedFragment.IsEmpty()) + { + strbuf.Append(L'#'); + strbuf.Append(__encodedFragment); + } + // AppendFragment end + + return strbuf; +} + + +//////////////////////////////////////////////////////////////////////////////////////////// +// Operations + +int +Uri::CompareTo(const Uri& uri) const +{ + bool thisOpaque = false; + bool thatOpaque = false; + + String query; + String otherQuery; + String path; + String otherPath; + String host; + String otherHost; + String fragment; + String otherFragment; + int ret = 0; + + ////////////////////////////////////////////////// + // Opaque // + ///////////////////////////////////////////////// + thisOpaque = IsOpaque(); + thatOpaque = uri.IsOpaque(); + + // Both the current instance and a given instance are opaque + if (thisOpaque && thatOpaque) + { + // Compare Scheme-specific-part + ret = Compare(__ssp, uri.__ssp); + + if (ret != 0) + { + return ret; + } + + // compare fragment + ret = Compare(__fragment, uri.__fragment); + + return ret; + + } + else if (thisOpaque && !thatOpaque) + { + return 1; + } + else if (!thisOpaque && thatOpaque) + { + return -1; + } + + + ////////////////////////////////////////////////// + // Hierarchical // + ///////////////////////////////////////////////// + if (!__host.IsEmpty() && !uri.__host.IsEmpty()) + { + // Server-based URI + // Compare User-info + ret = Compare(__userInfo, uri.__userInfo); + + if (ret != 0) + { + return ret; + } + + // Compare host + ret = Compare(__host, uri.__host); + + if (ret != 0) + { + return ret; + } + + // Compare port + int portDiff = __port - uri.__port; + if (portDiff > 0) + { + return 1; + } + else if (portDiff == 0) + { + ret = 0; + } + else + { + return -1; + } + } + else + { + // If one of them is registry-based URI, then compare authority. + ret = Compare(__authority, uri.__authority); + + if (ret != 0) + { + return ret; + } + } + + // Compare path + ret = Compare(__path, uri.__path); + if (ret != 0) + { + return ret; + } + + // Compare query + ret = Compare(__query, uri.__query); + if (ret != 0) + { + return ret; + } + + // Compare fragment + ret = Compare(__fragment, uri.__fragment); + + return ret; +} + + +bool +Uri::Equals(const Tizen::Base::Object& obj) const +{ + // Check that obj is an Uri instance. + const Uri* pOther = dynamic_cast (&obj); + if (pOther == null) + { + return false; + } + + int ret = CompareTo(*pOther); + if (ret != 0) + { + return false; + } + + return true; +} + + +int +Uri::GetHashCode(void) const +{ + return ToString().GetHashCode(); +} + + +Uri +Uri::Normalize(void) +{ + result r = E_SUCCESS; + Uri resultUri; + + // If the current instance is opaque or the path of the current instance is undefined or an empty string, + // return itself. + if (__path.IsEmpty() || IsOpaque()) + { + return *this; + } + + String normalizedUri; + normalizedUri = InternalNormalize(__path); + if (normalizedUri == __path || GetLastResult() == E_INVALID_ARG) + { + return *this; + } + + if (!__scheme.IsEmpty()) + { + r = resultUri.SetScheme(__scheme); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), *this, r, "[%s] : Failed to set scheme.", GetErrorMessage(r)); + } + + if (!__fragment.IsEmpty()) + { + r = resultUri.SetFragment(__fragment); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), *this, r, "[%s] : Failed to set fragment.", GetErrorMessage(r)); + } + + if (!__authority.IsEmpty()) + { + r = resultUri.SetAuthority(__authority); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), *this, r, "[%s] : Failed to set authority.", GetErrorMessage(r)); + } + + if (!__userInfo.IsEmpty()) + { + r = resultUri.SetUserInfo(__userInfo); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), *this, r, "[%s] : Failed to set userinfo.", GetErrorMessage(r)); + } + + if (!__host.IsEmpty()) + { + r = resultUri.SetHost(__host); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), *this, r, "[%s] : Failed to set host.", GetErrorMessage(r)); + } + + resultUri.SetPort(__port); + + r = resultUri.SetPath(normalizedUri); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), *this, r, "[%s] : Failed to set path.", GetErrorMessage(r)); + + if (!__query.IsEmpty()) + { + r = resultUri.SetQuery(__query); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), *this, r, "[%s] : Failed to set query.", GetErrorMessage(r)); + } + + return resultUri; +} + + +result +Uri::ParseAuthority(Uri& uri) +{ + result r = E_SUCCESS; + + if (!__host.IsEmpty() || __authority.IsEmpty()) + { + uri = *this; + return r; + } + + String str = ToString(); + + Uri tempUri; + r = tempUri.SetUri(str); + + if (IsFailed(r)) + { + return r; + } + + r = ParseServerAuthority(str, tempUri.__host, tempUri.__userInfo, tempUri.__port); + if (IsFailed(r)) + { + return r; + } + + uri = tempUri; + + return r; +} + + +result +Uri::Relativize(const Uri& uri, Uri& resultUri) +{ + return Relativize(*this, uri, resultUri); +} + + +result +Uri::Resolve(const Uri& uri, Uri& resultUri) +{ + return Resolve(*this, uri, resultUri); +} + + +result +Uri::SetAuthority(const Tizen::Base::String& authority) +{ + bool isAuth = VerifyAuthority(authority); + + SysTryReturn(NID_BASE_UTIL, isAuth, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Authority.", GetErrorMessage(E_INVALID_FORMAT)); + + if (IsEncoded(authority)) + { + __encodedAuth = authority; + __authority = Decode(authority); + } + else + { + __authority = authority; + __encodedAuth = Encode(authority); + } + + return E_SUCCESS; +} + + +result +Uri::SetFragment(const Tizen::Base::String& fragment) +{ + bool isFragment = VerifyUriChar(fragment); + + SysTryReturn(NID_BASE_UTIL, isFragment, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Fragment.", GetErrorMessage(E_INVALID_FORMAT)); + + if (IsEncoded(fragment)) + { + __encodedFragment = fragment; + __fragment = Decode(fragment); + } + else + { + __fragment = fragment; + __encodedFragment = Encode(fragment); + } + + return E_SUCCESS; +} + + +result +Uri::SetHost(const Tizen::Base::String& host) +{ + bool isHost = VerifyHost(host); + + SysTryReturn(NID_BASE_UTIL, isHost, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Host.", GetErrorMessage(E_INVALID_FORMAT)); + + __host = host; + + return E_SUCCESS; +} + + +result +Uri::SetPath(const Tizen::Base::String& path) +{ + bool isPath = VerifyPath(path); + + SysTryReturn(NID_BASE_UTIL, isPath, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Path.", GetErrorMessage(E_INVALID_FORMAT)); + + if (IsEncoded(path)) + { + __encodedPath = path; + __path = Decode(path); + } + else + { + __path = path; + __encodedPath = Encode(path); + } + + return E_SUCCESS; +} + + +result +Uri::SetPort(int port) +{ + SysTryReturn(NID_BASE_UTIL, port >= 0, E_INVALID_ARG, E_INVALID_ARG, "[%s] Invalid argument is used. The port(%d) MUST be greater than or equal to 0.", GetErrorMessage(E_INVALID_ARG), port); + + __port = port; + + return E_SUCCESS; +} + + +result +Uri::SetQuery(const Tizen::Base::String& query) +{ + bool isQuery = VerifyUriChar(query); + + SysTryReturn(NID_BASE_UTIL, isQuery, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Query.", GetErrorMessage(E_INVALID_FORMAT)); + + if (IsEncoded(query)) + { + __encodedQuery = query; + __query = Decode(query); + } + else + { + __query = query; + __encodedQuery = Encode(query); + } + + return E_SUCCESS; +} + + +result +Uri::SetScheme(const Tizen::Base::String& scheme) +{ + bool isScheme = VerifyScheme(scheme); + + SysTryReturn(NID_BASE_UTIL, isScheme, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Scheme.", GetErrorMessage(E_INVALID_FORMAT)); + + __scheme = scheme; + + return E_SUCCESS; +} + + +result +Uri::SetSchemeSpecificPart(const Tizen::Base::String& ssp) +{ + bool isSsp = VerifyUriChar(ssp); + + SysTryReturn(NID_BASE_UTIL, isSsp, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid SchemeSpecificPart.", GetErrorMessage(E_INVALID_FORMAT)); + + if (IsEncoded(ssp)) + { + __encodedSsp = ssp; + __ssp = Decode(ssp); + } + else + { + __ssp = ssp; + __encodedSsp = Encode(ssp); + } + + return E_SUCCESS; +} + + +result +Uri::SetUserInfo(const Tizen::Base::String& userInfo) +{ + bool isUserInfo = VerifyUserInfo(userInfo); + + SysTryReturn(NID_BASE_UTIL, isUserInfo, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid UserInfo.", GetErrorMessage(E_INVALID_FORMAT)); + + if (IsEncoded(userInfo)) + { + __encodedUserInfo = userInfo; + __userInfo = Decode(userInfo); + } + else + { + __userInfo = userInfo; + __encodedUserInfo = Encode(userInfo); + } + + return E_SUCCESS; +} + + +Tizen::Base::String +Uri::ToString(void) const +{ + String strbuf; + + // Scheme + if (!__scheme.IsEmpty()) + { + strbuf.Append(__scheme); + strbuf.Append(L':'); + } + + //AppendSchemeSpecificPart(strbuf, __ssp, __authority, __userInfo, __host, __port, __path, __query); + if (IsOpaque()) + { + strbuf.Append(__ssp); + } + else + { + //r = AppendAuthority(strbuf, __authority, __userInfo, __host, __port); + if (!__host.IsEmpty()) + { + // Check the Host + strbuf.Append(L"//"); + + // Check the Userinfo + if (!__userInfo.IsEmpty()) + { + strbuf.Append(__userInfo); + strbuf.Append(L'@'); + } + + int indexOf = 0; + result re = E_SUCCESS; + re = __host.IndexOf(L':', 0, indexOf); + + String openBracket(L"["); + String closeBracket(L"]"); + + bool start = __host.StartsWith(openBracket, 0); + bool end = __host.EndsWith(closeBracket); + + bool needBracket = false; + if (!start && !end && re == E_SUCCESS) + { + needBracket = true; + } + else + { + needBracket = false; + } + + if (needBracket) + { + strbuf.Append(L'['); + } + + strbuf.Append(__host); + + if (needBracket) + { + strbuf.Append(L']'); + } + + // Check the port + if (__port >= 0) + { + strbuf.Append(L':'); + strbuf.Append(__port); + } + } + else if (!__authority.IsEmpty()) + { + strbuf.Append(L"//"); + strbuf.Append(__authority); + } + // AppendAuthority end + + + if (!__path.IsEmpty()) + { + strbuf.Append(__path); + } + + if (!__query.IsEmpty()) + { + strbuf.Append(L'?'); + strbuf.Append(__query); + } + } + // AppendSchemeSpecificPart end + + + //AppendFragment(strbuf, __fragment); + if (!__fragment.IsEmpty()) + { + strbuf.Append(L'#'); + strbuf.Append(__fragment); + } + // AppendFragment end + + return strbuf; +} + + +//////////////////////////////////////////////////////////////////////// +// Private methods + +// +// This method constructs an URI instance. +// +result +Uri::SetUri(const Tizen::Base::String& scheme, const Tizen::Base::String& opaque, const Tizen::Base::String& authority, + const Tizen::Base::String& userInfo, const Tizen::Base::String& host, int port, const Tizen::Base::String& path, + const Tizen::Base::String& query, + const Tizen::Base::String& fragment) +{ + result r = E_SUCCESS; + String fullUri; + String strbuf; + + // Scheme + if (!scheme.IsEmpty()) + { + // Check that an extracted scheme is satisfied with RFC2396. + bool isScheme = VerifyScheme(scheme); + if (!isScheme) + { + r = E_INVALID_FORMAT; + goto CATCH; + } + + r = strbuf.Append(scheme); + if (IsFailed(r)) + { + goto CATCH; + } + + r = strbuf.Append(L':'); + if (IsFailed(r)) + { + goto CATCH; + } + } + + r = AppendSchemeSpecificPart(strbuf, opaque, authority, userInfo, host, port, path, query); + if (IsFailed(r)) + { + goto CATCH; + } + + r = AppendFragment(strbuf, fragment); + if (IsFailed(r)) + { + goto CATCH; + } + + fullUri = strbuf; + + r = SetUri(fullUri); + if (IsFailed(r)) + { + goto CATCH; + } + +CATCH: + return r; +} + + +result +Uri::AppendSchemeSpecificPart(Tizen::Base::String& strbuf, const Tizen::Base::String& opaque, const Tizen::Base::String& authority, + const Tizen::Base::String& userInfo, const Tizen::Base::String& host, int port, + const Tizen::Base::String& path, + const Tizen::Base::String& query) const +{ + result r = E_SUCCESS; + // Opaque part + if (!opaque.IsEmpty()) + { + if (VerifyUriChar(opaque)) + { + r = strbuf.Append(opaque); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + else + { + r = AppendAuthority(strbuf, authority, userInfo, host, port); + if (IsFailed(r)) + { + goto CATCH; + } + + if (!path.IsEmpty()) + { + if (VerifyPath(path)) + { + r = strbuf.Append(path); + } + else + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + + if (!query.IsEmpty()) + { + if (VerifyUriChar(query)) + { + r = strbuf.Append(L'?'); + if (IsFailed(r)) + { + goto CATCH; + } + + r = strbuf.Append(query); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + } + +CATCH: + return r; +} + + +result +Uri::AppendFragment(Tizen::Base::String& strbuf, const Tizen::Base::String& fragment) const +{ + result r = E_SUCCESS; + if (!fragment.IsEmpty()) + { + bool isFragment = VerifyUriChar(fragment); + if (isFragment) + { + r = strbuf.Append(L'#'); + if (IsFailed(r)) + { + goto CATCH; + } + + r = strbuf.Append(fragment); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + +CATCH: + return r; +} + + +result +Uri::AppendAuthority(Tizen::Base::String& strbuf, const Tizen::Base::String& authority, const Tizen::Base::String& userInfo, + const Tizen::Base::String& host, + int port) const +{ + result r = E_SUCCESS; + + String doubleSlash(L"//"); + + if (!host.IsEmpty()) + { + // Check the Host + bool isHost = VerifyHost(host); + if (!isHost) + { + r = E_INVALID_FORMAT; + goto CATCH; + } + + r = strbuf.Append(doubleSlash); + if (IsFailed(r)) + { + goto CATCH; + } + + // Check the Userinfo + if (!userInfo.IsEmpty()) + { + bool user = VerifyUserInfo(userInfo); + if (user) + { + r = strbuf.Append(userInfo); + if (IsFailed(r)) + { + goto CATCH; + } + + r = strbuf.Append(L'@'); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + + int indexOf = 0; + result re = E_SUCCESS; + re = host.IndexOf(L':', 0, indexOf); + //if (IsFailed(r)) goto CATCH; + + String openBracket(L"["); + String closeBracket(L"]"); + + bool start = host.StartsWith(openBracket, 0); + bool end = host.EndsWith(closeBracket); + + bool needBracket = true; + if (!start && !end && re == E_SUCCESS) + { + needBracket = true; + } + else + { + needBracket = false; + } + + if (needBracket) + { + r = strbuf.Append(L'['); + if (IsFailed(r)) + { + goto CATCH; + } + } + + r = strbuf.Append(host); + if (IsFailed(r)) + { + goto CATCH; + } + + if (needBracket) + { + r = strbuf.Append(L']'); + if (IsFailed(r)) + { + goto CATCH; + } + } + + // Check the port + if (port >= 0) + { + r = strbuf.Append(L':'); + if (IsFailed(r)) + { + goto CATCH; + } + + r = strbuf.Append(port); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + if (port != -1) + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + } + else if (!authority.IsEmpty()) + { + r = strbuf.Append(doubleSlash); + if (IsFailed(r)) + { + goto CATCH; + } + + bool auth = VerifyAuthority(authority); + if (auth) + { + r = strbuf.Append(authority); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + +CATCH: + return r; +} + + +// +// This method breaks a given string into Uri components. +// str : [scheme:][#] +// +result +Uri::ParseUri(const Tizen::Base::String& str) +{ + result r = E_SUCCESS; + wchar_t colon = L':'; + wchar_t sharp = L'#'; + int indexOf = 0; + int startSsp = 0; + int curIndex = 0; // points the current index + int startFragment = 0; + int lengthOfUri = str.GetLength(); + + String authority; + String path; + String query; + + ///////////////////////////////////////////////////////////////// + // First, exract a scheme component from a given string.// + //////////////////////////////////////////////////////////////// + + // Check the space + SysTryReturn(NID_BASE_UTIL, str[0] != L' ', E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Scheme.", GetErrorMessage(E_INVALID_FORMAT)); + + // Get a index of ':' + r = str.IndexOf(colon, 0, indexOf); + if (indexOf >= 0 && r == E_SUCCESS) + { + // There is a scheme componenet. + String scheme; + r = str.SubString(0, indexOf, scheme); + SysTryCatch(NID_BASE_UTIL, r == E_SUCCESS, , r, "[%s] Propagating.", GetErrorMessage(r)); + + // Check that an extracted scheme is satisfied with RFC2396. + bool isScheme = VerifyScheme(scheme); + + SysTryReturn(NID_BASE_UTIL, isScheme, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Scheme.", GetErrorMessage(E_INVALID_FORMAT)); + + curIndex = indexOf; + __scheme = scheme; + __hasScheme = true; + } + else + { + // In case there is no scheme component, the Uri is a hierarchical URI. + startSsp = 0; + __hasScheme = false; + } + + //////////////////////////////////////////////////////////////////////// + // Second, extract a scheme-specific-part from a given string.// + /////////////////////////////////////////////////////////////////////// + if (__hasScheme) // This URI has a scheme. + { + startSsp = ++curIndex; // skip ':' + if (startSsp >= lengthOfUri) + { + r = E_INVALID_FORMAT; + goto CATCH; + } + + if (str[startSsp] == '/') + { + // Hierarchical URI + r = ParseHierarchicalUri(str, startSsp, authority, path, query, curIndex); + if (IsFailed(r)) + { + goto CATCH; + } + + SetAndEncodeAuthority(authority, path, query); + + String ssp; + r = str.SubString(startSsp, curIndex - startSsp, ssp); + if (IsFailed(r)) + { + goto CATCH; + } + + if (IsEncoded(ssp)) + { + __ssp = Decode(ssp); + __encodedSsp = ssp; + } + else + { + __ssp = ssp; + __encodedSsp = Encode(ssp); + } + + } + else + { + // Opaque URI + String ssp; + + r = str.IndexOf(sharp, curIndex, (int&)startFragment); + if (startFragment > curIndex && r == E_SUCCESS) + { + r = str.SubString(startSsp, startFragment - curIndex, ssp); + if (IsFailed(r)) + { + goto CATCH; + } + } + else if (r == E_OBJ_NOT_FOUND) + { + startFragment = 0; + r = str.SubString(startSsp, lengthOfUri - curIndex, ssp); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + goto CATCH; + } + + bool isOpaque = VerifyUriChar(ssp); + + SysTryReturn(NID_BASE_UTIL, isOpaque, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Opaque URI.", GetErrorMessage(E_INVALID_FORMAT)); + + // Opaque URI is not subject to further parsing. + if (IsEncoded(ssp)) + { + __ssp = Decode(ssp); + __encodedSsp = ssp; + } + else + { + __ssp = ssp; + __encodedSsp = Encode(ssp); + } + + if (startFragment == 0) + { + return E_SUCCESS; + } + + // Check the fragment + String fragment; + + startFragment++; + r = str.SubString(startFragment, lengthOfUri - startFragment, fragment); + if (IsFailed(r)) + { + goto CATCH; + } + + bool isFragment = VerifyUriChar(fragment); + + SysTryReturn(NID_BASE_UTIL, isFragment, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Fragment.", GetErrorMessage(E_INVALID_FORMAT)); + + if (IsEncoded(fragment)) + { + __fragment = Decode(fragment); + __encodedFragment = fragment; + } + else + { + __fragment = fragment; + __encodedFragment = Encode(fragment); + } + + return E_SUCCESS; + } + } + else // This URI doesn't have a Scheme. - www.samsung.com[#ocean] + { + startSsp = 0; + + r = ParseHierarchicalUri(str, startSsp, authority, path, query, curIndex); + if (IsFailed(r)) + { + goto CATCH; + } + + String ssp; + r = str.SubString(startSsp, curIndex - startSsp, ssp); + if (IsFailed(r)) + { + goto CATCH; + } + + if (IsEncoded(ssp)) + { + __ssp = Decode(ssp); + __encodedSsp = ssp; + } + else + { + __ssp = ssp; + __encodedSsp = Encode(ssp); + } + + SetAndEncodeAuthority(authority, path, query); + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Parse an authority component. The authority component is registry_based or server_based authority.// + // Server_based authority consists of user-info, host and port. // + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + if (!authority.IsEmpty()) + { + String userInfo; + String host; + int port = 0; + + String newAuth; + r = ParseAuthority(authority, curIndex, newAuth, userInfo, host, port); + if (IsFailed(r)) + { + goto CATCH; + } + + if (!userInfo.IsEmpty()) + { + if (IsEncoded(userInfo)) + { + __userInfo = Decode(userInfo); + __encodedUserInfo = userInfo; + } + else + { + __userInfo = userInfo; + __encodedUserInfo = Encode(userInfo); + } + } + + if (!host.IsEmpty()) + { + __host = host; + } + + __port = port; + } + + ///////////////////////////////////////////////// + // Finally, extract a fragment component // + //////////////////////////////////////////////// + startFragment = curIndex; + if (startFragment < lengthOfUri && str[startFragment] == '#') + { + startFragment++; + String fragment; + + r = str.SubString(startFragment, lengthOfUri - startFragment, fragment); + if (IsFailed(r)) + { + goto CATCH; + } + + bool isFragment = VerifyUriChar(fragment); + + SysTryReturn(NID_BASE_UTIL, isFragment, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Fragment.", GetErrorMessage(E_INVALID_FORMAT)); + + if (IsEncoded(fragment)) + { + __fragment = Decode(fragment); + __encodedFragment = fragment; + } + else + { + __fragment = fragment; + __encodedFragment = Encode(fragment); + } + + // curIndex = lengthOfUri; + curIndex += fragment.GetLength() + 1; // skip '#' + } + + if (curIndex < lengthOfUri) + { + // Invalid URI format + r = E_INVALID_FORMAT; + goto CATCH; + } + + // Convert Unicode string to UTF8 string when there is a wchar_t which is greater than 0x0080. + // authority fragment path query ssp + //EncodeAllComponent(); +CATCH: + return r; +} + + +void +Uri::SetAndEncodeAuthority(const Tizen::Base::String& authority, const Tizen::Base::String& path, const Tizen::Base::String& query) +{ + bool isEncoded = false; + + //// Authority //// + if (!authority.IsEmpty()) + { + isEncoded = IsEncoded(authority); + if (isEncoded) + { + __authority = Decode(authority); + __encodedAuth = authority; + } + else + { + __authority = authority; + __encodedAuth = Encode(authority); + } + } + + //// Path //// + if (!path.IsEmpty()) + { + isEncoded = IsEncoded(path); + if (isEncoded) + { + __path = Decode(path); + __encodedPath = path; + } + else + { + __path = path; + __encodedPath = Encode(path); + } + } + + //// Query //// + if (!query.IsEmpty()) + { + isEncoded = IsEncoded(query); + if (isEncoded) + { + __query = Decode(query); + __encodedQuery = query; + } + else + { + __query = query; + __encodedQuery = Encode(query); + } + } +} + + +result +Uri::ParseHierarchicalUri(const Tizen::Base::String& str, int startSsp, Tizen::Base::String& authority, Tizen::Base::String& path, + Tizen::Base::String& query, + int& index) +{ + result r = E_SUCCESS; + int curIndex = startSsp; +// bool isServerAuth; + + String tempPath; + String queSharp(L"?#"); + String doubleSlash(L"//"); + + bool startsWith = str.StartsWith(doubleSlash, curIndex); + + int position = 0; + bool isPath = false; + int temp = 0; + + if (startsWith) + { + curIndex += 2; +// int indexOf; + + String special(L"/?#"); + + int index = Scan(str, curIndex, special); + if (index > (int) curIndex) + { + r = str.SubString(curIndex, index - curIndex, authority); + if (IsFailed(r)) + { + goto CATCH; + } + + //bool isServer; + //r = ParseAuthority(str, curIndex, isServer); + //if (IsFailed(r)) goto CATCH; + } + else if (index < (int) str.GetLength()) + { + // allow an empty authority +// authority = String::Empty(); + // empty statement + } + else + { + r = E_INVALID_FORMAT; + goto CATCH; + } + curIndex += authority.GetLength(); + } + + r = queSharp.IndexOf(str[0], 0, temp); + if (r == E_SUCCESS) + { + position = 0; + } + else + { + position = Scan(str, curIndex, queSharp); // may be empty + if (position < 0) + { + r = E_INVALID_FORMAT; + goto CATCH; + } + + if (position == curIndex) + { + // There is no path and query + r = E_SUCCESS; + goto CATCH; + } + + } + + r = str.SubString(curIndex, position - curIndex, tempPath); + if (IsFailed(r)) + { + goto CATCH; + } + + isPath = VerifyPath(tempPath); + SysTryReturn(NID_BASE_UTIL, isPath, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Path.", GetErrorMessage(E_INVALID_FORMAT)); + + path = tempPath; + + curIndex = position; + + if (curIndex < str.GetLength() && str[curIndex] == L'?') + { + String tempQuery; + + curIndex++; + int indexOf = 0; + r = str.IndexOf(L'#', curIndex, indexOf); + if (r == E_SUCCESS) + { + r = str.SubString(curIndex, indexOf - curIndex, tempQuery); + if (IsFailed(r)) + { + goto CATCH; + } + } + else if (r == E_OBJ_NOT_FOUND) + { + r = str.SubString(curIndex, tempQuery); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + goto CATCH; + } + + bool isQuery = VerifyUriChar(tempQuery); + if (isQuery) + { + query = tempQuery; + } + curIndex += query.GetLength(); + } + +CATCH: + index = curIndex; + return r; +} + + +// +// This method parses an authority component. +// This component is server based or registrty authority. +// +result +Uri::ParseAuthority(const Tizen::Base::String& str, int curIndex, Tizen::Base::String& newAuth, Tizen::Base::String& userInfo, + Tizen::Base::String& host, + int& port) +{ + result r = E_SUCCESS; + + bool isServerChar = VerifyServerAuthority(str); + bool isRegChar = VerifyRegistryAuthority(str); + + if (isRegChar && !isServerChar) + { + newAuth = str; + return E_SUCCESS; + } + + if (isServerChar) + { + r = ParseServerAuthority(str, userInfo, host, port); + if (IsFailed(r)) + { + return r; + } + + newAuth = str; + } + + if (isRegChar) + { + newAuth = str; + } + + return E_SUCCESS; +} + + +// +// This method parses a server_based authority componenet. +// server_based authority : [user-info@][:port] +// +result +Uri::ParseServerAuthority(const Tizen::Base::String& str, Tizen::Base::String& user, Tizen::Base::String& host, int& port) +{ + result r = E_SUCCESS; + int indexOf = 0; + int index = 0; + String userInfo; + + // User-info + r = str.IndexOf(L'@', 0, indexOf); + if (r == E_SUCCESS) + { + r = str.SubString(0, indexOf, userInfo); + if (IsFailed(r)) + { + goto CATCH; + } + + bool isUser = VerifyUserInfo(userInfo); + + SysTryReturn(NID_BASE_UTIL, isUser, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid UserInfo.", GetErrorMessage(E_INVALID_FORMAT)); + + user = userInfo; + + index += indexOf + 1; // skip '@' + } + + // IPv4 or IPv6 address + if (str[0] == L'[') + { + // IPv6 not supported + return E_INVALID_FORMAT; +#if 0 + // IPv6 address + index++; + + if (str[str.GetLength() - 1] == L']') + { + String ip6; + String outIpv6; + + r = str.SubString(1, str.GetLength() - 2, ip6); + if (IsFailed(r)) + { + goto CATCH; + } + + // TODO : Parsing IPv6 is not implemented. + r = ParseIPv6(ip6, outIpv6); + if (IsFailed(r)) + { + goto CATCH; + } + + // TODO : Because IPv6 is hardly used, a member variable for IPv6 stores it directly. + __ipv6 = outIpv6; + + index += str.GetLength(); + } + else + { + r = E_INVALID_FORMAT; // This component has no closing bracket although it is a IPv6 address. + goto CATCH; + } +#endif + } + else + { + String ip4; + int count = 0; + + r = ParseIpv4(str, index, count); // length of ipv4 string + if (IsFailed(r)) + { + goto CATCH; + } + + if (count >= 0) + { + r = str.SubString(0, count, ip4); + if (IsFailed(r)) + { + goto CATCH; + } + + host = ip4; + } + else if (count < 0) + { + // This is a host name + String tmpHost; + + r = ParseHostName(str, index, tmpHost); + if (IsFailed(r)) + { + return r; + } + + host = tmpHost; + } + } + + // Port + if (host.IsEmpty()) + { + port = -1; + return E_SUCCESS; + } + + index += host.GetLength(); + if (index < str.GetLength() && str[index] == L':') + { + String tmpPort; + + index++; + r = str.IndexOf(L'/', index, indexOf); + if (r == E_SUCCESS) + { + r = str.SubString(index, indexOf - index, tmpPort); + if (IsFailed(r)) + { + goto CATCH; + } + } + else if (r == E_OBJ_NOT_FOUND) + { + r = str.SubString(index, tmpPort); + if (IsFailed(r)) + { + goto CATCH; + } + } + + int tmpPortLen = tmpPort.GetLength(); + for (int i = 0; i < tmpPortLen; i++) + { + wchar_t ch = tmpPort[i]; + if (!(Character::IsDigit(ch))) + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + index += tmpPort.GetLength(); + + int ret = 0; + r = Integer::Parse(tmpPort, 10, ret); + port = ret; + } + else + { + port = -1; + } + + if (index < (int) str.GetLength()) + { + r = E_INVALID_FORMAT; + goto CATCH; + } + + return E_SUCCESS; + +CATCH: + return r; +} + + +// +// This method parses a host name and returns a host name as an out-param. +// +result +Uri::ParseHostName(const Tizen::Base::String& str, int index, Tizen::Base::String& host) +{ + result r = E_SUCCESS; + int indexOf = 0; + bool isHost = false; + + int strLen = str.GetLength(); + r = str.IndexOf(L':', index, indexOf); + if (r == E_SUCCESS) + { + r = str.SubString(index, indexOf - index, host); + if (IsFailed(r)) + { + goto CATCH; + } + } + else if (r == E_OBJ_NOT_FOUND) + { + //host = str; + r = str.SubString(index, host); + if (IsFailed(r)) + { + goto CATCH; + } + } + + for (int i = 0; i < strLen; i++) + { + if (str[i] == L'%') + { + wchar_t ch1 = str[i + 1]; + wchar_t ch2 = str[i + 2]; + bool escape = IsEscapedChar(ch1, ch2); + if (!escape) + { + break; + } + + host = L""; + return E_SUCCESS; + } + } + + isHost = VerifyHost(host); + + SysTryReturn(NID_BASE_UTIL, isHost, E_INVALID_FORMAT, E_INVALID_FORMAT, "[%s] Invalid Host.", GetErrorMessage(E_INVALID_FORMAT)); + +CATCH: + return r; +} + + +// +// This method parses an IPv6 address. +// This method covers all and only the following cases : +// hex_seq +// hex_seq : IPv4 address +// hex_seq :: +// hex_seq :: hex_seq +// hex_seq :: hex_seq : IPv4 address +// :: hex_seq +// :: hex_seq : IPv4 address +// :: +// +// Additionally, we constrain the IPv6 address as follows : +// 1) IPv6 address without compressed zeros should contain exactly 16 bytes. +// 2) IPv6 address with comporessed zeros should contain less than 16 bytes. +// +result +Uri::ParseIpv6(const Tizen::Base::String& ip6, Tizen::Base::String& outIpv6) +{ + // TODO : It will be implemented + return E_SUCCESS; +} + + +result +Uri::ParseIpv4(const Tizen::Base::String& str, int start, int& count) +{ + result r = E_SUCCESS; + String dot(L"."); + String ipHost; + + r = str.SubString(start, ipHost); + if (IsFailed(r)) + { + return r; + } + + // Set the index as an end position of ipv4 + count = ipHost.GetLength(); + + StringTokenizer strTok(ipHost, dot); + + // Check that a given string consists of digit or dot. + int ipHostLen = ipHost.GetLength(); + for (int i = 0; i < ipHostLen; i++) + { + wchar_t ch = ipHost[i]; + if (ch != L'.' && !(Character::IsDigit(ch))) + { + count = -1; + //r = E_INVALID_FORMAT; + goto CATCH; + } + } + + while (strTok.HasMoreTokens() == true) + { + String token; + + r = strTok.GetNextToken(token); + if (IsFailed(r)) + { + goto CATCH; + } + + int ret = 0; + r = Integer::Parse(token, 10, ret); + if (IsFailed(r)) + { + goto CATCH; + } + + // each part of IPv4 address cannot exceed 255. + if (ret < 0 || ret > 255) + { + r = E_INVALID_FORMAT; + goto CATCH; + } + } + + return E_SUCCESS; + +CATCH: + return r; +} + + +////////////////////////////////////////////////////////////////////////////////////////// +// Verify a component + +// +// This method verifies whether a given string is scheme format or not. +// The scheme has an combination of alphabet, digit, plus(+), dash(-) and period(.). +// The first character must be an alphabet. +// +bool +Uri::VerifyScheme(const Tizen::Base::String& str) const +{ + bool isAlpha = Character::IsLetter(str[0]); + if (!isAlpha) + { + return false; + } + + int strLen = str.GetLength(); + for (int i = 1; i < strLen; i++) + { + if ((str[i] != '+') && (str[i] != '-') && (str[i] != '.') && (!Character::IsAlphaNumeric(str[i])) && + (!Character::IsDigit(str[i]))) + { + return false; + } + } + + return true; +} + + +bool +Uri::VerifyAuthority(const Tizen::Base::String& str) const +{ + bool isReg = VerifyRegistryAuthority(str); + bool isServer = VerifyServerAuthority(str); + + if (isReg || isServer) + { + return true; + } + else + { + return false; + } +} + + +bool +Uri::VerifyHost(const Tizen::Base::String& str) const +{ + int length = str.GetLength(); + + for (int i = 0; i < length; i++) + { + wchar_t ch = str[i]; + if (ch != L'-' && ch != L'.' && !Character::IsAlphaNumeric(ch) && !Character::IsDigit(ch)) + { + return false; + } + + if (ch == L'-') + { + if (i == 0 || i == length - 1) + { + return false; + } + } + } + return true; +} + + +bool +Uri::VerifyPath(const Tizen::Base::String& str) const +{ + result r = E_SUCCESS; + String reserved(L":@&=+$\",;/"); + + int strLen = str.GetLength(); + for (int i = 0; i < strLen; i++) + { + int indexOf = 0; + r = reserved.IndexOf(str[i], 0, indexOf); + + if (str[i] == L'%') + { + wchar_t ch1 = str[i + 1]; + wchar_t ch2 = str[i + 2]; + bool escape = IsEscapedChar(ch1, ch2); + if (!escape) + { + return false; + } + } + else if (str[i] == L' ') // add a space + { + } + else if (r == E_OBJ_NOT_FOUND && !Character::IsAlphaNumeric(str[i]) && !Character::IsDigit(str[i]) && !IsMark(str[i])) + { + // Check the unicode letter + if (!(Character::GetUnicodeCategory(str[i]) == UNICODE_LETTER)) + { + return false; + } + } + + } + return true; +} + + +bool +Uri::VerifyUserInfo(const Tizen::Base::String& str) const +{ + String reserved(L";:&=+$,"); + int strLen = str.GetLength(); + + for (int i = 0; i < strLen; i++) + { + int indexOf = 0; + reserved.IndexOf(str[i], 0, indexOf); + + if (str[i] == L'%') + { + wchar_t ch1 = str[i + 1]; + wchar_t ch2 = str[i + 2]; + bool escape = IsEscapedChar(ch1, ch2); + if (!escape) + { + return false; + } + } + else if (str[i] == L' ') // add a space + { + } + else if (indexOf < 0 && !Character::IsAlphaNumeric(str[i]) && !Character::IsDigit(str[i]) && !IsMark(str[i])) + { + // Check the unicode letter + if (!(Character::GetUnicodeCategory(str[i]) == UNICODE_LETTER)) + { + return false; + } + } + } + return true; +} + + +bool +Uri::VerifyUriChar(const Tizen::Base::String& str) const +{ + result r = E_SUCCESS; +// String reserved(L";/?:@&=+$,[]"); + // [ ] removed form "reserved" + // RFC 2732: (Format for Literal IPv6 Addresses in URLs) is not supported for now. + String reserved(L";/?:@&=+$,"); + String delims(L"<>#\""); // <, >, #, %, " + int strLen = str.GetLength(); + + for (int i = 0; i < strLen; i++) + { + wchar_t ch = str[i]; + int indexOf = 0; + + r = delims.IndexOf(ch, 0, indexOf); // check delims + if (r == E_SUCCESS) + { + return false; + } + + r = reserved.IndexOf(ch, 0, indexOf); + if (ch == L'%') + { + wchar_t ch1 = str[i + 1]; + wchar_t ch2 = str[i + 2]; + bool escape = IsEscapedChar(ch1, ch2); + if (!escape) + { + return false; + } + } + else if (IsControlChar(ch)) // control + { + return false; + } + else if ((ch != ' ') && (ch < 0x80) && !Character::IsAlphaNumeric(ch) && !Character::IsDigit(ch) && !IsMark(ch) && + !(r == E_SUCCESS)) + { + // Check the unicode letter + if (!(Character::GetUnicodeCategory(str[i]) == UNICODE_LETTER)) + { + return false; + } + } + } + return true; +} + + +// +// This method checks that a given string consists of only server_based characters. +// @return True if a string consists of only server_based characters. +// +bool +Uri::VerifyServerAuthority(const Tizen::Base::String& str) const +{ + result r = E_SUCCESS; + String special(L".:@[]"); + + int indexOf = 0; + int strLen = str.GetLength(); + // Server based authority consists of alphabets, digits, marks(-_!.~*'()), escaped(%hexhex), and ;:&=+$'',@[] + for (int i = 0; i < strLen; i++) + { + wchar_t ch = str[i]; + r = special.IndexOf(ch, 0, indexOf); + //if (r == E_SUCCESS && indexOf >= 0) + //{ + // return true; + //} + // + if (ch == L'-' || IsUserInfo(ch) || r == E_SUCCESS) + { + // This string is a server_based authority character + if (ch == L'%') + { + // escaped octets + if (!IsEscapedChar(str[i + 1], str[i + 2])) + { + return false; + } + } +// return true; + } + else + { + // Check the unicode letter + if (!(Character::GetUnicodeCategory(str[i]) == UNICODE_LETTER)) + { + return false; + } + } + } + return true; +} + + +// +// This method checks that a given string consists of only registry_based characters. +// @return True if a string consists of only registry_based characters. +// +bool +Uri::VerifyRegistryAuthority(const Tizen::Base::String& str) const +{ + result r = E_SUCCESS; + String specialChar(L"@%;:&=+$,"); + + int indexOf = 0; + int strLen = str.GetLength(); + for (int i = 0; i < strLen; i++) + { + wchar_t ch = str[i]; + r = specialChar.IndexOf(ch, 0, indexOf); + + if (!(Character::IsAlphaNumeric(ch)) && !(Character::IsDigit(ch)) && !IsMark(ch) && !(indexOf >= 0 && r == E_SUCCESS)) + { + // Check the unicode letter + if (!(Character::GetUnicodeCategory(str[i]) == UNICODE_LETTER)) + { + return false; + } + } + else if (ch == L'%') + { + if (!IsEscapedChar(str[i + 1], str[i + 2])) + { + return false; + } + } + } + + return true; +} + + +////////////////////////////////////////////////////////////////////// +// Utility methods such as IsUserInfo, IsMark and so on. + +// +// This method returns true if a given wchar_t is a user-info character. +// user-info char : alphabet, digit, -_.!~*'(), ;:&=+$, +// +bool +Uri::IsUserInfo(wchar_t mch) const +{ + result r = E_SUCCESS; + String specialChar(L";:&=+$,"); + + if (mch == L'%' || Character::IsAlphaNumeric(mch) || Character::IsDigit(mch) || IsMark(mch)) + { + return true; + } + + int indexOf = 0; + r = specialChar.IndexOf(mch, 0, indexOf); + if (indexOf >= 0 && r == E_SUCCESS) + { + return true; + } + + return false; +} + + +// +// This method returns true if a given wchar_t is a mark character. +// mark char : -_.!~*'() +// +bool +Uri::IsMark(wchar_t mch) const +{ + result r = E_SUCCESS; + String mark(L"-_.!~*'()"); + + int indexOf = 0; + + r = mark.IndexOf(mch, 0, indexOf); + if (indexOf >= 0 && r == E_SUCCESS) + { + return true; + } + + return false; +} + + +bool +Uri::IsControlChar(wchar_t ch) const +{ + if ((ch <= 0x009F) && ((ch <= 0x001F) || (ch >= 0x007F))) + { + return true; + } + else + { + return false; + } +} + + +bool +Uri::IsEscapedChar(wchar_t ch1, wchar_t ch2) const +{ + if ((ch1 >= L'a' && ch1 <= L'f') || (ch1 >= L'A' && ch1 <= L'F') || Character::IsDigit(ch1)) + { + if ((ch2 >= L'a' && ch2 <= L'f') || (ch2 >= L'A' && ch2 <= L'F') || Character::IsDigit(ch2)) + { + return true; + } + } + + return false; +} + + +//////////////////////////////////////////////////////////////////////// +// Private operations + +// +// This method finds the first character in the stop-string. +// +int +Uri::Scan(const Tizen::Base::String& str, int start, const Tizen::Base::String& stopString) +{ + result r = E_SUCCESS; + int index = start; + int strLen = str.GetLength(); + while (index < strLen) + { + int indexOf = 0; + wchar_t ch = str[index]; + + r = stopString.IndexOf(ch, 0, indexOf); + if (r == E_SUCCESS) + { + break; + } + + index++; + } + return index; +} + + +// +// This method convers a component represented by UTF8 to a component represented by Unicode. +// +Tizen::Base::String +Uri::Decode(const Tizen::Base::String& str) +{ + if (str.IsEmpty()) + { + return str; + } + + result r = E_SUCCESS; + + int len = str.GetLength(); + int index = 0; + + String decodedBuf; + + while (index < len) + { + if (str[index] != L'%') + { + decodedBuf.Append(str[index]); + index++; + continue; + } + + ByteBuffer bb; + r = bb.Construct(20); + + while (1) + { + String utf8Str; + r = str.SubString(index + 1, 2, utf8Str); + + short ret = 0; + r = Short::Parse(utf8Str, 16, ret); + if (IsFailed(r)) + { + goto CATCH; + } + + r = bb.SetByte((byte) ret); + + index = index + 3; + + if (index >= len || str[index] != '%') + { + r = bb.SetByte(0); + break; + } + } + + String unicode; + r = StringUtil::Utf8ToString((char*) bb.GetPointer(), unicode); +// if (IsFailed(r)) goto CATCH; + if (IsFailed(r)) + { + decodedBuf.Append(L'?'); + } + else + { + decodedBuf.Append(unicode); + } + } + + return decodedBuf; + +CATCH: + return str; +} + + +// +// This method converts a component represented by Unicode to a component represented by UTF8. +// +Tizen::Base::String +Uri::Encode(const Tizen::Base::String& str) const +{ + if (str.IsEmpty()) + { + return str; + } + + result r = E_SUCCESS; + String upper; + WcharBuffer wchar_tBuf; + + r = wchar_tBuf.Construct(str.GetLength() + 1); + + String strbuf; + + r = wchar_tBuf.SetArray(str.GetPointer(), 0, str.GetLength()); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = wchar_tBuf.Set(L'\0'); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + + wchar_tBuf.Flip(); + + std::unique_ptr< char[] > pChar(new (std::nothrow) char[10]); + SysTryReturn(NID_BASE_UTIL, pChar != null, str, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + memset(pChar.get(), 0, 10); + + while (wchar_tBuf.HasRemaining()) + { + wchar_t mch = 0x00; + r = wchar_tBuf.Get(mch); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + + if (mch == 0) + { + break; + } + + if (mch >= 0x0080 || IsControlChar(mch)) + { + WcharBuffer tmpBuf; + String tempStr; + + String unicode; + + int bbPos = 0; + + r = tmpBuf.Construct(2); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = tmpBuf.Set(mch); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = tmpBuf.Set(L'\0'); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + + tmpBuf.Flip(); + + tempStr = tmpBuf.GetPointer(); + std::unique_ptr< ByteBuffer > pBuf(StringUtil::StringToUtf8N(tempStr)); + SysTryReturn(NID_BASE_UTIL, pBuf != null, str, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + while (bbPos < pBuf->GetLimit() - 1) // null + { + byte b = '\0'; + r = pBuf->GetByte(bbPos, b); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + + sprintf(pChar.get() + (bbPos * 3), "%%%x", (int) b); + bbPos++; + } + + r = StringUtil::Utf8ToString(pChar.get(), unicode); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + + r = unicode.ToUpper(upper); + + r = strbuf.Append(upper); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + } + else if (mch == 0x20) + { + String unicode(L"%20"); + r = strbuf.Append(unicode); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + } + else // ASCII character + { + r = strbuf.Append(mch); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), str, r, "[%s] Propagating.", GetErrorMessage(r)); + } + } + + SetLastResult(E_SUCCESS); + return strbuf; +} + + +result +Uri::AppendEscape(Tizen::Base::String& strbuf, byte b) +{ + byte bt1 = '\0'; + byte bt2 = '\0'; + + result r = E_SUCCESS; + r = strbuf.Append(L'%'); + if (IsFailed(r)) + { + goto CATCH; + } + + bt1 = (b >> 4) & 0x0f; + r = strbuf.Append(HEX_DIGITS[bt1]); + if (IsFailed(r)) + { + goto CATCH; + } + + bt2 = (b >> 0) & 0x0f; + r = strbuf.Append(HEX_DIGITS[bt2]); + if (IsFailed(r)) + { + goto CATCH; + } + + return r; + +CATCH: + return r; +} + + +// This method compares str1 and str2 after replacing all uppercase letters with their lowercase letters +int +Uri::Compare(const Tizen::Base::String& str1, const Tizen::Base::String& str2) const +{ + String small1; + String small2; + + if (str1.IsEmpty()) + { + if (str2.IsEmpty()) + { + // Both pStr1 and pStr2 are null + return 0; + } + else + { + // pStr1 is null but pStr isn't. + return -1; + } + } + else + { + if (str2.IsEmpty()) + { + // pStr1 is not null but pStr2 is null + return 1; + } + } + + // Replace all uppercase letters with their lowercase letters + str1.ToLower(small1); + str2.ToLower(small2); + + return small1.CompareTo(small2); + +} + + +////////////////////////////////////////////////////////////////////////////////////////// +// Normalization + +Tizen::Base::String +Uri::InternalNormalize(const Tizen::Base::String& path) +{ + result r = E_SUCCESS; + String joinedStr; + String str; + int segCount = 0; + int join = 0; + + std::unique_ptr< WcharBuffer > pBuf(StringUtil::StringToMbN(path, 0, path.GetLength())); + if (pBuf == null) + { + return str; + } + + // Get the number of segments from a given path + segCount = GetNumberOfSegments(path); + if (segCount <= 0) + { + return path; + } + + // Get the first index of each segment + std::unique_ptr< int[] > pSegments(new (std::nothrow) int[segCount]); + SplitIntoSegments(*pBuf, pSegments.get(), segCount); + + // Remove dots + RemoveDots(*pBuf, pSegments.get(), segCount, path.GetLength()); + + // Prevent scheme-name confusion + AddLeadingDot(*pBuf, pSegments.get(), segCount); + + // Join the remaining segments and returns the result + join = Join(*pBuf, pSegments.get(), segCount); + + r = StringUtil::MbToString(*pBuf, str); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), L"", E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(E_INVALID_ARG)); + + // Empty String + if (str.IsEmpty()) + { + return str; + } + + r = str.SubString(0, join - 1, joinedStr); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), L"", E_INVALID_ARG, "[%s] Propagating.", GetErrorMessage(E_INVALID_ARG)); + + if (joinedStr.Equals(path)) + { + return path; // String was already normalized. + } + + SetLastResult(E_SUCCESS); + return joinedStr; +} + + +// +// This method returns the number of segments from a given path. +// +int +Uri::GetNumberOfSegments(const Tizen::Base::String& path) const +{ + bool normal = true; + int segCount = 0; + int endIndex = path.GetLength() - 1; + int p = 0; + + // find the index of non-slash character + while (p <= endIndex) + { + if (path[p] != L'/') + { + break; + } + p++; + } + if (p > 1) + { + normal = false; + } + + // Scan segments + while (p <= endIndex) + { + // Looking at '.' or '..' + if ((path[p] == L'.') && ((p == endIndex) || ((path[p + 1] == L'/') || + ((path[p + 1] == L'.') && ((p + 1 == endIndex) || (path[p + 2] == L'/')))))) + { + normal = false; + } + segCount++; + + // Find the beginning index of next segment + while (p <= endIndex) + { + if (path[p++] != L'/') + { + continue; + } + + // skip redundant slashes + while (p <= endIndex) + { + if (path[p] != L'/') + { + break; + } + + normal = false; + p++; + } + + break; + } + } + + if (normal) + { + return -1; + } + else + { + return segCount; + } +} + + +void +Uri::SplitIntoSegments(Tizen::Base::WcharBuffer& mb, int* segments, int segCount) +{ + int end = StringUtil::GetStringLengthInMb(mb); + + //int end = mb.GetLimit() - 1; + int p = 0; + int index = 0; // the index of current segment + + // skip initial slash + while (p <= end) + { + if (mb[p] != L'/') + { + break; + } + mb[p] = L'\0'; + p++; + } + + while (p <= end) + { + if (index >= segCount) + { + break; + } + + // start of segment + segments[index] = p; + index++; + p++; + + // Find beginning of next segment + while (p <= end) + { + if (mb[p++] != L'/') + { + continue; + } + mb[p - 1] = L'\0'; + + // skip redundant slash + while (p <= end) + { + if (mb[p] != L'/') + { + break; + } + mb[p++] = L'\0'; + } + break; + } + } + + // index must be equal to the length of segments[] +} + + +void +Uri::RemoveDots(const Tizen::Base::WcharBuffer& mb, int* segments, int segCount, int length) +{ + int end = length; + + for (int i = 0; i < segCount; i++) + { + int dots = 0; // number of dots found + + // Find next occurrence of "." or ".. + do + { + int p = segments[i]; + if (mb[p] == '.') + { + if (p == end) + { + dots = 1; + break; + } + else if (mb[p + 1] == L'\0') + { + dots = 1; + break; + } + else if ((mb[p + 1] == L'.') && ((p + 1 == end) || (mb[p + 2] == L'\0'))) + { + dots = 2; + break; + } + } + i++; + } + while (i < segCount); + + if ((i > segCount) || (dots == 0)) + { + break; + } + + if (dots == 1 && i < segCount) + { + // Remove this occurrence of '.' + segments[i] = -1; + } + else + { + // If there is a preceding non-".." segment, remove both that segment and this occurrence of ".."; + // otherwise, leave this ".." segment as-is. + int j = 0; + for (j = i - 1; j >= 0; j--) + { + if (segments[j] != -1) + { + break; + } + } + + if (j >= 0) + { + int q = segments[j]; + if (!((mb[q] == '.') && (mb[q + 1] == '.') && (mb[q + 2] == '\0'))) + { + segments[i] = -1; + segments[j] = -1; + } + } + } + } +} + + +void +Uri::AddLeadingDot(Tizen::Base::WcharBuffer& mb, int* segments, int segCount) +{ + if (mb[0] == L'\0') + { + // The path is absolute + return; + } + + int firstSegment = 0; // Index of first segment + while (firstSegment < segCount) + { + if (segments[firstSegment] >= 0) + { + break; + } + firstSegment++; + } + + if ((firstSegment >= segCount) || (firstSegment == 0)) + { + // The path is empty, or else the original first segment survived, + // in which case we already know that no leading "." is needed + return; + } + + int p = segments[firstSegment]; + while ((mb[p] != L':') && (mb[p] != L'\0') && (p < mb.GetLimit())) + { + p++; + } + + if (mb[p] == L'\0' || p >= mb.GetLimit()) + { + // No colon in first segment, so no "." needed + return; + } + + // At this point we know that the first segment is unused, + // hence we can insert a "." segment at that position + mb[0] = L'.'; + mb[1] = L'\0'; + segments[0] = 0; +} + + +// Join the segments in the given path according to the given segment-index array, +// ignoring those segments whose index entries have been set to -1, and inserting slashes as needed. +// Return the length of the resulting path. +// +// Preconditions: +// segs[i] == -1 implies segment i is to be ignored +// path computed by split, as above, with '\0' having replaced '/' +// +// Postconditions: +// path[0] .. path[return value] == Resulting path +// +int +Uri::Join(Tizen::Base::WcharBuffer& mb, int* segments, int segCount) +{ + //int end = StringUtil::GetStringLengthInMb(mb); + + int end = mb.GetLimit() - 1; + int p = 0; + + if (mb[p] == L'\0') + { + // Restore initial slash for absolute paths + mb[p++] = L'/'; + } + + for (int i = 0; i < segCount; i++) + { + int q = segments[i]; + if (q == -1) + { + // ignore this segment + continue; + } + + if (p == q) + { + // skip to its end + while ((p <= end) && (mb[p] != L'\0')) + { + p++; + } + if (p <= end) + { + // Preserve trailing slash + mb[p++] = L'/'; + } + } + else if (p < q) + { + while ((q <= end) && mb[q] != L'\0') + { + mb[p++] = mb[q++]; + } + if (q < end) + { + // Preserve trailing slash + mb[p++] = L'/'; + } + } + } + if (p == mb.GetLimit()) + { + result r = E_SUCCESS; + r = mb.SetLimit(p + 1); + if (IsFailed(r)) + { + return p; + } + } + mb[p++] = L'\0'; + + return p; +} + + +/////////////////////////////////////////////////////////////////////////////////////////////// +// Resolution + +// +// This method implements Uri resolution in RFC2396 5.2 +// +result +Uri::Resolve(const Uri& baseUri, const Uri& childUri, Uri& resultUri) +{ + result r = E_SUCCESS; + + // If either baseUri or childUri is opaque, then resultUri is childUri + if (baseUri.IsOpaque() || childUri.IsOpaque()) + { + resultUri = childUri; + return E_SUCCESS; + } + + + // 5.2(2) If scheme, authority, path, and query of childUri are null, + // the components of baseUri are copied to components of resultUri. + if ((childUri.__scheme.IsEmpty()) && (childUri.__authority.IsEmpty()) && (childUri.__path.IsEmpty()) + && (!childUri.__fragment.IsEmpty()) && (childUri.__query.IsEmpty())) + { + if ((!baseUri.__fragment.IsEmpty()) && (childUri.__fragment.GetLength() == baseUri.__fragment.GetLength())) + { + resultUri = baseUri; + return E_SUCCESS; + } + + if (!baseUri.__scheme.IsEmpty()) + { + r = resultUri.SetScheme(baseUri.__scheme); + if (IsFailed(r)) + { + return r; + } + } + + if (!baseUri.__authority.IsEmpty()) + { + r = resultUri.SetAuthority(baseUri.__authority); + if (IsFailed(r)) + { + return r; + } + } + + if (!baseUri.__userInfo.IsEmpty()) + { + r = resultUri.SetUserInfo(baseUri.__userInfo); + if (IsFailed(r)) + { + return r; + } + } + + if (!baseUri.__host.IsEmpty()) + { + r = resultUri.SetHost(baseUri.__host); + if (IsFailed(r)) + { + return r; + } + } + + resultUri.SetPort(baseUri.__port); + + if (!baseUri.__path.IsEmpty()) + { + r = resultUri.SetPath(baseUri.__path); + if (IsFailed(r)) + { + return r; + } + } + + if (!childUri.__fragment.IsEmpty()) + { + r = resultUri.SetFragment(childUri.__fragment); + if (IsFailed(r)) + { + return r; + } + } + + if (!baseUri.__query.IsEmpty()) + { + r = resultUri.SetQuery(baseUri.__query); + if (IsFailed(r)) + { + return r; + } + } + + return E_SUCCESS; + } + + + // 5.2(3) child is an absolute URI + if (!childUri.__scheme.IsEmpty()) + { + resultUri = childUri; + return E_SUCCESS; + } + + + if (!baseUri.__scheme.IsEmpty()) + { + r = resultUri.SetScheme(baseUri.__scheme); + if (IsFailed(r)) + { + return r; + } + } + + if (!childUri.__query.IsEmpty()) + { + r = resultUri.SetQuery(childUri.__query); + if (IsFailed(r)) + { + return r; + } + } + + if (!childUri.__fragment.IsEmpty()) + { + r = resultUri.SetFragment(childUri.__fragment); + if (IsFailed(r)) + { + return r; + } + } + + // 5.2(4) Authority + if (childUri.__authority.IsEmpty()) + { + if (!baseUri.__authority.IsEmpty()) + { + r = resultUri.SetAuthority(baseUri.__authority); + if (IsFailed(r)) + { + return r; + } + } + + if (!baseUri.__host.IsEmpty()) + { + r = resultUri.SetHost(baseUri.__host); + if (IsFailed(r)) + { + return r; + } + } + + if (!baseUri.__userInfo.IsEmpty()) + { + r = resultUri.SetUserInfo(baseUri.__userInfo); + if (IsFailed(r)) + { + return r; + } + } + + resultUri.SetPort(baseUri.__port); + + String resolve; + String encodedPath = childUri.__encodedPath; + if (!encodedPath.IsEmpty()) + { + resolve = childUri.__encodedPath; + } + + if ((!resolve.IsEmpty()) && (resolve[0] == L'/')) + { + // 5.2(5) child uri's path is absolute + if (!encodedPath.IsEmpty()) + { + r = resultUri.SetPath(encodedPath); + if (IsFailed(r)) + { + return r; + } + } + } + else + { + String encPath = baseUri.__encodedPath; + if (!encPath.IsEmpty()) + { + // 5.2(6) Resolve relative path + String relPath = ResolvePath(encPath, resolve, baseUri.IsAbsolute()); + if (relPath.IsEmpty()) + { + return GetLastResult(); + } + + r = resultUri.SetPath(relPath); + if (IsFailed(r)) + { + return r; + } + } + } + } + else + { + if (!childUri.__authority.IsEmpty()) + { + r = resultUri.SetAuthority(childUri.__authority); + if (IsFailed(r)) + { + return r; + } + } + + if (!childUri.__host.IsEmpty()) + { + r = resultUri.SetHost(childUri.__host); + if (IsFailed(r)) + { + return r; + } + } + + if (!childUri.__userInfo.IsEmpty()) + { + r = resultUri.SetUserInfo(childUri.__userInfo); + if (IsFailed(r)) + { + return r; + } + } + + resultUri.SetPort(childUri.__port); + + if (!childUri.__path.IsEmpty()) + { + r = resultUri.SetPath(childUri.__path); + if (IsFailed(r)) + { + return r; + } + } + + } + + return E_SUCCESS; +} + + +// RFC2396 5.2(6) +Tizen::Base::String +Uri::ResolvePath(const String& basePath, const String& childPath, bool isAbsolute) +{ + result r = E_SUCCESS; + String path; + + int indexOf = 0; + r = basePath.LastIndexOf(L'/', basePath.GetLength() - 1, indexOf); + + int len = childPath.GetLength(); + + if (len == 0) + { + if (indexOf >= 0 && r == E_SUCCESS) + { + r = basePath.SubString(0, indexOf + 1, path); + if (IsFailed(r)) + { + goto CATCH; + } + } + } + // 5.2 (6a) + else + { + String strbuf; + + if (r == E_SUCCESS) + { + String tmpath; + r = basePath.SubString(0, indexOf + 1, tmpath); + if (IsFailed(r)) + { + goto CATCH; + } + + r = strbuf.Append(tmpath); + if (IsFailed(r)) + { + goto CATCH; + } + } + + r = strbuf.Append(childPath); + if (IsFailed(r)) + { + goto CATCH; + } + + path = strbuf; + } + + return InternalNormalize(path); + +CATCH: + SetLastResult(r); + return null; +} + + +////////////////////////////////////////////////////////////////////////// +// Relativize +result +Uri::Relativize(const Uri& baseUri, const Uri& childUri, Uri& resultUri) +{ + result r = E_SUCCESS; + + // If either base URI or child URI is opaque, result URI is the childUri. + if (baseUri.IsOpaque() || childUri.IsOpaque()) + { + resultUri = childUri; + return E_SUCCESS; + } + + int ret1 = Compare(baseUri.__scheme, childUri.__scheme); + + bool equal = false; + if (!baseUri.__authority.IsEmpty() && !childUri.__authority.IsEmpty()) + { + equal = EqualsComponent(baseUri.__authority, childUri.__authority); + } + + if ((ret1 != 0) || (!equal)) + { + resultUri = childUri; + return E_SUCCESS; + } + + String basePath = InternalNormalize(baseUri.__path); + String childPath = InternalNormalize(childUri.__path); + + if (basePath.Equals(childPath) == false) + { + String newBp; + String slash(L"/"); + + bool endWith = basePath.EndsWith(slash); + if (!endWith) + { + String strbuf(basePath); + + r = strbuf.Append(slash); + if (IsFailed(r)) + { + return r; + } + + newBp = strbuf; + } + else + { + newBp = basePath; + } + + bool startsWith = childPath.StartsWith(basePath, 0); + + if (!startsWith) + { + resultUri = childUri; + return E_SUCCESS; + } + } + + String path; + r = childPath.SubString(basePath.GetLength(), path); + if (IsFailed(r)) + { + return E_SUCCESS; + } + + r = resultUri.SetPath(path); + if (IsFailed(r)) + { + return r; + } + + if (!childUri.__query.IsEmpty()) + { + r = resultUri.SetQuery(childUri.__query); + if (IsFailed(r)) + { + return r; + } + } + + if (!childUri.__fragment.IsEmpty()) + { + r = resultUri.SetFragment(childUri.__fragment); + if (IsFailed(r)) + { + return r; + } + } + + return r; +} + + +// +// This method compares two components. If a component is encoded, +// then its raw component is compared with another component. +// +bool +Uri::EqualsComponent(const Tizen::Base::String& comp1, const Tizen::Base::String& comp2) +{ + result r = E_SUCCESS; + + if (comp1 == comp2) + { + return true; + } + + if (comp1.GetLength() != comp2.GetLength()) + { + return false; + } + + int indexOf = 0; + r = comp1.IndexOf(L'%', 0, indexOf); + if (r == E_OBJ_NOT_FOUND) + { + return comp1.Equals(comp2); + } + + int len = comp1.GetLength(); + for (int i = 0; i < len; ) + { + wchar_t c1 = (comp1)[i]; + wchar_t c2 = (comp2)[i]; + if (c1 != L'%') + { + if (c1 != c2) + { + return false; + } + i++; + continue; + } + i++; + + + if (Character::ToLower(comp1[i]) == Character::ToLower(comp2[i])) + { + return false; + } + + i++; + if (Character::ToLower(comp1[i]) == Character::ToLower(comp2[i])) + { + return false; + } + + i++; + } + + return true; +} + + +bool +Uri::IsEncoded(const Tizen::Base::String& str) const +{ + int strLen = str.GetLength(); + for (int i = 0; i < strLen; i++) + { + wchar_t ch = str[i]; + if (ch >= 0x0080 || ch == L' ' || IsControlChar(ch)) + { + return false; + } + } + return true; +} + + +void +Uri::Clear(void) +{ + // Component + __scheme.Clear(); + __ssp.Clear(); + __authority.Clear(); + __host.Clear(); + __fragment.Clear(); + __path.Clear(); + __userInfo.Clear(); + __query.Clear(); + __ipv4.Clear(); + __ipv6.Clear(); + __port = -1; + + // Encoded Component + __encodedAuth.Clear(); + __encodedFragment.Clear(); + __encodedPath.Clear(); + __encodedQuery.Clear(); + __encodedSsp.Clear(); +} + + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilUrlDecoder.cpp b/src/base/utility/FBaseUtilUrlDecoder.cpp new file mode 100644 index 0000000..ac6c505 --- /dev/null +++ b/src/base/utility/FBaseUtilUrlDecoder.cpp @@ -0,0 +1,136 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilUrlDecoder.cpp + * @brief This is the implementation file for UrlDecoder class. + */ + +// Includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBase_StringConverter.h" +#include "FBase_NativeError.h" +#include "FBaseUtil_IcuConverter.h" + + +namespace Tizen { namespace Base { namespace Utility +{ + +UrlDecoder::UrlDecoder(void) +{ + +} + + +UrlDecoder::~UrlDecoder(void) +{ + +} + + +result +UrlDecoder::Decode(const Tizen::Base::String& str, const Tizen::Base::String& encodingScheme, Tizen::Base::String& decodedStr) +{ + SysTryReturnResult(NID_BASE_UTIL, str.GetLength() > 0, E_INVALID_ARG, "String to be encoded is empty."); + SysTryReturnResult(NID_BASE_UTIL, encodingScheme.GetLength() > 0, E_INVALID_ARG, "Invalid encoding scheme."); + + _ICUConverter converter; + bool converted = converter.OpenConverter(encodingScheme); + result r = GetLastResult(); + SysTryReturnResult(NID_BASE_UTIL, converted, r, "Propagating."); + + const wchar_t* pMchar = null; + int index = 0; + bool found = false; + int numChars = 0; + int charCount = 0; + wchar_t* pIn = null; + + numChars = str.GetLength(); + pMchar = str.GetPointer(); + pIn = const_cast(&pMchar[0]); + + std::unique_ptr< char[] > pUrlDecodedBuf(new (std::nothrow) char[numChars + 1]); + SysTryReturnResult(NID_BASE_UTIL, pUrlDecodedBuf != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + memset(pUrlDecodedBuf.get(), 0x00, numChars + 1); + + charCount = numChars; + decodedStr.Clear(); + + //Decode url-encoded string + while (charCount > 0 && (*pIn != '\0')) + { + if (*pIn == '%') + { + char hexChar[3]; + int decimal = 0; + + hexChar[0] = *(pIn + 1); + hexChar[1] = *(pIn + 2); + hexChar[2] = '\0'; + pIn += 3; + + //Converting %ab type substring to corresponing decimal value + sscanf(hexChar, "%X", &decimal); + pUrlDecodedBuf[index] = decimal; + index++; + charCount -= 3; + found = true; + } + else + { + if (found) + { + std::unique_ptr< wchar_t[] > pDst(converter.ConvertToUcharN(reinterpret_cast< const char* >(pUrlDecodedBuf.get()), index)); + SysTryReturnResult(NID_BASE_UTIL, pDst != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + decodedStr.Append(pDst.get()); + memset(pUrlDecodedBuf.get(), 0x00, numChars + 1); + index = 0; + found = false; + } + + (*pIn == '+') ? decodedStr.Append(' '):decodedStr.Append(*pIn); + pIn++; + charCount--; + } + } + + // if %XX is the last substring or all the substrings in input string are in form of %XX (e.g. %D7%91%D7%93%D7) + if (found) + { + std::unique_ptr< wchar_t[] > pDst(converter.ConvertToUcharN(reinterpret_cast< const char* >(pUrlDecodedBuf.get()), index)); + r = GetLastResult(); + SysTryReturnResult(NID_BASE_UTIL, pDst != null, r, "Propagating."); + decodedStr.Append(pDst.get()); + } + + converter.CloseConverter(); + return r; +} +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilUrlEncoder.cpp b/src/base/utility/FBaseUtilUrlEncoder.cpp new file mode 100644 index 0000000..840d7e6 --- /dev/null +++ b/src/base/utility/FBaseUtilUrlEncoder.cpp @@ -0,0 +1,132 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilUrlEncoder.cpp + * @brief This is the implementation file for UrlEncoder class. + */ + +// Includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBase_StringConverter.h" +#include "FBase_NativeError.h" +#include "FBaseUtil_IcuConverter.h" + + +namespace Tizen { namespace Base { namespace Utility +{ + + +/////////////////////////////////////////////////////////////////////////////// +/// UrlEncoder class lifecycle + +UrlEncoder::UrlEncoder(void) +{ +} + + +UrlEncoder::~UrlEncoder(void) +{ +} + + +/////////////////////////////////////////////////////////////////////////////// +/// UrlEncoder class Operations + +result +UrlEncoder::Encode(const Tizen::Base::String& str, const Tizen::Base::String& encodingScheme, Tizen::Base::String& encodedStr) +{ + SysTryReturnResult(NID_BASE_UTIL, str.GetLength() > 0, E_INVALID_ARG, "Invalid argument is used. String to be encoded is empty."); + SysTryReturnResult(NID_BASE_UTIL, encodingScheme.GetLength() > 0, E_INVALID_ARG, "Invalid argument is used. Invalid encoding scheme."); + + _ICUConverter converter; + bool converted = converter.OpenConverter(encodingScheme); + result r = GetLastResult(); + SysTryReturnResult(NID_BASE_UTIL, converted, r, "Propagating."); + + int startIndex = -1; + std::unique_ptr< char[] > pOutBuf(null); + const wchar_t* pTmpBytePtr = str.GetPointer(); + encodedStr.Clear(); + int strLen = str.GetLength(); + + for (int i = 0; i < strLen; i++) + { + // Do not convert unreserved characters (Unreserved Characters for URI in RFC 3986) + if ((pTmpBytePtr[i] >= 'a' && pTmpBytePtr[i] <= 'z') || (pTmpBytePtr[i] >= 'A' && pTmpBytePtr[i] <= 'Z') || (pTmpBytePtr[i] >= '0' && pTmpBytePtr[i] <= '9') || (pTmpBytePtr[i] == '_') || (pTmpBytePtr[i] == '~') || (pTmpBytePtr[i] == '-') || (pTmpBytePtr[i] == '.') || (pTmpBytePtr[i] == ' ')) + { + if (startIndex >= 0) + { + int retLength = 0; + pOutBuf.reset(converter.ConvertFromUcharN(pTmpBytePtr + startIndex, (i - startIndex), retLength)); + r = GetLastResult(); + SysTryReturnResult(NID_BASE_UTIL, pOutBuf != null, r, "Propagating."); + + for (int j = 0; j < retLength; j++) + { + + char hexChar[4]; + memset(&hexChar, 0x00, 4); + sprintf(hexChar, "%%%02X", (unsigned char) pOutBuf[j]); + hexChar[3] = 0; + encodedStr.Append(hexChar); // Append %ab buffer to encoded string + } + startIndex = -1; + } + + (pTmpBytePtr[i] == ' ') ? encodedStr.Append('+'):encodedStr.Append(pTmpBytePtr[i]); + } + else if (startIndex < 0) + { + startIndex = i; + } + } + + if (startIndex >= 0) + { + int retLength = 0; + pOutBuf.reset(converter.ConvertFromUcharN(pTmpBytePtr + startIndex, (str.GetLength() - startIndex), retLength)); + r = GetLastResult(); + SysTryReturnResult(NID_BASE_UTIL, pOutBuf != null, r, GetErrorMessage(r)); + + for (int j = 0; j < retLength; j++) + { + + char hexChar[4]; + memset(&hexChar, 0x00, 4); + sprintf(hexChar, "%%%02X", (unsigned char) pOutBuf[j]); + hexChar[3] = 0; + encodedStr.Append(hexChar); // Append %ab buffer to encoded string + } + startIndex = -1; + } + + converter.CloseConverter(); + return r; +} +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtilZipEntry.cpp b/src/base/utility/FBaseUtilZipEntry.cpp new file mode 100644 index 0000000..e069a82 --- /dev/null +++ b/src/base/utility/FBaseUtilZipEntry.cpp @@ -0,0 +1,140 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtilZipEntry.cpp + * @brief This is the implementation file for ZipEntry class. + */ + +//Includes +#include + +#include "FBaseUtil_ZipEntryInfo.h" + +namespace Tizen { namespace Base { namespace Utility +{ + + +ZipEntry::ZipEntry(void) + : __unzFile(null) + , __compressionLevel(DEFAULT_COMPRESSION) + , __pZipEntryImpl(null) +{ +} + + +ZipEntry::~ZipEntry(void) +{ + if (__unzFile) + { + delete static_cast <_ZipEntryInfo*>(__unzFile); + __unzFile = null; + } +} + + +String +ZipEntry::GetName(void) const +{ + return __name; +} + + +CompressionLevel +ZipEntry::GetCompressionLevel(void) const +{ + return __compressionLevel; +} + + +bool +ZipEntry::IsDirectory(void) const +{ + _ZipEntryInfo* pZipEntryInfo = static_cast <_ZipEntryInfo*>(__unzFile); + return pZipEntryInfo->__isDirectory; +} + + +unsigned long +ZipEntry::GetCompressedSize(void) const +{ + _ZipEntryInfo* pZipEntryInfo = static_cast <_ZipEntryInfo*>(__unzFile); + return pZipEntryInfo->__compressedSize; +} + + +unsigned long +ZipEntry::GetUncompressedSize(void) const +{ + _ZipEntryInfo* pZipEntryInfo = static_cast <_ZipEntryInfo*>(__unzFile); + return pZipEntryInfo->__uncompressedSize; +} + + +String +ZipEntry::GetArchiveName(void) const +{ + _ZipEntryInfo* pZipEntryInfo = static_cast <_ZipEntryInfo*>(__unzFile); + return pZipEntryInfo->__archiveName; +} + + +bool +ZipEntry::Equals(const Tizen::Base::Object& obj) const +{ + const ZipEntry* pOther = dynamic_cast (&obj); + + if (pOther != null) + { + if (!GetArchiveName().Equals(pOther->GetArchiveName(), true)) + { + return false; + } + + if (__compressionLevel != pOther->__compressionLevel) + { + return false; + } + + if (__name != pOther->__name) + { + return false; + } + } + return true; + +} + + +int +ZipEntry::GetHashCode(void) const +{ + return (int) this; +} + + +void +ZipEntry::Set(void* unzFile) +{ + _ZipEntryInfo* pZipEntryInfo = static_cast <_ZipEntryInfo*>(unzFile); + __name = pZipEntryInfo->__name; + __unzFile = pZipEntryInfo; + __compressionLevel = pZipEntryInfo->__compressionLevel; +} + + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtil_FileUnzipperImpl.cpp b/src/base/utility/FBaseUtil_FileUnzipperImpl.cpp new file mode 100644 index 0000000..d2cade7 --- /dev/null +++ b/src/base/utility/FBaseUtil_FileUnzipperImpl.cpp @@ -0,0 +1,432 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @File : FBaseUtil_FileUnzipperImpl.cpp + * @brief : Implementation for _FileUnzipperImpl Class + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "FBaseUtil_ZipEntryInfo.h" +#include "FBaseUtil_FileUnzipperImpl.h" + +using namespace Tizen::Io; + +namespace Tizen {namespace Base {namespace Utility +{ + + +#define UNZ_COMP_CASE_SENSITIVE 1 +#define UNZ_COMP_NO_CASE_SENSITIVE 2 + +#define UNZ_WRITE_BUF_LEN 4096 \ +// _BADA_SLP_FIXME : TODO - Select an optimal value for this. + +struct CloseUnzipFile +{ + void operator ()(void* p) + { + if (p != null) + { + unzClose(p); + } + } +}; + +struct CloseFile +{ + void operator ()(FILE* p) + { + if (p != null) + { + fclose(p); + } + } +}; + +result +_FileUnzipperImpl::CreateDirectories(char* pFilePath) +{ + result r = E_SUCCESS; + int ret = 0; + + char* pPos = pFilePath; + while ((pPos = strchr(pPos + 1, '/')) != null) + { + *pPos = '\0'; + if (access(pFilePath, F_OK) != 0) + { + ret = mkdir(pFilePath, S_IRUSR | S_IWUSR | S_IXUSR); + if (ret == -1) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysTryReturnResult(NID_BASE_UTIL, + (r == E_SUCCESS) || (r == E_FILE_ALREADY_EXIST), r, "Unable to create directory [%s]", pFilePath); + } + } + *pPos = '/'; + } + + return E_SUCCESS; +} + +bool +_FileUnzipperImpl::IsFileExistsInZip(const char pArchiveName[], const char* pFilePathForZip) +{ + std::unique_ptr< void, CloseUnzipFile > pUnzipFile(unzOpen(pArchiveName)); + if (pUnzipFile != null) + { + return unzLocateFile(pUnzipFile.get(), pFilePathForZip, UNZ_COMP_CASE_SENSITIVE) != UNZ_END_OF_LIST_OF_FILE; + } + return false; +} + + +_FileUnzipperImpl::_FileUnzipperImpl(void) + : __pArchiveName(null) + , __entryCount(0) + , __dirCount(0) + , __fileCount(0) +{ +} + +_FileUnzipperImpl::~_FileUnzipperImpl(void) +{ +} + + +result +_FileUnzipperImpl::Construct(const String& filePath) +{ + SysAssertf(__pArchiveName == null, "Already constructed! " + "Calling Construct() twice or more on a same instance is not allowed for this class"); + + std::unique_ptr< ByteBuffer > pFilePathBuff(StringUtil::StringToUtf8N(filePath)); + SysTryReturnResult(NID_BASE_UTIL, pFilePathBuff != null, E_INVALID_ARG, "Invalid file path."); + + const char* pFilePath = reinterpret_cast (pFilePathBuff->GetPointer()); + SysTryReturnResult(NID_BASE_UTIL, access(pFilePath, F_OK) == 0, E_FILE_NOT_FOUND, "Invalid file path [%s].", pFilePath); + + std::unique_ptr< void, CloseUnzipFile > pUnzipFile(unzOpen(pFilePath)); + SysTryReturnResult(NID_BASE_UTIL, pUnzipFile != null, E_IO, "Failed to open [%s].", pFilePath); + + int dirCount = 0; + int fileCount = 0; + + FilePath unzFileEntryName = {0}; + unz_global_info gunzfileInfo = {0}; + unz_file_info unzfileInfo = {0}; + + int err = unzGetGlobalInfo(pUnzipFile.get(), &gunzfileInfo); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to open the zip entry."); + + err = unzGoToFirstFile(pUnzipFile.get()); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to get the first file entry in the zip file."); + + do + { + err = unzGetCurrentFileInfo(pUnzipFile.get(), &unzfileInfo, unzFileEntryName, PATH_MAX, null, 0, null, 0); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to get file entry info from the zip file."); + + (unzFileEntryName[strlen(unzFileEntryName) - 1] == '/')? dirCount++ : fileCount++; + + err = unzGoToNextFile(pUnzipFile.get()); + SysTryReturnResult(NID_BASE_UTIL, + (err == UNZ_OK) || (err == UNZ_END_OF_LIST_OF_FILE), E_IO, "Failed to get the next entry in the zip file."); + + } while (UNZ_END_OF_LIST_OF_FILE != err); + + int len = strlen(pFilePath); + std::unique_ptr< char[] > pArchiveName(new (std::nothrow) char[len + 1]); + SysTryReturnResult(NID_BASE_UTIL, pArchiveName != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + strncpy(pArchiveName.get(), pFilePath, len); + pArchiveName[len] = 0; + + __pArchiveName = std::move(pArchiveName); + __entryCount = gunzfileInfo.number_entry; + __dirCount = dirCount; + __fileCount = fileCount; + + ClearLastResult(); + return E_SUCCESS; +} + +result +_FileUnzipperImpl::UnzipCurrentFileTo(void* pUnZipFile, FilePath outPath, int usedBytes) const +{ + unz_file_info unzfileInfo = {0}; + int err = unzGetCurrentFileInfo(pUnZipFile, &unzfileInfo, &(outPath[usedBytes]), PATH_MAX - usedBytes, null, 0, null, 0); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to get file entry info from the zip file."); + + result r = _FileUnzipperImpl::CreateDirectories(outPath); + SysTryReturnResult(NID_BASE_UTIL, r == E_SUCCESS, r, "Failed to create Directory [%s]", outPath); + + if(outPath[strlen(outPath) - 1] != '/') + { + std::unique_ptr< FILE, CloseFile > pFile(fopen(outPath, "w")); + r = __ConvertNativeErrorToResult(errno); + SysTryReturnResult(NID_BASE_UTIL, pFile != null, r, "Failed to open file [name: %s, errorno: %d].", outPath, errno); + + err = unzOpenCurrentFile(pUnZipFile); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to open current zip file."); + + int writeCnt = 0; + int readLen = 1; + char writeBuf[UNZ_WRITE_BUF_LEN] = {0}; + while (readLen > 0) + { + readLen = unzReadCurrentFile(pUnZipFile, writeBuf, sizeof(writeBuf)); + r = (readLen < 0) ? E_IO : E_SUCCESS; + SysTryCatch(NID_BASE_UTIL, r == E_SUCCESS, unzCloseCurrentFile(pUnZipFile), r, + "[%s] Failed to read from zip file (%s).", GetErrorMessage(E_IO), outPath); + + if (readLen > 0) + { + writeCnt = fwrite(writeBuf, 1, readLen, pFile.get()); + if (writeCnt < readLen) + { + int ret = ferror(pFile.get()); + r = __ConvertNativeErrorToResult(ret); + SysTryCatch(NID_BASE_UTIL, ret != 0, unzCloseCurrentFile(pUnZipFile), r, + "[%s] Failed to perform write operation.", GetErrorMessage(r)); + } + } + } + + unzCloseCurrentFile(pUnZipFile); + } + +CATCH: + return r; +} + +result +_FileUnzipperImpl::UnzipTo(const String& dirPath) const +{ + SysAssertf(__pArchiveName != null, "Not yet constructed! Construct() should be called before use"); + + String dirPathStr(dirPath); + dirPathStr.Replace(L"\\", L"/"); + if (dirPathStr.EndsWith(L"/") == false) + { + dirPathStr.Append(L"/"); + } + + std::unique_ptr< ByteBuffer > pDirBuff(StringUtil::StringToUtf8N(dirPathStr)); + SysTryReturnResult(NID_BASE_UTIL, pDirBuff != null, E_INVALID_ARG, "Invalid file path."); + + FilePath outPath = {0}; + int dirPathLength = pDirBuff->GetCapacity() - 1; + strncat(outPath, reinterpret_cast (pDirBuff->GetPointer()), dirPathLength); + + std::unique_ptr< void, CloseUnzipFile > pUnzipFile(unzOpen(__pArchiveName.get())); + SysTryReturnResult(NID_BASE_UTIL, pUnzipFile != null, E_IO, "Failed to open [%s].", __pArchiveName.get()); + + int err = unzGoToFirstFile(pUnzipFile.get()); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to get the first file entry in the zip file."); + + result r = E_SUCCESS; + int entryCount = __entryCount; + while (entryCount--) + { + r = UnzipCurrentFileTo(pUnzipFile.get(), outPath, dirPathLength); + SysTryReturnResult(NID_BASE_UTIL, r == E_SUCCESS, r, "Failed to unzip current file"); + + if (entryCount) + { + err = unzGoToNextFile(pUnzipFile.get()); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to fetch the next file entry in the zip file."); + } + } + + return r; +} + +result +_FileUnzipperImpl::UnzipTo(const String& dirPath, const String& zipEntryName) const +{ + SysAssertf(__pArchiveName != null, "Not yet constructed! Construct() should be called before use"); + + String dirPathStr = dirPath; + dirPathStr.Replace(L"\\", L"/"); + if (dirPathStr.EndsWith(L"/") == false) + { + dirPathStr.Append(L"/"); + } + + std::unique_ptr< ByteBuffer > pDirBuff(StringUtil::StringToUtf8N(dirPathStr)); + SysTryReturnResult(NID_BASE_UTIL, pDirBuff != null, E_INVALID_ARG, "Invalid file path."); + + FilePath outPath = {0}; + int dirPathLength = pDirBuff->GetCapacity() - 1; + strncat(outPath, reinterpret_cast (pDirBuff->GetPointer()), dirPathLength); + + std::unique_ptr< ByteBuffer > pZipEntryBuff(StringUtil::StringToUtf8N(zipEntryName)); + SysTryReturnResult(NID_BASE_UTIL, pZipEntryBuff != null, E_INVALID_ARG, "[%s] Invalid zip Entry Name.", GetErrorMessage(E_INVALID_ARG)); + + const char* pZipEntryName = reinterpret_cast (pZipEntryBuff->GetPointer()); + + std::unique_ptr< void, CloseUnzipFile > pUnzipFile(unzOpen(__pArchiveName.get())); + SysTryReturnResult(NID_BASE_UTIL, pUnzipFile != null, E_IO, "Failed to open [%s].", __pArchiveName.get()); + + int err = unzLocateFile(pUnzipFile.get(), pZipEntryName, UNZ_COMP_CASE_SENSITIVE); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_FILE_NOT_FOUND, "Failed to locate file entry (%s).", pZipEntryName); + + return UnzipCurrentFileTo(pUnzipFile.get(), outPath, dirPathLength); +} + +int +_FileUnzipperImpl::GetEntryCount(void) const +{ + SysAssertf(__pArchiveName != null, "Not yet constructed! Construct() should be called before use"); + return __entryCount; +} + +int +_FileUnzipperImpl::GetFileCount(void) const +{ + SysAssertf(__pArchiveName != null, "Not yet constructed! Construct() should be called before use"); + return __fileCount; +} + + +int +_FileUnzipperImpl::GetDirectoryCount(void) const +{ + SysAssertf(__pArchiveName != null, "Not yet constructed! Construct() should be called before use"); + return __dirCount; +} + +result +_FileUnzipperImpl::GetCurrentFileInfo(void* pUnZipFile, ZipEntry& entry) const +{ + unz_file_info unzFileInfo = {0}; + char unzFileEntryName[PATH_MAX + 1]; + + // after locate, the current file is the entry, fetch its info + int err = unzGetCurrentFileInfo(pUnZipFile, &unzFileInfo, unzFileEntryName, PATH_MAX, null, 0, null, 0); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to fetch information of current file in the zip entry."); + + String fileEntryName; + result r = StringUtil::Utf8ToString(unzFileEntryName, fileEntryName); + SysTryReturnResult(NID_BASE_UTIL, r == E_SUCCESS, E_IO, "Invalid file path in Zip file."); + + String archieveName; + r = StringUtil::Utf8ToString(__pArchiveName.get(), archieveName); + SysTryReturnResult(NID_BASE_UTIL, r == E_SUCCESS, E_IO, "Invalid file path in Zip file."); + + int method = 0; + int level = DEFAULT_COMPRESSION; + + err = unzOpenCurrentFile2(pUnZipFile, &method, &level, 1); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to open the current entry in the zip file."); + + err = unzCloseCurrentFile(pUnZipFile); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to close the zip entry."); + + _ZipEntryInfo* pZipEntryInfo = null; + if (entry.__unzFile == null) + { + pZipEntryInfo = new (std::nothrow) _ZipEntryInfo; + SysTryReturnResult(NID_BASE_UTIL, pZipEntryInfo != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + } + else + { + pZipEntryInfo = static_cast <_ZipEntryInfo*>(entry.__unzFile); + } + +// pZipEntryInfo->__unzFile = __pUzFile; + pZipEntryInfo->__name = fileEntryName; + if (level == Z_BEST_SPEED) + { + pZipEntryInfo->__compressionLevel = BEST_SPEED; + } + else if (level == Z_BEST_COMPRESSION) + { + pZipEntryInfo->__compressionLevel = BEST_COMPRESSION; + } + else + { + pZipEntryInfo->__compressionLevel = DEFAULT_COMPRESSION; + } + + pZipEntryInfo->__isDirectory = (unzFileInfo.external_fa == 16) ? true : false; + pZipEntryInfo->__compressedSize = unzFileInfo.compressed_size; + pZipEntryInfo->__uncompressedSize = unzFileInfo.uncompressed_size; + pZipEntryInfo->__archiveName = archieveName; + pZipEntryInfo->__method = method; + + // set the entry information + entry.Set(pZipEntryInfo); + + return E_SUCCESS; +} + +result +_FileUnzipperImpl::GetEntry(const String& zipEntryName, ZipEntry& entry) const +{ + SysAssertf(__pArchiveName != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< ByteBuffer > pZipEntryBuff(StringUtil::StringToUtf8N(zipEntryName)); + SysTryReturnResult(NID_BASE_UTIL, pZipEntryBuff != null, E_INVALID_ARG, "Invalid file path."); + + const char* pZipEntryName = reinterpret_cast (pZipEntryBuff->GetPointer()); + + std::unique_ptr< void, CloseUnzipFile > pZipFile(unzOpen(__pArchiveName.get())); + SysTryReturnResult(NID_BASE_UTIL, pZipFile != null, E_IO, "Failed to open [%s].", __pArchiveName.get()); + + int err = unzLocateFile(pZipFile.get(), pZipEntryName, UNZ_COMP_CASE_SENSITIVE); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_FILE_NOT_FOUND, "Failed to locate file entry (%s).", pZipEntryName); + + return GetCurrentFileInfo(pZipFile.get(), entry); +} + + +result +_FileUnzipperImpl::GetEntry(int index, ZipEntry& entry) const +{ + SysAssertf(__pArchiveName != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< void, CloseUnzipFile > pZipFile(unzOpen(__pArchiveName.get())); + SysTryReturnResult(NID_BASE_UTIL, pZipFile != null, E_IO, "Failed to open [%s].", __pArchiveName.get()); + + // goto the first file in the archive + int err = unzGoToFirstFile(pZipFile.get()); + SysTryReturnResult(NID_BASE_UTIL, (err == UNZ_OK), E_IO, "Failed to get the first file entry in the zip file."); + + while (index--) + { + err = unzGoToNextFile(pZipFile.get()); + SysTryReturnResult(NID_BASE_UTIL, err == UNZ_OK, E_IO, "Failed to move to the next entry in zip file."); + } + + return GetCurrentFileInfo(pZipFile.get(), entry); +} + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtil_FileUnzipperImpl.h b/src/base/utility/FBaseUtil_FileUnzipperImpl.h new file mode 100644 index 0000000..9fed43c --- /dev/null +++ b/src/base/utility/FBaseUtil_FileUnzipperImpl.h @@ -0,0 +1,74 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtil__FileUnzipperImplImpl.h + * @brief This is the header file for _FileUnzipperImpl class. + * + * This header file contains the declarations of the _FileUnzipperImpl class. + */ + +#ifndef _FBASE_UTIL_INTERNAL_FILEUNZIPPER_IMPL_H_ +#define _FBASE_UTIL_INTERNAL_FILEUNZIPPER_IMPL_H_ + +#include +#include + +#include +#include + +typedef char FilePath[PATH_MAX + 1]; + +namespace Tizen { namespace Base { namespace Utility +{ + + +class _FileUnzipperImpl + : public Tizen::Base::Object +{ +public: + _FileUnzipperImpl(void); + virtual ~_FileUnzipperImpl(void); + result Construct(const String& filePath); + + result UnzipTo(const String& dirPath) const; + result UnzipTo(const String& dirPath, const String& zipEntryName) const; + int GetEntryCount(void) const; + int GetFileCount(void) const; + int GetDirectoryCount(void) const; + result GetEntry(const String& zipEntryName, ZipEntry& entry) const; + result GetEntry(int index, ZipEntry& entry) const; + + static result CreateDirectories(char* pFilePath); + static result IsFileExists(const char* pFilePath); + static bool IsFileExistsInZip(const char pArchiveName[], const char* pFilePathForZip); + +private: + result UnzipCurrentFileTo(void* pUnZipFile, FilePath outPath, int usedBytes) const; + result GetCurrentFileInfo(void* pUnZipFile, ZipEntry& entry) const; + +private: + std::unique_ptr< char[] > __pArchiveName; + unsigned long __entryCount; + unsigned long __dirCount; + unsigned long __fileCount; + +}; // _FileUnzipperImpl + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_INTERNAL_FILEUNZIPPER_IMPL_H_ diff --git a/src/base/utility/FBaseUtil_FileZipperImpl.cpp b/src/base/utility/FBaseUtil_FileZipperImpl.cpp new file mode 100644 index 0000000..162afbd --- /dev/null +++ b/src/base/utility/FBaseUtil_FileZipperImpl.cpp @@ -0,0 +1,228 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @File : FBaseUtil_FileZipperImpl.cpp + * @brief : Implementation for _FileZipperImpl Class + */ + +#include +#include +#include + +#include +#include +#include +#include + +#include "FBase_NativeError.h" +#include "FBaseUtil_FileUnzipperImpl.h" +#include "FBaseUtil_FileZipperImpl.h" + + +using namespace Tizen::Io; + +namespace Tizen { namespace Base { namespace Utility +{ + +struct ZipFileDeleter +{ + void operator ()(void* p) + { + if (p != null) + { + zipClose(p, null); + } + } +}; + +#define UNZ_COMP_CASE_SENSITIVE 1 +#define UNZ_COMP_NO_CASE_SENSITIVE 2 + +#define ZIP_WRITE_BUF_LEN 4096 + +_FileZipperImpl::_FileZipperImpl(void) + : __pArchiveName(null) + , __overwrite(false) +{ +} + +_FileZipperImpl::~_FileZipperImpl(void) +{ +} + +result +_FileZipperImpl::Construct(const String& filePath) +{ + SysAssertf(__pArchiveName == null, "Already constructed! " + "Calling Construct() twice or more on a same instance is not allowed for this class"); + + std::unique_ptr< ByteBuffer > pFilePathBuff(StringUtil::StringToUtf8N(filePath)); + SysTryReturnResult(NID_BASE_UTIL, pFilePathBuff != null, E_INVALID_ARG, "Invalid file path."); + + const char* pFilePath = reinterpret_cast (pFilePathBuff->GetPointer()); + + result r = IsFileExists(pFilePath); + SysTryReturnResult(NID_BASE_UTIL, (r == E_SUCCESS) || (r == E_FILE_NOT_FOUND), r, "Invalid file path [%s].", pFilePath); + + int createOption = (r == E_FILE_NOT_FOUND)? APPEND_STATUS_CREATE : APPEND_STATUS_ADDINZIP; + std::unique_ptr< void, ZipFileDeleter > pZfile(zipOpen(pFilePath, createOption)); + SysTryReturnResult(NID_BASE_UTIL, pZfile != null, E_IO, "Invalid file path [%s].", pFilePath); + + int len = strlen(pFilePath); + std::unique_ptr< char[] > pArchiveName(new (std::nothrow) char[len + 1]); + SysTryReturnResult(NID_BASE_UTIL, pArchiveName != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + strncpy(pArchiveName.get(), pFilePath, len); + pArchiveName[len] = 0; + + __pArchiveName = std::move(pArchiveName); + + ClearLastResult(); + return E_SUCCESS; +} + +result +_FileZipperImpl::AddToZip(const String& filePath, bool excludePath, CompressionLevel level) +{ + SysAssertf(__pArchiveName != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< ByteBuffer > pFilePathBuff(StringUtil::StringToUtf8N(filePath)); + SysTryReturnResult(NID_BASE_UTIL, pFilePathBuff != null, E_INVALID_ARG, "Invalid file path argument."); + + const char* pFilePath = reinterpret_cast (pFilePathBuff->GetPointer()); + + result r = IsFileExists(pFilePath); + SysTryReturnResult(NID_BASE_UTIL, r == E_SUCCESS, E_FILE_NOT_FOUND, "The file is not found."); + + const char* pFilePathForZip = pFilePath; + if (excludePath == true) + { + const char* pPos = strrchr(pFilePathForZip, '/'); + if (pPos) + { + pFilePathForZip = pPos; + } + + if (pFilePathForZip[0] == '/') + { + pFilePathForZip++; + } + } + +// while (pFilePathForZip[0] == '/' || pFilePathForZip[0] == '\\') +// { +// pFilePathForZip++; +// } + + int compLevel = DEFAULT_COMPRESSION; + if (level == BEST_SPEED) + { + compLevel = Z_BEST_SPEED; + } + else if (level == BEST_COMPRESSION) + { + compLevel = Z_BEST_COMPRESSION; + } + + if (_FileUnzipperImpl::IsFileExistsInZip(__pArchiveName.get(), pFilePathForZip)) + { + SysTryReturnResult(NID_BASE_UTIL, __overwrite == true, E_FILE_ALREADY_EXIST, "File already exist but overwrite flag is not set"); + return OverwriteInZip(pFilePath, pFilePathForZip, compLevel); + } + + return AddToZip(pFilePath, pFilePathForZip, compLevel); +} + + +bool +_FileZipperImpl::GetOverwriteFlag(void) const +{ + return __overwrite; +} + + +void +_FileZipperImpl::SetOverwriteFlag(bool flag) +{ + __overwrite = flag; +} + +result +_FileZipperImpl::AddToZip(const char* pFilePath, const char* pFilePathForZip, int level) +{ + int err = ZIP_OK; + result r = E_SUCCESS; + + std::unique_ptr< void, ZipFileDeleter > pZfile(zipOpen(__pArchiveName.get(), APPEND_STATUS_ADDINZIP)); + SysTryReturnResult(NID_BASE_UTIL, pZfile != null, E_IO, "Invalid file path [%s].", __pArchiveName.get()); + + zip_fileinfo zipInfo = {{0}}; + err = zipOpenNewFileInZip(pZfile.get(), pFilePathForZip, &zipInfo, null, 0, null, 0, null, Z_DEFLATED, level); + SysTryReturnResult(NID_BASE_UTIL, err == ZIP_OK, E_IO, "Failed to open new file in zip."); + + FILE* pFile = fopen(pFilePath, "r"); + if (pFile == null) + { + zipCloseFileInZip(pZfile.get()); + SysTryReturnResult(NID_BASE_UTIL, pFile != null, __ConvertNativeErrorToResult(errno), "[%s] Failed to open the file."); + } + + int readCnt = 1; + char buffer[ZIP_WRITE_BUF_LEN] = {0}; + while (readCnt > 0 && !feof(pFile)) + { + readCnt = fread(buffer, 1, ZIP_WRITE_BUF_LEN, pFile); + if (readCnt > 0) + { + err = zipWriteInFileInZip(pZfile.get(), buffer, readCnt); + SysTryCatch(NID_BASE_UTIL, err == ZIP_OK, r = E_IO, E_IO, "[%s] Failed to write in zip file.", GetErrorMessage(E_IO)); + } + } + + // fall through +CATCH: + zipCloseFileInZip(pZfile.get()); + if(pFile != null) + { + fclose(pFile); + } + + SetLastResult(r); + return r; +} + +result +_FileZipperImpl::OverwriteInZip(const char* pFilePath, const char* pFilePathForZip, int level) +{ + // TODO: Add Support for overwriting + return AddToZip(pFilePath, pFilePathForZip, level); +} + +result +_FileZipperImpl::IsFileExists(const char* pFilePath) +{ + if (access(pFilePath, F_OK) != 0) + { + return __ConvertNativeErrorToResult(errno); + } + + return E_SUCCESS; +} + + +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtil_FileZipperImpl.h b/src/base/utility/FBaseUtil_FileZipperImpl.h new file mode 100644 index 0000000..12c99af --- /dev/null +++ b/src/base/utility/FBaseUtil_FileZipperImpl.h @@ -0,0 +1,77 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtil_FileZipperImpl.h + * @brief This is the header file for the _FileZipperImpl class. + * + * This header file contains the declarations of the _FileZipperImpl class. + */ + +#ifndef _FBASE_UTIL_INTERNAL_FILEZIPPERIMPL_H_ +#define _FBASE_UTIL_INTERNAL_FILEZIPPERIMPL_H_ + +#include + +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +class _FileZipperImpl + : public Tizen::Base::Object +{ +public: + _FileZipperImpl(void); + virtual ~_FileZipperImpl(void); + + result Construct(const String& filePath); + + result AddToZip(const String& filePath, bool excludePath = true, CompressionLevel level = DEFAULT_COMPRESSION); + bool GetOverwriteFlag(void) const; + void SetOverwriteFlag(bool flag); + + +private: + /** + * This is the copy constructor for this class. + * @param [in] fileZipper The instance of the FileZip class to copy from + * @remarks This constructor is hidden. + */ + _FileZipperImpl(const _FileZipperImpl& fileZipper); + + /** + * This is the assignment operator. + * @param [in] fileZipper The instance of the FileZip class to assign from + * @remarks This operator is hidden. + */ + _FileZipperImpl& operator =(const _FileZipperImpl& fileZipper); + + result IsFileExists(const char* pFilePath); + result AddToZip(const char* pFilePath,const char* pFilePathForZip, int level); + result OverwriteInZip(const char* pFilePath, const char* pFilePathForZip, int level); + + std::unique_ptr< char[] > __pArchiveName; + bool __overwrite; + +}; // _FileZipperImpl + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_INTERNAL_FILEZIPPERIMPL_H_ diff --git a/src/base/utility/FBaseUtil_IcuConverter.cpp b/src/base/utility/FBaseUtil_IcuConverter.cpp new file mode 100644 index 0000000..1569e34 --- /dev/null +++ b/src/base/utility/FBaseUtil_IcuConverter.cpp @@ -0,0 +1,204 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @File : FBaseUtil_ICUConverter.cpp + * @brief : Implementation for _ICUConverter Class + */ +// Includes +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBase_StringConverter.h" +#include "FBase_NativeError.h" +#include +#include "FBaseUtil_IcuConverter.h" + + +namespace Tizen { namespace Base { namespace Utility +{ +_ICUConverter::_ICUConverter(void) + :__pConverter(null) +{ + +} +_ICUConverter::~_ICUConverter(void) +{ + if (__pConverter) + { + ucnv_close(__pConverter); + __pConverter = null; + } +} + +bool +_ICUConverter::OpenConverter(const Tizen::Base::String& encodingScheme) +{ + std::unique_ptr< char[] > pConverterName(_StringConverter::CopyToCharArrayN(encodingScheme)); + SysTryReturn(NID_BASE_UTIL, pConverterName != null, false, E_INVALID_ARG, "[%s] Invalid coding scheme.", GetErrorMessage(E_INVALID_ARG)); + UErrorCode err = U_ZERO_ERROR; + + if (!encodingScheme.CompareTo("UCS-2")) + { + __pConverter = ucnv_open("UTF-16LE", &err); + } + else + { + __pConverter = ucnv_open(pConverterName.get(), &err); + } + + result r = GetResultFromIcuErrorCode(err); + SysTryReturn(NID_BASE_UTIL, r == E_SUCCESS, false, r, "[%s] The err must be U_ZERO_ERROR.", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return true; +} + +void +_ICUConverter::CloseConverter(void) +{ + if (__pConverter) + { + ucnv_close(__pConverter); + __pConverter = null; + } +} + +char* +_ICUConverter::ConvertFromUcharN(const wchar_t* pSrc, int srcLength, int& retLength) +{ + UErrorCode errorCode = U_ZERO_ERROR; + result r = E_SUCCESS; + char* pOutBuf = null; + ucnv_setFromUCallBack(__pConverter, UCNV_FROM_U_CALLBACK_STOP, null, null, null, &errorCode); + + int outLen = 0; + int icuStrLen = srcLength * 2; + UChar* pIcuStr = new (std::nothrow) UChar[icuStrLen]; + SysTryReturn(NID_BASE_UTIL, pIcuStr != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + UChar* pResultStr = u_strFromWCS(pIcuStr, icuStrLen, &outLen, pSrc, srcLength, &errorCode); + if (U_SUCCESS(errorCode)) + { + char* pTmpOut = null; + int outBytesLeftOut = srcLength * 4; + pOutBuf = new (std::nothrow) char[outBytesLeftOut + 1]; + SysTryCatch(NID_BASE_UTIL, pOutBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + pTmpOut = pOutBuf; + memset(pOutBuf, 0, (outBytesLeftOut + 1)); + retLength = ucnv_fromUChars(__pConverter, pTmpOut, outBytesLeftOut, pResultStr, outLen, &errorCode); + r = GetResultFromIcuErrorCode(errorCode); + if (IsFailed(r)) + { + delete[] pOutBuf; + pOutBuf = null; + } + } + +CATCH: + delete[] pIcuStr; + pIcuStr = null; + SetLastResult(r); + return pOutBuf; +} + +wchar_t* +_ICUConverter::ConvertToUcharN(const char* src, int srcLength) +{ + UErrorCode errorCode = U_ZERO_ERROR; + ucnv_setToUCallBack(__pConverter, UCNV_TO_U_CALLBACK_STOP, null, null, null, &errorCode); + wchar_t* pDst = null; + wchar_t* pResultStr = null; + const char* pTmpIn = src; + int icuStrLen = (srcLength + 1); + UChar* pIcuStr = new (std::nothrow) UChar[icuStrLen]; + SysTryReturn(NID_BASE_UTIL, pIcuStr != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + memset(pIcuStr, 0, sizeof(UChar) * (icuStrLen)); + + signed int retLength = ucnv_toUChars(__pConverter, pIcuStr, icuStrLen, pTmpIn, srcLength, &errorCode); + result r = GetResultFromIcuErrorCode(errorCode); + if (U_SUCCESS(errorCode)) + { + pDst = new (std::nothrow) wchar_t[retLength + 1]; + SysTryCatch(NID_BASE_UTIL, pDst != null, , E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + memset(pDst, 0, sizeof(wchar_t) * (retLength + 1)); + pResultStr = u_strToWCS(pDst, retLength, &retLength, pIcuStr, retLength, &errorCode); + r = GetResultFromIcuErrorCode(errorCode); + if (IsFailed(r)) + { + delete[] pDst; + pDst = null; + } + } + +CATCH: + SetLastResult(r); + delete[] pIcuStr; + pIcuStr = null; + return pResultStr; +} + +result +_ICUConverter::GetResultFromIcuErrorCode(UErrorCode& err) +{ + if (U_FAILURE(err)) + { + switch (err) + { + case U_ZERO_ERROR: + return E_SUCCESS; + case U_MEMORY_ALLOCATION_ERROR: + return E_OUT_OF_MEMORY; + + case U_INDEX_OUTOFBOUNDS_ERROR: + return E_INVALID_ARG; + + case U_TRUNCATED_CHAR_FOUND: + // fall through to U_INVALID_CHAR_FOUND + case U_INVALID_CHAR_FOUND: + // fall through to U_ILLEGAL_CHAR_FOUND + case U_ILLEGAL_CHAR_FOUND: + return E_INVALID_ENCODING_RANGE; + + case U_INVALID_TABLE_FORMAT: + return E_SYSTEM; + + case U_BUFFER_OVERFLOW_ERROR: + return E_OVERFLOW; + + case U_STRING_NOT_TERMINATED_WARNING: + return E_INVALID_ARG; + + case U_ILLEGAL_ARGUMENT_ERROR: + return E_INVALID_ARG; + + case U_FILE_ACCESS_ERROR: + case U_AMBIGUOUS_ALIAS_WARNING: + return E_UNSUPPORTED_TYPE; + + default: + return E_SYSTEM; + } + } + return E_SUCCESS; +} +} } } // Tizen::Base::Utility diff --git a/src/base/utility/FBaseUtil_RegularExpressionImpl.cpp b/src/base/utility/FBaseUtil_RegularExpressionImpl.cpp new file mode 100644 index 0000000..fa27b2e --- /dev/null +++ b/src/base/utility/FBaseUtil_RegularExpressionImpl.cpp @@ -0,0 +1,1017 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @File : FBaseUtil_RegularExpressionImpl.cpp + * @brief : Implementation for _RegularExpressionImpl Class + */ + +//Includes +//#include "FBaseSysInternal.h" +#include +#include +#include +#include +#include +#include "FBaseUtil_RegularExpressionImpl.h" +#include "pcre.h" + +#define REGEX_MAX_GROUP_COUNT 16 + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Base { namespace Utility +{ + + +static int allOptions = + (REGEX_CASELESS | + REGEX_MULTI_LINE | + REGEX_DOTALL | + REGEX_EXTENDED | + REGEX_DOLLAR_ENDONLY | + REGEX_UNGREEDY | + REGEX_UNICODE + ); + +static char emptyString[1] = {'\0'}; + +struct RegExInfo +{ + void* pRe; // pcre object + char* pPattern; // regular expression pattern + unsigned long options; // options used while compiling + int* pOffsets; // array to store offsets while match + int offsetCount; // entries in offsets array + + // Valid in case of error + char* pError; // Error string if compilation fails + int errOffset; // Error offset in patter in case compilation fails +}; + +void +RegexFree(RegExInfo* pRegex) +{ + if (pRegex) + { + if (pRegex->pRe != null) + { + pcre_free(pRegex->pRe); + } + + if (pRegex->pPattern != emptyString) + { + free(pRegex->pPattern); + } + + if (pRegex->pError != emptyString) + { + free(pRegex->pError); + } + + if (pRegex->pOffsets != null) + { + free(pRegex->pOffsets); + } + + free(pRegex); + } +} + +int +RegexGetGroupCountInPattern(const char* pattern, int len) +{ + int grpCount = 0; + const char* pos = pattern + 1; + while ((--len) && (grpCount < REGEX_MAX_GROUP_COUNT)) + { + if (*pos == '(') + { + if (*(pos - 1) != '\\') + { + grpCount++; + } + } + pos++; + } + + return grpCount; +// return REGEX_MAX_GROUP_COUNT; +} +void +RegexAllocateOffset(RegExInfo* pRegex, int maxGroupCount) +{ + if (pRegex) + { + if (pRegex->pOffsets) + { + free(pRegex->pOffsets); + } + + if (maxGroupCount < REGEX_MAX_GROUP_COUNT) + { + maxGroupCount = REGEX_MAX_GROUP_COUNT; + } + + pRegex->offsetCount = (maxGroupCount + 1) * 3; + pRegex->pOffsets = (int*) calloc(pRegex->offsetCount, sizeof(int)); + } +} + + +_RegularExpressionImpl::_RegularExpressionImpl() + : __pReFull(null) + , __pRePartial(null) + , __options(0) + , __isCompilationRequired(true) + , __isLastMatchPartial(true) +{ +} + +_RegularExpressionImpl::~_RegularExpressionImpl() +{ + Cleanup(); +} + +void +_RegularExpressionImpl::Cleanup(void) +{ + if (__pReFull != null) + { + RegexFree((RegExInfo*) __pReFull); + __pReFull = null; + } + + if (__pRePartial != null) + { + RegexFree((RegExInfo*) __pRePartial); + __pRePartial = null; + } +} + +result +_RegularExpressionImpl::Construct(const String& pattern, unsigned long options) +{ + if (options & (~allOptions)) + { + return E_INVALID_ARG; + } + + result r = E_SUCCESS; + r = Init(pattern, options); + return r; +} + + +result +_RegularExpressionImpl::Init(const String& pattern, const int options) +{ + result r = E_SUCCESS; + __pattern = pattern; + __options = options; + __pReFull = null; + __pRePartial = null; + + __options |= PCRE_UTF8; + + __pRePartial = Compile(__pattern, __options, false); + if (null != __pRePartial) + { + __pReFull = Compile(__pattern, __options, true); + } + + r = GetLastResult(); + __isCompilationRequired = (r == E_SUCCESS) ? false : true; + + return r; +} + +void* +_RegularExpressionImpl::Compile(const String& pattern, int options, bool forFullMatch) +{ + RegExInfo* pRegex = null; + int lenPattern = 0; + result r = E_SUCCESS; + String pat = pattern; + if (forFullMatch) + { + r = pat.Insert("(?:", 0); + SysTryReturn(NID_BASE_UTIL, !IsFailed(r), null, r, "[%s] : Failed to insert string", GetErrorMessage(r)); + pat.Append(")\\z"); + } + + std::unique_ptr< ByteBuffer > pTmpBuf(StringUtil::StringToUtf8N(pat)); + + if (pTmpBuf) + { + int errorCode = 0; + lenPattern = pTmpBuf->GetLimit() - 1; + pRegex = (RegExInfo*) calloc(1, sizeof(RegExInfo)); + if(pRegex != null) + { + pRegex->pError = emptyString; + pRegex->options = options; + pTmpBuf->SetByte(lenPattern, '\0'); + pRegex->pRe = pcre_compile2((const char*) pTmpBuf->GetPointer(), // Pattern to compile + options, // Compile options + &errorCode, // Error code return by PCRE + (const char**) &pRegex->pError, // Pointer to string containing error message + &pRegex->errOffset, // Index in pattern, where error occurs + null // Passing null for pointer to character table so it will use default table. + ); + } + + if (0 != errorCode) + { + result r = PcreCompileErrorToSystemError(errorCode); + SetLastResult(r); + free(pRegex); + return null; + } + if(pRegex != null) + { + pRegex->pPattern = (char*) calloc(lenPattern, sizeof(char)); + if(pRegex->pPattern != null) + { + strncpy(pRegex->pPattern, (const char*) pTmpBuf->GetPointer(), lenPattern); + } + else + { + delete pRegex; + pRegex = null; + return null; + } + } + + // Allocating memory for offset array, to be used during match operation + RegexAllocateOffset(pRegex, RegexGetGroupCountInPattern((const char*) pTmpBuf->GetPointer(), lenPattern)); + + } + else + { + r = GetLastResult(); + } + + SetLastResult(r); + return (void*) pRegex; +} + +bool +_RegularExpressionImpl::Match(const Tizen::Base::String& text, bool fullMatch, IList* pMatchedString) +{ + int matchCount = 0; + ClearLastResult(); + + matchCount = Match(fullMatch, text, 0, 0); + if (pMatchedString && matchCount > 0) + { + GetLastMatchedGroups(text, *pMatchedString); + } + + SetLastResult(E_SUCCESS); + return(matchCount > 0); + +} + +int +_RegularExpressionImpl::Match(bool isFull, const String& text, int startPos, int matchOptions) +{ + result r = E_SUCCESS; + std::unique_ptr< ByteBuffer > pTmpBuf(null); + + bool containsNonAsciiChars = false; + + if (__isCompilationRequired || ((isFull) == false ? __pReFull : __pRePartial)) + { + if (__pRePartial && __pReFull) + { + Cleanup(); + } + Init(__pattern, __options); + } + + RegExInfo* pRegex = static_cast((isFull) ? __pReFull : __pRePartial); + if ((pRegex == null)) + { + SetLastResult(E_INVALID_STATE); + return -1; + } + if ((pRegex->pRe == null) || (pRegex->pOffsets == null)) + { + SetLastResult(E_INVALID_ARG); + return -1; + } + + if (isFull) + { + matchOptions |= PCRE_ANCHORED; + } + + if (text.IsEmpty()) + { + pTmpBuf.reset(new (std::nothrow) ByteBuffer); + if (!pTmpBuf) + { + SetLastResult(E_OUT_OF_MEMORY); + return -1; + } + r = pTmpBuf->Construct(1); + if(IsFailed(r) == true) + { + SetLastResult(r); + return -1; + } + r = pTmpBuf->SetByte('\0'); + if(IsFailed(r) == true) + { + SetLastResult(r); + return -1; + } + + } + else + { + pTmpBuf.reset(StringUtil::StringToUtf8N(text)); + if (!pTmpBuf) + { + return -1; + } + + pTmpBuf->SetByte(pTmpBuf->GetLimit() - 1, '\0'); + + if ((pTmpBuf->GetLimit() - 1) != text.GetLength()) + { + containsNonAsciiChars = true; + startPos = StringToUtf8Index(text, startPos); + } + } + + // Ressting offset array to invalid values + memset(pRegex->pOffsets, -1, pRegex->offsetCount * sizeof(int)); + int matchCount = pcre_exec((pcre*) (pRegex->pRe), // the regular expression object + null, // &extra, + (const char*) pTmpBuf->GetPointer(), // pointer to subject string + pTmpBuf->GetLimit() - 1, // length of subject string + startPos, // where to start in the subject string + matchOptions, // option bits + pRegex->pOffsets, // points to a vector of ints to be filled in with offsets + pRegex->offsetCount // the number of elements in the vector + ); + if (matchCount == PCRE_ERROR_NOMATCH) + { + return 0; + } + + if (matchCount < 0) + { + SetLastResult(PcreExecErrorToSystemError(matchCount)); + return -1; + } + + // To handle cases where captured strings count is grater than offset count + if (matchCount == 0) + { + matchCount = pRegex->offsetCount / 2; + } + + if (containsNonAsciiChars) + { + int offsetCnt = matchCount * 2; + for (int i = 0; i < offsetCnt; i += 2) + { + pRegex->pOffsets[i] = Utf8ToStringIndex((char*) pTmpBuf->GetPointer(), pRegex->pOffsets[i]); + pRegex->pOffsets[i + 1] = Utf8ToStringIndex((char*) pTmpBuf->GetPointer(), pRegex->pOffsets[i + 1]); + } + } + + SetLastResult(E_SUCCESS); + + __isLastMatchPartial = !isFull; + return matchCount; +} + +bool +_RegularExpressionImpl::Consume(Tizen::Base::String& text, Tizen::Base::Collection::IList* pMatchedString) +{ + result r = E_SUCCESS; + int matchCount = 0; + ClearLastResult(); + + matchCount = Match(false, text, 0, PCRE_ANCHORED); + if (matchCount > 0) + { + if (pMatchedString) + { + r = GetLastMatchedGroups(text, *pMatchedString); + if (IsFailed(r)) + { + goto CATCH; + } + } + + r = text.Remove(0, GetLastMatchEnd()); + if (IsFailed(r)) + { + goto CATCH; + } + + SetLastResult(E_SUCCESS); + return true; + } +CATCH: + SetLastResult(r); + return false; + +} + +bool +_RegularExpressionImpl::FindAndConsume(Tizen::Base::String& text, Tizen::Base::Collection::IList* pMatchedString) +{ + result r = E_SUCCESS; + int matchCount = 0; + ClearLastResult(); + + matchCount = Match(false, text, 0, 0); + if (matchCount > 0) + { + if (pMatchedString) + { + r = GetLastMatchedGroups(text, *pMatchedString); + if (IsFailed(r)) + { + goto CATCH; + } + } + + r = text.Remove(0, GetLastMatchEnd()); + if (IsFailed(r)) + { + goto CATCH; + } + } + + SetLastResult(r); + return true; + +CATCH: + SetLastResult(r); + return false; +} + +bool +_RegularExpressionImpl::Replace(Tizen::Base::String& text, const Tizen::Base::String& rewrite, bool globalReplace, int startPos) +{ + result r = E_SUCCESS; + int count = 0; + String out; + int lenText = text.GetLength(); + bool isMatchEmpty = false; + + ClearLastResult(); + + if (startPos > 0) + { + r = text.SubString(0, startPos, out); + if (IsFailed(r)) + { + goto CATCH; + } + } + + while (startPos <= text.GetLength()) + { + int matchCount = 0; + int matchStart = 0; + int matchEnd = 0; + String out1; + + if (isMatchEmpty) + { + matchCount = Match(false, text, startPos, PCRE_ANCHORED | PCRE_NOTEMPTY); + if ((matchCount <= 0)) + { + if (startPos < text.GetLength()) + { + r = out.Append(text[startPos]); + if (IsFailed(r)) + { + goto CATCH; + } + } + + startPos++; + isMatchEmpty = false; + continue; + } + } + else + { + matchCount = Match(false, text, startPos, 0); + if (matchCount <= 0) + { + break; + } + } + + matchStart = GetLastMatchStart(); + matchEnd = GetLastMatchEnd(); + + if ((matchStart < startPos) || (matchEnd < matchStart)) + { + r = GetLastResult(); + goto CATCH; + } + + if (matchStart > startPos) + { + r = text.SubString(startPos, matchStart - startPos, out1); + if (IsFailed(r)) + { + goto CATCH; + } + out.Append(out1); + } + + r = Rewrite(rewrite, text, out1); + if (IsFailed(r)) + { + goto CATCH; + } + out.Append(out1); + + startPos = matchEnd; + count++; + isMatchEmpty = (matchStart == matchEnd); + + if (!globalReplace) + { + break; + } + + } + + if (count == 0) + { + r = GetLastResult(); + goto CATCH; + } + + if (startPos < lenText) + { + String out1; + r = text.SubString(startPos, lenText - startPos, out1); + if (IsFailed(r)) + { + goto CATCH; + } + out.Append(out1); + } + + text = out; + + SetLastResult(E_SUCCESS); + return true; + +CATCH: + SetLastResult(r); + return false; +} + +bool +_RegularExpressionImpl::Extract(const Tizen::Base::String& text, const Tizen::Base::String& rewrite, Tizen::Base::String& out) +{ + result r = E_SUCCESS; + int matchCount = 0; + + ClearLastResult(); + + matchCount = Match(false, text, 0, 0); + if (matchCount <= 0) + { + goto CATCH; + } + + r = Rewrite(rewrite, text, out); + if (IsFailed(r)) + { + goto CATCH; + } + + return true; + +CATCH: + SetLastResult(r); + return false; +} + +Tizen::Base::String +_RegularExpressionImpl::GetPattern(void) const +{ + return __pattern; +} + +result +_RegularExpressionImpl::SetOptions(unsigned long options) +{ + if (options & (~allOptions)) + { + return E_INVALID_ARG; + } + + __options = options; + + if (!(options && PCRE_NOTEMPTY)) + { + __isCompilationRequired = true; + } + return E_SUCCESS; +} + +unsigned long +_RegularExpressionImpl::GetOptions(void) const +{ + return __options; +} + + +result +_RegularExpressionImpl::GetLastMatchedGroups(const String& text, IList& matchedGrpStrList) +{ + result r = E_SUCCESS; + RegExInfo* pRegex = static_cast((__isLastMatchPartial) ? __pRePartial : __pReFull); + if (pRegex) + { + int grpCount = GetLastGroupCount(); + if (grpCount < 0) + { + return E_INVALID_STATE; + } + + grpCount = (grpCount + 1) * 2; + for (int i = 0; i < grpCount; i += 2) + { + String* pTmpStr = new (std::nothrow) String(); + if (pRegex->pOffsets[i] >= 0 && (pRegex->pOffsets[i] < pRegex->pOffsets[i + 1])) + { + r = text.SubString(pRegex->pOffsets[i], pRegex->pOffsets[i + 1] - pRegex->pOffsets[i], *pTmpStr); + if (IsFailed(r)) + { + delete pTmpStr; + pTmpStr = null; + goto FAILED; + } + } + + r = matchedGrpStrList.Add(*pTmpStr); + if (IsFailed(r)) + { + goto FAILED; + } + } + return E_SUCCESS; + } + +FAILED: + matchedGrpStrList.RemoveAll(true); + return r; +} + +int +_RegularExpressionImpl::GetLastGroupCount(void) +{ + int grpCount = 0; + RegExInfo* pRegex = static_cast((__isLastMatchPartial) ? __pRePartial : __pReFull); + if (pRegex == null) + { + + SetLastResult(E_INVALID_STATE); + return -1; + } + if (pRegex->pRe == null) + { + SetLastResult(E_INVALID_ARG); + return -1; + } + + int retValue = pcre_fullinfo((pcre*) (pRegex->pRe), // the regular expression object + null, // points extra data, or null + PCRE_INFO_CAPTURECOUNT, // what information is required + (void*) &grpCount // where to put the information + ); + +// Handling error + if ((0 != retValue) || (grpCount < -1)) + { + return -1; + } + + return grpCount; +} +int +_RegularExpressionImpl::StringToUtf8Index(const Tizen::Base::String text, int index) +{ + int newIndex = -1; + String tmpStr; + + if (index == 0) + { + return 0; + } + result r = text.SubString(0, index, tmpStr); + if (!IsFailed(r)) + { + std::unique_ptr< ByteBuffer > pTmpBuf(StringUtil::StringToUtf8N(tmpStr)); + if (pTmpBuf) + { + newIndex = pTmpBuf->GetLimit() - 1; + } + } + +// SysLogExceptionxception("[%s] Regex: StringToUtf8Index failed", GetErrorMessage(r)); + return newIndex; +} +int +_RegularExpressionImpl::Utf8ToStringIndex(char* pUtf8String, int index) +{ + if (index == 0) + { + return 0; + } + + int newIndex = -1; + String tmpStr; + if (pUtf8String) + { + int byteAtIndex = pUtf8String[index]; + pUtf8String[index] = '\0'; + + result r = StringUtil::Utf8ToString(pUtf8String, tmpStr); + if (!IsFailed(r)) + { + newIndex = tmpStr.GetLength(); + } + else + { +// SysLogExceptionxception("[%s] Regex: Utf8ToStringIndex failed", GetErrorMessage(r)); + } + + pUtf8String[index] = byteAtIndex; + } + + return newIndex; +} + +int +_RegularExpressionImpl::CheckRewritePattern(const Tizen::Base::String& rewrite) +{ + byte c = '\0'; + result r = E_SUCCESS; + int maxGrpNum = -1; + std::unique_ptr< ByteBuffer > pTmpBuf(StringUtil::StringToUtf8N(rewrite)); + if (pTmpBuf) + { + int limit = pTmpBuf->GetLimit(); + while (limit > pTmpBuf->GetPosition()) + { + if (IsFailed(pTmpBuf->GetByte(c))) + { + break; + } + + if (c == '\\') + { + if (IsFailed(pTmpBuf->GetByte(c))) + { + r = E_INVALID_ARG; + break; + } + + if ((c >= '0') && (c <= '9')) + { + int n = (c - '0'); + if (n > maxGrpNum) + { + maxGrpNum = n; + } + } + else if (c != '\\') + { + r = E_INVALID_ARG; + break; + } + } + } + } + + SetLastResult(r); + return maxGrpNum; +} + +result +_RegularExpressionImpl::Rewrite(const String& rewrite, const String& text, String& out) +{ + result r = E_UNKNOWN; + int index = 0; + int maxCount = 0; + ArrayList matchedGrpStrList; + + maxCount = CheckRewritePattern(rewrite); + r = GetLastResult(); + if (IsFailed(r)) + { + return r; + } + + if (maxCount == -1) + { + out = rewrite; + return E_SUCCESS; + } + + if (maxCount == 0) + { + String matchedStr = GetLastMatchedString(text); + out = rewrite; + return out.Replace("\\0", matchedStr); + } + + String out1(rewrite); + r = matchedGrpStrList.Construct(REGEX_MAX_GROUP_COUNT); + if (IsFailed(r)) + { + goto FAILED; + } + + r = GetLastMatchedGroups(text, matchedGrpStrList); + if (maxCount >= matchedGrpStrList.GetCount()) + { + goto FAILED; + } + + if (!IsFailed(r)) + { + for (index = 0; index <= maxCount; index++) + { + String* pTemp = static_cast(matchedGrpStrList.GetAt(index)); + if (pTemp) + { + String tmp1("\\"); + r = tmp1.Append(index); + if (!IsFailed(r)) + { + r = out1.Replace(tmp1, *pTemp); + } + + if (IsFailed(r)) + { + goto FAILED; + } + } + } + } + + if (!IsFailed(r)) + { + out = out1; + } + +FAILED: + matchedGrpStrList.RemoveAll(true); + return r; +} + + +int +_RegularExpressionImpl::GetLastMatchStart(void) +{ + RegExInfo* pRegEx = static_cast((__isLastMatchPartial) ? __pRePartial : __pReFull); + if (pRegEx) + { + return pRegEx->pOffsets[0]; + } + + return -1; +} + +int +_RegularExpressionImpl::GetLastMatchEnd(void) +{ + RegExInfo* pRegEx = static_cast((__isLastMatchPartial) ? __pRePartial : __pReFull); + if (pRegEx) + { + return pRegEx->pOffsets[1]; + } + + return -1; +} + +String +_RegularExpressionImpl::GetLastMatchedString(const String& text) +{ + String out(""); + result r = E_SUCCESS; + RegExInfo* pRegEx = static_cast((__isLastMatchPartial) ? __pRePartial : __pReFull); + if (pRegEx && pRegEx->pOffsets[0] > -1 && pRegEx->pOffsets[1] > -1) + { + r = text.SubString(pRegEx->pOffsets[0], pRegEx->pOffsets[1] - pRegEx->pOffsets[0], out); + + } + + SetLastResult(r); + return out; +} +result +_RegularExpressionImpl::PcreCompileErrorToSystemError(int compileErr) +{ + switch (compileErr) + { + case 23: + //fall through + case 52: + return E_SYSTEM; + + case 21: + return E_OUT_OF_MEMORY; + + default: + return E_INVALID_ARG; + } +} + +result +_RegularExpressionImpl::PcreExecErrorToSystemError(int err) +{ + switch (err) + { + case PCRE_ERROR_NOMATCH: + return E_SUCCESS; + +// case PCRE_ERROR_NULL: + case PCRE_ERROR_NOSUBSTRING: + //fall through + case PCRE_ERROR_MATCHLIMIT: + //fall through + case PCRE_ERROR_CALLOUT: + //fall through + case PCRE_ERROR_PARTIAL: + //fall through + case PCRE_ERROR_BADPARTIAL: + //fall through + case PCRE_ERROR_INTERNAL: + //fall through + case PCRE_ERROR_BADCOUNT: + //fall through + case PCRE_ERROR_DFA_UITEM: + //fall through + case PCRE_ERROR_DFA_UCOND: + //fall through + case PCRE_ERROR_DFA_UMLIMIT: + //fall through + case PCRE_ERROR_DFA_WSSIZE: + //fall through + case PCRE_ERROR_DFA_RECURSE: + //fall through + case PCRE_ERROR_RECURSIONLIMIT: + //fall through + case PCRE_ERROR_NULLWSLIMIT: + return E_SYSTEM; + + case PCRE_ERROR_NULL: + //fall through + case PCRE_ERROR_BADOPTION: + //fall through + case PCRE_ERROR_BADMAGIC: + //fall through + case PCRE_ERROR_UNKNOWN_OPCODE: + //fall through +// case PCRE_ERROR_UNKNOWN_NODE: + case PCRE_ERROR_BADUTF8: + //fall through + case PCRE_ERROR_BADUTF8_OFFSET: + //fall through + case PCRE_ERROR_BADNEWLINE: +// case PCRE_ERROR_BADOFFSET: +// case PCRE_ERROR_SHORTUTF8: + return E_INVALID_ARG; + + case PCRE_ERROR_NOMEMORY: + return E_OUT_OF_MEMORY; + } + return E_SUCCESS; +} +}}} diff --git a/src/base/utility/FBaseUtil_RegularExpressionImpl.h b/src/base/utility/FBaseUtil_RegularExpressionImpl.h new file mode 100644 index 0000000..d1548e1 --- /dev/null +++ b/src/base/utility/FBaseUtil_RegularExpressionImpl.h @@ -0,0 +1,98 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtil_RegularExpressionImpl.h + * @brief This is the header file for the _RegularExpressionImpl class. + * This header file contains the declarations of the _RegularExpressionImpl class. + */ + +#ifndef _FBASE_UTIL_INTERNAL_REGULAREXPRESSIONIMPL_H_ +#define _FBASE_UTIL_INTERNAL_REGULAREXPRESSIONIMPL_H_ + +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +class _RegularExpressionImpl + : public Tizen::Base::Object +{ +public: + _RegularExpressionImpl(void); + virtual ~_RegularExpressionImpl(void); + + result Construct(const Tizen::Base::String& pattern, unsigned long options); + bool Match(const Tizen::Base::String& text, bool fullMatch, Tizen::Base::Collection::IList* pMatchedString); + bool Consume(String& text, Tizen::Base::Collection::IList* pMatchedString); + bool FindAndConsume(Tizen::Base::String& text, Tizen::Base::Collection::IList* pMatchedString); + bool Replace(Tizen::Base::String& text, const Tizen::Base::String& rewrite, bool globalReplace, int startPos); + bool Extract(const Tizen::Base::String& text, const Tizen::Base::String& rewrite, Tizen::Base::String& out); + Tizen::Base::String GetPattern(void) const; + result SetOptions(unsigned long options); + unsigned long GetOptions(void) const; + + +private: + void Cleanup(void); + // Initializes _RegularExpressionImpl object + result Init(const Tizen::Base::String& pattern, const int options); + + int Match(bool isFull, const Tizen::Base::String& text, int startPos, int matchOptions); + + // Compiles _RegularExpressionImpl object with supplied pattern and options + void* Compile(const Tizen::Base::String& pattern, int options, bool forFullMatch); + + result Rewrite(const Tizen::Base::String& rewrite, const Tizen::Base::String& text, Tizen::Base::String& out); + + // Convert index pointing to Sting index [wchar_t] to char array [UTF8] + int StringToUtf8Index(const Tizen::Base::String text, int index); + + // Convert index pointing to char array [UTF8] to Sting index [wchar_t] + int Utf8ToStringIndex(char* pUtf8String, int index); + + int CheckRewritePattern(const Tizen::Base::String& rewrite); + result GetLastMatchedGroups(const Tizen::Base::String& text, Tizen::Base::Collection::IList& matchedGrpStrList); + String GetLastMatchedString(const Tizen::Base::String& text); + int GetLastGroupCount(void); + + int GetLastMatchStart(void); + int GetLastMatchEnd(void); + result PcreCompileErrorToSystemError(int compileErr); + result PcreExecErrorToSystemError(int err); + + Tizen::Base::String __pattern; + void* __pReFull; + void* __pRePartial; + + unsigned long __options; + bool __isCompilationRequired; + bool __isLastMatchPartial; + + friend class RegularExpression; + +}; // _RegularExpressionImpl + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_INTERNAL_REGULAREXPRESSIONIMPL_H_ diff --git a/src/base/utility/FBaseUtil_ZipEntryInfo.h b/src/base/utility/FBaseUtil_ZipEntryInfo.h new file mode 100644 index 0000000..794e17c --- /dev/null +++ b/src/base/utility/FBaseUtil_ZipEntryInfo.h @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FBaseUtil_ZipEntryInfo.h + * @brief This is the header file for _ZipEntryInfo. + */ + +#ifndef _FBASE_UTIL_ZIP_ENTRY_INFO_H_ +#define _FBASE_UTIL_ZIP_ENTRY_INFO_H_ + +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Utility +{ + +class _ZipEntryInfo +{ + +public: + ~_ZipEntryInfo(void) + { + } + +private: + _ZipEntryInfo(void) + : __unzFile(null) + , __compressionLevel(DEFAULT_COMPRESSION) + , __isDirectory(false) + , __compressedSize(0) + , __uncompressedSize(0) + , __method(0) + { + } + +public: + unzFile __unzFile; + String __name; + CompressionLevel __compressionLevel; + bool __isDirectory; + int __compressedSize; + int __uncompressedSize; + String __archiveName; + int __method; + +private: + friend class _FileUnzipperImpl; + +}; // _ZipEntryInfo + +}}} // Tizen::Base::Utility + +#endif // _FBASE_UTIL_ZIP_ENTRY_INFO_H_ diff --git a/src/io/CMakeLists.txt b/src/io/CMakeLists.txt new file mode 100755 index 0000000..c5f3185 --- /dev/null +++ b/src/io/CMakeLists.txt @@ -0,0 +1,94 @@ +SET (this_target io) + +INCLUDE_DIRECTORIES ( + ${SLP_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/inc + ${CMAKE_SOURCE_DIR}/src/base/inc + ${CMAKE_SOURCE_DIR}/src/app/inc + ${CMAKE_SOURCE_DIR}/src/security/inc + ${CMAKE_SOURCE_DIR}/src/system/inc + inc + ) + +SET (${this_target}_SOURCE_FILES + FIo_ChannelManager.cpp + FIo_Channel.cpp + FIoClientChannel.cpp + FIo_ClientChannelImpl.cpp + FIo_ChannelService.cpp + FIoServerChannel.cpp + FIo_ServerChannelImpl.cpp + FIoDatabase.cpp + FIo_DatabaseImpl.cpp + FIoDbEnumerator.cpp + FIo_DbEnumeratorImpl.cpp + FIoDbStatement.cpp + FIo_DbStatementImpl.cpp + FIoSqlStatementBuilder.cpp + FIo_DbContextImpl.cpp + FIoDirEntry.cpp + FIo_DirEntryImpl.cpp + FIoDirEnumerator.cpp + FIo_DirEnumeratorImpl.cpp + FIoDirectory.cpp + FIo_DirectoryImpl.cpp + FIo_NormalFile.cpp + FIo_NormalRegistry.cpp + FIo_SecureFile.cpp + FIo_SecureIoUtil.cpp + FIo_SecureRegistry.cpp + FIo_FileUtil.cpp + FIoFile.cpp + FIo_FileImpl.cpp + FIoFileAttributes.cpp + FIo_FileAttributesImpl.cpp + FIoFileEventManager.cpp + FIo_FileEventManagerImpl.cpp + FIoRegistry.cpp + FIo_RegistryImpl.cpp + FIo_RegistryCore.cpp + FIo_IpcClient.cpp + FIo_IpcServer.cpp + FIo_IIpcClientEventListener.cpp + FIo_IIpcServerEventListener.cpp + FIo_ChannelMessages.cpp + FIo_ChannelServiceProxy.cpp + FIo_ChannelServiceStub.cpp + FIo_ChannelServiceManager.cpp + FIo_DataControlResultSetImpl.cpp + FIo_DataControlResultSetEnumerator.cpp + FIoSerialPort.cpp + FIo_SerialPortImpl.cpp + FIo_DataRouter.cpp + FIo_ServiceMessage.cpp + FIoMemoryMappedFile.cpp + FIo_MemoryMappedFileImpl.cpp + FIo_ChannelCAppStub.cpp + FIo_ChannelWebAppStub.cpp + FIoMmcStorageManager.cpp + FIo_MmcStorageManagerImpl.cpp + FIo_MmcStorageManagerIpcMessages.cpp + FIo_MmcStorageManagerProxy.cpp + FIoMessagePortManager.cpp + FIo_MessagePortManagerImpl.cpp + FIoLocalMessagePort.cpp + FIo_LocalMessagePortImpl.cpp + FIoRemoteMessagePort.cpp + FIo_RemoteMessagePortImpl.cpp + FIo_MessagePortMessages.cpp + FIo_MessagePortProxy.cpp + ) + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") +## SET EXTRA COMPILER FLAGS +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fPIC -DSQLITE_HAS_CODEC") + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} STATIC ${${this_target}_SOURCE_FILES}) + diff --git a/src/io/FIoClientChannel.cpp b/src/io/FIoClientChannel.cpp new file mode 100644 index 0000000..1e9d258 --- /dev/null +++ b/src/io/FIoClientChannel.cpp @@ -0,0 +1,126 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoClientChannel.cpp + * @brief This is the implementation file for the ClientChannel class. + * + */ + +#include +#include +#include + +#include +#include +#include +#include "FIo_ClientChannelImpl.h" + + +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +ClientChannel* ClientChannel::__pClientChannelInstance = null; + +ClientChannel::ClientChannel(void) + : __pClientChannelImpl(null) +{ +} + +ClientChannel::~ClientChannel(void) +{ + delete __pClientChannelImpl; +} + +void +ClientChannel::SetChannelResponseEventListener(IChannelResponseEventListener* pResponseListener) +{ + SysAssertf(__pClientChannelImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + __pClientChannelImpl->SetChannelResponseEventListener(pResponseListener); +} + +result +ClientChannel::SendRequest(const String& serverChannelId, const IList* pArgs, RequestId& reqId) +{ + SysAssertf(__pClientChannelImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysTryReturnResult(NID_IO, !serverChannelId.IsEmpty(), E_OBJ_NOT_FOUND, "The server channel is not found."); + + return __pClientChannelImpl->SendRequest(serverChannelId, pArgs, reqId); +} + +ClientChannel* +ClientChannel::GetInstance(void) +{ + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + if (__pClientChannelInstance == null) + { + ClearLastResult(); + + pthread_once(&onceBlock, InitSingleton); + result r = GetLastResult(); + if (IsFailed(r)) + { + onceBlock = PTHREAD_ONCE_INIT; + SysPropagate(NID_IO, r); + } + } + + return __pClientChannelInstance; +} + +ClientChannel* +ClientChannel::GetInstance(const String& channelName) +{ + ClientChannel* pClientChannel = _ClientChannelImpl::GetClientChannel(channelName); + SysTryReturn(NID_IO, pClientChannel != null, null, E_SYSTEM, "[E_SYSTEM] Failed to create a client channel."); + + return pClientChannel; +} + +void +ClientChannel::InitSingleton(void) +{ + ClientChannel* pInst = new (std::nothrow) ClientChannel(); + SysTryReturnVoidResult(NID_IO, pInst, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pInst->__pClientChannelImpl = _ClientChannelImpl::GetInstance(pInst); + SysTryCatch(NID_IO, pInst->__pClientChannelImpl != null, , E_SYSTEM, + "[E_SYSTEM] Failed to initialize the client channel."); + + __pClientChannelInstance = pInst; + std::atexit(DestroySingleton); + return; + +CATCH: + delete pInst; +} + +void +ClientChannel::DestroySingleton(void) +{ + delete __pClientChannelInstance; +} + +} } // Tizen::Io diff --git a/src/io/FIoDatabase.cpp b/src/io/FIoDatabase.cpp new file mode 100644 index 0000000..5d30282 --- /dev/null +++ b/src/io/FIoDatabase.cpp @@ -0,0 +1,255 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDatabase.cpp + * @brief This is the implementation file for Database class. + */ + +#include +#include +#include + +#include +#include +#include +#ifdef _OSP_EMUL_ +#include +#else +#include +#endif +#include +#include +#include +#include + +#include +#include + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; +using namespace Tizen::System; + +namespace Tizen { namespace Io +{ + +Database::Database(void) + : __pDatabaseImpl(null) +{ +} + +Database::~Database(void) +{ + delete __pDatabaseImpl; +} + +result +Database::Construct(const String& dbPath, bool createIfNotExist) +{ + SysAssertf(__pDatabaseImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + SysTryReturnResult(NID_IO, dbPath.GetLength() > 0 && dbPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "Wrong path length."); + + unique_ptr<_DatabaseImpl> pDatabaseImpl(new (std::nothrow) _DatabaseImpl); + SysTryReturnResult(NID_IO, pDatabaseImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pDatabaseImpl->Construct(dbPath, createIfNotExist); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pDatabaseImpl = pDatabaseImpl.release(); + + return E_SUCCESS; +} + +result +Database::Construct(const String& dbPath, long openMode, long option) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, dbPath.GetLength() > 0 && dbPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The length of the specified dbPath is zero or exceeds system limitations."); + + SysAssertf(__pDatabaseImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + unique_ptr<_DatabaseImpl> pDatabaseImpl(new (std::nothrow) _DatabaseImpl); + SysTryReturnResult(NID_IO, pDatabaseImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pDatabaseImpl->Construct(dbPath, openMode, null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pDatabaseImpl = pDatabaseImpl.release(); + + return E_SUCCESS; +} + +result +Database::Construct(const String& dbPath, const char* pOpenMode) +{ + SysAssertf(__pDatabaseImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, dbPath.GetLength() > 0 && dbPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The length of the specified dbPath is zero or exceeds system limitations."); + + unique_ptr<_DatabaseImpl> pDatabaseImpl(new (std::nothrow) _DatabaseImpl); + SysTryReturnResult(NID_IO, pDatabaseImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pDatabaseImpl->Construct(dbPath, pOpenMode, null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pDatabaseImpl = pDatabaseImpl.release(); + + return E_SUCCESS; +} + +result +Database::Construct(const String& dbPath, const char* pOpenMode, const ByteBuffer& secureKey) +{ + SysAssertf(__pDatabaseImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, dbPath.GetLength() > 0 && dbPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The length of the specified dbPath is zero or exceeds system limitations."); + SysTryReturnResult(NID_IO, secureKey.GetRemaining() > 0, E_INVALID_ARG, "The length of the specified secureKey is zero."); + + unique_ptr<_DatabaseImpl> pDatabaseImpl(new (std::nothrow) _DatabaseImpl); + SysTryReturnResult(NID_IO, pDatabaseImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + +#ifndef _OSP_EMUL_ + result r = pDatabaseImpl->Construct(dbPath, pOpenMode, &secureKey); +#else + result r = pDatabaseImpl->Construct(dbPath, pOpenMode, null); +#endif + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pDatabaseImpl = pDatabaseImpl.release(); + + return E_SUCCESS; +} + +DbStatement* +Database::CreateStatementN(const String& statement) +{ + SysTryReturn(NID_IO, statement.GetLength() > 0, null, E_INVALID_ARG, + "[E_INVALID_ARG] The length of SQL statement is zero."); + + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pDatabaseImpl->CreateStatementN(statement); +} + +DbEnumerator* +Database::ExecuteStatementN(const DbStatement& dbStatement) +{ + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pDatabaseImpl->ExecuteStatementN(dbStatement); +} + +result +Database::ExecuteSql(const String& statement, bool autoCommit) +{ + SysTryReturnResult(NID_IO, statement.GetLength() > 0, E_INVALID_ARG, + "The length of SQL statement is zero."); + + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pDatabaseImpl->ExecuteSql(statement, autoCommit); +} + +DbEnumerator* +Database::QueryN(const String& statement) +{ + SysTryReturn(NID_IO, statement.GetLength() > 0, null, E_INVALID_ARG, + "[E_INVALID_ARG] The length of SQL statement is zero."); + + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pDatabaseImpl->QueryN(statement); +} + +result +Database::BeginTransaction(void) +{ + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pDatabaseImpl->BeginTransaction(); +} + +result +Database::CommitTransaction(void) +{ + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pDatabaseImpl->CommitTransaction(); +} + +result +Database::RollbackTransaction(void) +{ + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pDatabaseImpl->RollbackTransaction(); +} + +String +Database::GetName(void) const +{ + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pDatabaseImpl->GetName(); +} + +result +Database::Delete(const String& dbPath) +{ + SysTryReturnResult(NID_IO, dbPath.GetLength() > 0 && dbPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The length of the specified dbPath is zero or exceeds system limitations."); + + return _DatabaseImpl::Delete(dbPath); +} + +bool +Database::Exists(const String& dbPath) +{ + SysTryReturn(NID_IO, dbPath.GetLength() > 0 && dbPath.GetLength() <= PATH_MAX, false, E_INVALID_ARG, + "[E_INVALID_ARG] The length of the specified dbPath is zero or exceeds system limitations."); + + return _DatabaseImpl::Exists(dbPath); +} + +result +Database::ConvertToSecureDatabase(const String& normalDbPath, const String& secureDbPath, const ByteBuffer& secretKey) +{ +#ifndef _OSP_EMUL_ + bool secure = false; + result r = SystemInfo::GetValue(L"http://tizen.org/feature/database.encryption", secure); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "The method cannot proceed due to a severe system error."); + SysTryReturnResult(NID_IO, secure == true, E_UNSUPPORTED_OPERATION, "This operation is not supported."); + return _DatabaseImpl::ConvertToSecureDatabase(normalDbPath, secureDbPath, &secretKey); +#else + return File::Copy(normalDbPath, secureDbPath, true); +#endif +} + +long long +Database::GetLastInsertRowId(void) const +{ + SysAssertf(__pDatabaseImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pDatabaseImpl->GetLastInsertRowId(); +} + +}} // Tizen::Io + diff --git a/src/io/FIoDbEnumerator.cpp b/src/io/FIoDbEnumerator.cpp new file mode 100644 index 0000000..4adcdfa --- /dev/null +++ b/src/io/FIoDbEnumerator.cpp @@ -0,0 +1,159 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDbEnumerator.cpp + * @brief This is the implementation file for DbEnumerator class. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Io +{ + +DbEnumerator::DbEnumerator(void) + : __pDbEnumeratorImpl(null) +{ + + __pDbEnumeratorImpl = new (std::nothrow)_DbEnumeratorImpl; + + SysTryReturnVoidResult(NID_IO, __pDbEnumeratorImpl != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); +} + +DbEnumerator::~DbEnumerator(void) +{ + delete __pDbEnumeratorImpl; +} + +result +DbEnumerator::MoveNext(void) +{ + return __pDbEnumeratorImpl->MoveNext(); +} + +result +DbEnumerator::MovePrevious(void) +{ + return __pDbEnumeratorImpl->MovePrevious(); +} + +result +DbEnumerator::MoveFirst(void) +{ + return __pDbEnumeratorImpl->MoveFirst(); +} + +result +DbEnumerator::MoveLast(void) +{ + return __pDbEnumeratorImpl->MoveLast(); +} + +result +DbEnumerator::Reset(void) +{ + return __pDbEnumeratorImpl->Reset(); +} + +result +DbEnumerator::GetIntAt(int columnIndex, int& value) const +{ + return __pDbEnumeratorImpl->GetIntAt(columnIndex, value); +} + +result +DbEnumerator::GetInt64At(int columnIndex, long long& value) const +{ + return __pDbEnumeratorImpl->GetInt64At(columnIndex, value); +} + +result +DbEnumerator::GetDoubleAt(int columnIndex, double& value) const +{ + return __pDbEnumeratorImpl->GetDoubleAt(columnIndex, value); +} + +result +DbEnumerator::GetStringAt(int columnIndex, String& value) const +{ + return __pDbEnumeratorImpl->GetStringAt(columnIndex, value); +} + +result +DbEnumerator::GetBlobAt(int columnIndex, ByteBuffer& value) const +{ + return __pDbEnumeratorImpl->GetBlobAt(columnIndex, value); +} + +result +DbEnumerator::GetBlobAt(int columnIndex, void* buffer, int size) const +{ + + SysTryReturnResult(NID_IO, buffer != null, E_INVALID_ARG, "Null pointer was passed."); + SysTryReturnResult(NID_IO, size > 0, E_INVALID_ARG, "Invalid size was passed."); + + return __pDbEnumeratorImpl->GetBlobAt(columnIndex, buffer, size); +} + +result +DbEnumerator::GetDateTimeAt(int columnIndex, DateTime& value) const +{ + return __pDbEnumeratorImpl->GetDateTimeAt(columnIndex, value); +} + +int +DbEnumerator::GetColumnCount(void) const +{ + return __pDbEnumeratorImpl->GetColumnCount(); +} + +DbColumnType +DbEnumerator::GetColumnType(int columnIndex) const +{ + return __pDbEnumeratorImpl->GetColumnType(columnIndex); +} + +String +DbEnumerator::GetColumnName(int columnIndex) const +{ + return __pDbEnumeratorImpl->GetColumnName(columnIndex); +} + +int +DbEnumerator::GetColumnSize(int columnIndex) const +{ + return __pDbEnumeratorImpl->GetColumnSize(columnIndex); +} + +}} // Tizen::Io + diff --git a/src/io/FIoDbStatement.cpp b/src/io/FIoDbStatement.cpp new file mode 100644 index 0000000..1034dc3 --- /dev/null +++ b/src/io/FIoDbStatement.cpp @@ -0,0 +1,125 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDbStatement.cpp + * @brief This is the implementation file for DbStatement class. + */ + +#include + +#include +#include +#include + +#include +#include + +#define FIO_STMT_VAR_NUM_MAX 999 + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +DbStatement::DbStatement(void) + : __pDbStatementImpl(null) +{ + __pDbStatementImpl = new (std::nothrow) _DbStatementImpl; + + SysTryReturnVoidResult(NID_IO, __pDbStatementImpl != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); +} + +DbStatement::~DbStatement(void) +{ + delete __pDbStatementImpl; +} + +result +DbStatement::BindInt(int columnIndex, int value) +{ + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex <= FIO_STMT_VAR_NUM_MAX, E_INVALID_ARG, + "Wrong column index."); + + return __pDbStatementImpl->BindInt(columnIndex, value); +} + +result +DbStatement::BindInt64(int columnIndex, long long value) +{ + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex <= FIO_STMT_VAR_NUM_MAX, E_INVALID_ARG, + "Wrong column index."); + + return __pDbStatementImpl->BindInt64(columnIndex, value); +} + +result +DbStatement::BindDouble(int columnIndex, double value) +{ + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex <= FIO_STMT_VAR_NUM_MAX, E_INVALID_ARG, + "Wrong column index."); + + return __pDbStatementImpl->BindDouble(columnIndex, value); +} + +result +DbStatement::BindString(int columnIndex, const String& value) +{ + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex <= FIO_STMT_VAR_NUM_MAX, E_INVALID_ARG, + "Wrong column index."); + + return __pDbStatementImpl->BindString(columnIndex, value); +} + +result +DbStatement::BindBlob(int columnIndex, const ByteBuffer& value) +{ + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex <= FIO_STMT_VAR_NUM_MAX, E_INVALID_ARG, + "Wrong column index."); + + return __pDbStatementImpl->BindBlob(columnIndex, value); +} + +result +DbStatement::BindBlob(int columnIndex, const void* buffer, int size) +{ + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex <= FIO_STMT_VAR_NUM_MAX, E_INVALID_ARG, + "Wrong column index."); + + return __pDbStatementImpl->BindBlob(columnIndex, buffer, size); +} + +result +DbStatement::BindDateTime(int columnIndex, const DateTime& value) +{ + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex <= FIO_STMT_VAR_NUM_MAX, E_INVALID_ARG, + "Wrong column index."); + + return __pDbStatementImpl->BindDateTime(columnIndex, value); +} + +result +DbStatement::BindNull(int columnIndex) +{ + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex <= FIO_STMT_VAR_NUM_MAX, E_INVALID_ARG, + "Wrong column index."); + + return __pDbStatementImpl->BindNull(columnIndex); +} + +}} // Tizen::Io + diff --git a/src/io/FIoDirEntry.cpp b/src/io/FIoDirEntry.cpp new file mode 100644 index 0000000..be67810 --- /dev/null +++ b/src/io/FIoDirEntry.cpp @@ -0,0 +1,122 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDirEntry.cpp + * @brief This is the implementation file for DirEntry class. + */ + +#include + +#include +#include +#include +#include + +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +DirEntry::DirEntry(void) + : __pDirEntryImpl(null) +{ + __pDirEntryImpl = new (std::nothrow) _DirEntryImpl; + SysTryReturnVoidResult(NID_IO, __pDirEntryImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient"); +} + +DirEntry::~DirEntry(void) +{ + delete __pDirEntryImpl; +} + +DirEntry::DirEntry(const DirEntry& dirEntry) +{ + __pDirEntryImpl = new (std::nothrow) _DirEntryImpl(*dirEntry.__pDirEntryImpl); + SysTryReturnVoidResult(NID_IO, __pDirEntryImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient"); +} + +DirEntry& +DirEntry::operator =(const DirEntry& dirEntry) +{ + if (&dirEntry != this) + { + *__pDirEntryImpl = *(dirEntry.__pDirEntryImpl); + } + + return *this; +} + +bool +DirEntry::Equals(const Object& object) const +{ + const DirEntry* pOther = dynamic_cast< const DirEntry* >(&object); + if (pOther == null) + { + return false; + } + + return __pDirEntryImpl->Equals(*pOther->__pDirEntryImpl); +} + +int +DirEntry::GetHashCode(void) const +{ + return __pDirEntryImpl->GetHashCode(); +} + +const Tizen::Base::String +DirEntry::GetName(void) const +{ + return __pDirEntryImpl->GetName(); +} + +unsigned long +DirEntry::GetFileSize(void) const +{ + return __pDirEntryImpl->GetFileSize(); +} + +bool +DirEntry::IsDirectory(void) const +{ + return __pDirEntryImpl->IsDirectory(); +} + +bool +DirEntry::IsHidden(void) const +{ + return __pDirEntryImpl->IsHidden(); +} + +bool +DirEntry::IsReadOnly(void) const +{ + return __pDirEntryImpl->IsReadOnly(); +} + +Tizen::Base::DateTime +DirEntry::GetDateTime(void) const +{ + return __pDirEntryImpl->GetDateTime(); +} + +}} // Tizen::Io + diff --git a/src/io/FIoDirEnumerator.cpp b/src/io/FIoDirEnumerator.cpp new file mode 100644 index 0000000..4ae971f --- /dev/null +++ b/src/io/FIoDirEnumerator.cpp @@ -0,0 +1,73 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDirEnumerator.cpp + * @brief This is the implementation file for DirEnumerator class. + */ + +#include +#include +#include + +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +DirEnumerator::DirEnumerator(const String& dirPath) + : __pCurDirEntry(null) + , __pDirEnumeratorImpl(null) +{ + __pDirEnumeratorImpl = new (std::nothrow) _DirEnumeratorImpl(dirPath); + SysTryReturnVoidResult(NID_IO, __pDirEnumeratorImpl != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); +} + +DirEnumerator::~DirEnumerator(void) +{ + delete __pDirEnumeratorImpl; +} + +DirEntry +DirEnumerator::GetCurrentDirEntry(void) const +{ + return __pDirEnumeratorImpl->GetCurrentDirEntry(); +} + +Object* +DirEnumerator::GetCurrent(void) const +{ + return __pDirEnumeratorImpl->GetCurrent(); +} + +result +DirEnumerator::MoveNext(void) +{ + return __pDirEnumeratorImpl->MoveNext(); +} + +result +DirEnumerator::Reset(void) +{ + return __pDirEnumeratorImpl->Reset(); +} + +}} // Tizen::Io + diff --git a/src/io/FIoDirectory.cpp b/src/io/FIoDirectory.cpp new file mode 100644 index 0000000..b3aabb3 --- /dev/null +++ b/src/io/FIoDirectory.cpp @@ -0,0 +1,102 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDirectory.cpp + * @brief This is the implementation file for Directory class. + */ + +#include +#include + +#include +#include + +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +Directory::Directory(void) + : __pDirectoryImpl(null) +{ +} + +Directory::~Directory(void) +{ + delete __pDirectoryImpl; +} + +result +Directory::Construct(const String& dirPath) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, dirPath.GetLength() > 0 && dirPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + ("Given directory name length is not correct!")); + + SysAssertf(__pDirectoryImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + std::unique_ptr<_DirectoryImpl> pDirectoryImpl(new (std::nothrow) _DirectoryImpl); + SysTryReturnResult(NID_IO, pDirectoryImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pDirectoryImpl->Construct(dirPath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pDirectoryImpl = pDirectoryImpl.release(); + + return E_SUCCESS; +} + +DirEnumerator* +Directory::ReadN(void) +{ + SysAssertf(__pDirectoryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pDirectoryImpl->ReadN(); +} + +result +Directory::Create(const String& dirPath, bool createParentDirsToo) +{ + SysTryReturnResult(NID_IO, dirPath.GetLength() > 0 && dirPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + ("Given directory name length is not correct!")); + return _DirectoryImpl::Create(dirPath, createParentDirsToo); +} + +result +Directory::Remove(const String& dirPath, bool recursive) +{ + SysTryReturnResult(NID_IO, dirPath.GetLength() > 0 && dirPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + ("Given file name length is not correct!")); + return _DirectoryImpl::Remove(dirPath, recursive); +} + +result +Directory::Rename(const String& orgDirPath, const String& newDirPath) +{ + SysTryReturnResult(NID_IO, orgDirPath.GetLength() > 0 && orgDirPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + ("Given file name length is not correct!")); + SysTryReturnResult(NID_IO, newDirPath.GetLength() > 0 && newDirPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + ("Given file name length is not correct!")); + return _DirectoryImpl::Rename(orgDirPath, newDirPath); +} + +}} // Tizen::Io + diff --git a/src/io/FIoFile.cpp b/src/io/FIoFile.cpp new file mode 100644 index 0000000..6d4c8ce --- /dev/null +++ b/src/io/FIoFile.cpp @@ -0,0 +1,313 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoFile.cpp + * @brief This is the implementation file for File class. + */ + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include "FIo_FileImpl.h" + +using namespace std; +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +File::File(void) + : __pFileImpl(null) +{ +} + +File::~File(void) +{ + delete __pFileImpl; +} + +result +File::Construct(const String& filePath, const String& openMode, bool createParentDirsToo) +{ + SysAssertf(__pFileImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The specified filePath length is zero or exceeds system limitations."); + SysTryReturnResult(NID_IO, filePath.EndsWith(L"/") == false, E_INVALID_ARG, + "The specified filePath is not correct. It ends with '/'."); + + unique_ptr<_FileImpl> pFileImpl(new (std::nothrow) _FileImpl); + SysTryReturnResult(NID_IO, pFileImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pFileImpl->Construct(filePath, openMode, createParentDirsToo, null); + if (IsFailed(r)) + { + if (r == E_SYSTEM) + { + r = E_IO; + } + SysPropagate(NID_IO, r); + return r; + } + + __pFileImpl = pFileImpl.release(); + + return E_SUCCESS; +} + +result +File::Construct(const String& filePath, const String& openMode) +{ + SysAssertf(__pFileImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The specified filePath length is zero or exceeds system limitations."); + SysTryReturnResult(NID_IO, filePath.EndsWith(L"/") == false, E_INVALID_ARG, + "The specified filePath is not correct. It ends with '/'."); + + unique_ptr<_FileImpl> pFileImpl(new (std::nothrow) _FileImpl); + SysTryReturnResult(NID_IO, pFileImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pFileImpl->Construct(filePath, openMode, false, null); + if (IsFailed(r)) + { + if (r == E_SYSTEM && Tizen::App::_AppInfo::IsOspCompat() == true) + { + r = E_IO; + } + SysPropagate(NID_IO, r); + return r; + } + + __pFileImpl = pFileImpl.release(); + + return E_SUCCESS; +} + +result +File::Construct(const String& filePath, const char* pOpenMode) +{ + SysAssertf(__pFileImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The specified filePath length is zero or exceeds system limitations."); + SysTryReturnResult(NID_IO, filePath.EndsWith(L"/") == false, E_INVALID_ARG, + "The specified filePath is not correct. It ends with '/'."); + + unique_ptr<_FileImpl> pFileImpl(new (std::nothrow) _FileImpl); + SysTryReturnResult(NID_IO, pFileImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pFileImpl->Construct(filePath, pOpenMode, null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pFileImpl = pFileImpl.release(); + + return E_SUCCESS; +} + +result +File::Construct(const String& filePath, const char* pOpenMode, const ByteBuffer& key) +{ + SysAssertf(__pFileImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The specified filePath length is zero or exceeds system limitations."); + SysTryReturnResult(NID_IO, filePath.EndsWith(L"/") == false, E_INVALID_ARG, + "The specified filePath is not correct. It ends with '/'."); + + unique_ptr<_FileImpl> pFileImpl(new (std::nothrow) _FileImpl); + SysTryReturnResult(NID_IO, pFileImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pFileImpl->Construct(filePath, pOpenMode, &key); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pFileImpl = pFileImpl.release(); + + return E_SUCCESS; +} + +result +File::Read(ByteBuffer& buffer) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pFileImpl->Read(buffer); +} + +int +File::Read(void* buffer, int length) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, buffer, E_INVALID_ARG, "The specified buffer is null."); + SysTryReturnResult(NID_IO, length > 0, E_INVALID_ARG, "The specified length is zero or exceeds system limitations."); + + int readBytes = __pFileImpl->Read(buffer, length); + SysTryReturn(NID_IO, GetLastResult() != E_END_OF_FILE, 0, E_END_OF_FILE, + "[E_END_OF_FILE] The end of file is reached."); + + return readBytes; +} + +result +File::Read(String& buffer) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pFileImpl->Read(buffer); +} + +result +File::Write(const ByteBuffer& buffer) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, buffer.GetPointer() != null && buffer.GetLimit() > 0, E_INVALID_ARG, "The specified buffer is invalid."); + return __pFileImpl->Write(buffer); +} + +result +File::Write(const void* buffer, int length) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, length > 0, E_INVALID_ARG, + "The specified length is zero or exceeds system limitations."); + SysTryReturnResult(NID_IO, buffer, E_INVALID_ARG, + "The specified buffer is null."); + + return __pFileImpl->Write(buffer, length); +} + +result +File::Write(const String& buffer) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pFileImpl->Write(buffer); +} + +result +File::Flush(void) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pFileImpl->Flush(); +} + +int +File::Tell(void) const +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pFileImpl->Tell(); +} + +result +File::Seek(FileSeekPosition position, long offset) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pFileImpl->Seek(position, offset); +} + +result +File::Truncate(int length) +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pFileImpl->Truncate(length); +} + +String +File::GetName(void) const +{ + SysAssertf(__pFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pFileImpl->GetName(); +} + +result +File::Remove(const String& filePath) +{ + SysTryReturnResult(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The specified filePath length is zero or exceeds system limitations."); + + return _FileImpl::Remove(filePath); +} + +result +File::Move(const String& oldFilePath, const String& newFilePath) +{ + SysTryReturnResult(NID_IO, oldFilePath.GetLength() > 0 && oldFilePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The specified oldFilePath length is zero or exceeds system limitations."); + SysTryReturnResult(NID_IO, newFilePath.GetLength() > 0 && newFilePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "Given newFilePath length is zero or exceeds system limitations."); + + return _FileImpl::Move(oldFilePath, newFilePath); +} + +result +File::Copy(const String& srcFilePath, const String& destFilePath, bool failIfExist) +{ + SysTryReturnResult(NID_IO, srcFilePath.GetLength() > 0 && srcFilePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The specified rcFilePath length is zero or exceeds system limitations."); + SysTryReturnResult(NID_IO, destFilePath.GetLength() > 0 && destFilePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The specified destFilePath length is zero or exceeds system limitations."); + + return _FileImpl::Copy(srcFilePath, destFilePath, failIfExist); +} + +result +File::GetAttributes(const String& filePath, FileAttributes& attribute) +{ + SysTryReturnResult(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The length of the specified filePath is zero or exceeds system limitations."); + + return _FileImpl::GetAttributes(filePath, attribute); +} + +String +File::GetFileName(const String& filePath) +{ + String name; + SysTryReturn(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, name, E_INVALID_ARG, + "[E_INVALID_ARG] The length of the specified filePath is zero or exceeds system limitations."); + + return _FileImpl::GetFileName(filePath); +} + +String +File::GetFileExtension(const String& filePath) +{ + String extName; + SysTryReturn(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, extName, E_INVALID_ARG, + "[E_INVALID_ARG] The length of the specified filePath is zero or exceeds system limitations."); + + return _FileImpl::GetFileExtension(filePath); +} + +bool +File::IsFileExist(const String& filePath) +{ + SysTryReturn(NID_IO, filePath.GetLength() > 0 && filePath.GetLength() <= PATH_MAX, false, E_INVALID_ARG, + "[E_INVALID_ARG] Given filePath length is zero or exceeds system limitations."); + + return _FileImpl::IsFileExist(filePath); +} + +result +File::ConvertToSecureFile(const String& plainFilePath, const String& secureFilePath, const ByteBuffer& key) +{ + return _FileImpl::ConvertToSecureFile(plainFilePath, secureFilePath, key); +} + +}} // Tizen::Io + diff --git a/src/io/FIoFileAttributes.cpp b/src/io/FIoFileAttributes.cpp new file mode 100644 index 0000000..d648c9a --- /dev/null +++ b/src/io/FIoFileAttributes.cpp @@ -0,0 +1,125 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoFileAttributes.cpp + * @brief This is the implementation file for FIoFileAttributes class. + */ + +#include + +#include +#include + +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +FileAttributes::FileAttributes(void) + : __pFileAttributesImpl(null) +{ + __pFileAttributesImpl = new (std::nothrow) _FileAttributesImpl; + SysTryReturnVoidResult(NID_IO, __pFileAttributesImpl != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); +} + +FileAttributes::~FileAttributes(void) +{ + delete __pFileAttributesImpl; +} + +FileAttributes::FileAttributes(const FileAttributes& fileAttributes) + : __pFileAttributesImpl(null) +{ + __pFileAttributesImpl = new (std::nothrow) _FileAttributesImpl(*fileAttributes.__pFileAttributesImpl); + SysTryReturnVoidResult(NID_IO, __pFileAttributesImpl != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); +} + +FileAttributes& +FileAttributes::operator =(const FileAttributes& fileAttributes) +{ + if (&fileAttributes != this) + { + delete __pFileAttributesImpl; + + __pFileAttributesImpl = new (std::nothrow) _FileAttributesImpl(*fileAttributes.__pFileAttributesImpl); + SysLogException(NID_IO, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + } + + return *this; +} + +bool +FileAttributes::Equals(const Object& object) const +{ + const FileAttributes* pOther = dynamic_cast< const FileAttributes* >(&object); + if (pOther == null) + { + return false; + } + + return __pFileAttributesImpl->Equals(*(pOther->__pFileAttributesImpl)); +} + +int +FileAttributes::GetHashCode(void) const +{ + return __pFileAttributesImpl->GetHashCode(); +} + +long long +FileAttributes::GetFileSize(void) const +{ + return __pFileAttributesImpl->GetFileSize(); +} + +DateTime +FileAttributes::GetDateTime(void) const +{ + return __pFileAttributesImpl->GetDateTime(); +} + +DateTime +FileAttributes::GetLastModifiedTime(void) const +{ + return __pFileAttributesImpl->GetLastModifiedTime(); +} + +bool +FileAttributes::IsDirectory(void) const +{ + return __pFileAttributesImpl->IsDirectory(); +} + +bool +FileAttributes::IsHidden(void) const +{ + return __pFileAttributesImpl->IsHidden(); +} + +bool +FileAttributes::IsReadOnly(void) const +{ + return __pFileAttributesImpl->IsReadOnly(); +} + +}} // Tizen::Io + diff --git a/src/io/FIoFileEventManager.cpp b/src/io/FIoFileEventManager.cpp new file mode 100644 index 0000000..a66e950 --- /dev/null +++ b/src/io/FIoFileEventManager.cpp @@ -0,0 +1,104 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoFileiEventManager.cpp + * @brief This is the implementation file for FileEventManager class. + */ + +#include +#include + +#include +#include +#include + +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ +FileEventManager::FileEventManager(void) + : __pFileEventManagerImpl(null) +{ +} + +FileEventManager::~FileEventManager(void) +{ + delete __pFileEventManagerImpl; +} + +result +FileEventManager::Construct(IFileEventListener& listener) +{ + SysAssertf(__pFileEventManagerImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + result r = E_SUCCESS; + std::unique_ptr<_FileEventManagerImpl> pFileEventManagerImpl(new (std::nothrow) _FileEventManagerImpl); + SysTryReturnResult(NID_IO, pFileEventManagerImpl, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pFileEventManagerImpl->Construct(listener); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pFileEventManagerImpl = pFileEventManagerImpl.release(); + + return E_SUCCESS; +} + +result +FileEventManager::AddPath(const String& path, unsigned long eventsToMonitor) +{ + result r = E_SUCCESS; + SysAssertf(__pFileEventManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + r = __pFileEventManagerImpl->AddPath(path, eventsToMonitor); + + if (r == E_FILE_NOT_FOUND) + { + SysLogException(NID_IO, E_FILE_NOT_FOUND, "[E_FILE_NOT_FOUND] An entry for the specified path[%ls] could not be found.", path.GetPointer()); + } + else if (r == E_ILLEGAL_ACCESS) + { + SysLogException(NID_IO, E_ILLEGAL_ACCESS, "[E_ILLEGAL_ACCESS] The specified path is not permitted."); + } + else if (r == E_INVALID_ARG) + { + SysLogException(NID_IO, E_INVALID_ARG, "[E_INVALID_ARG] The specified eventsToMonitor contains no valid events."); + } + else if (r == E_IO) + { + SysLogException(NID_IO, E_IO, "[E_IO] I/O error is occurred."); + } + return r; +} + +result +FileEventManager::RemovePath(const String& path) +{ + result r = E_SUCCESS; + SysAssertf(__pFileEventManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + r = __pFileEventManagerImpl->RemovePath(path); + + if (r == E_IO) + { + SysLogException(NID_IO, E_IO, "[E_IO] I/O error is occurred."); + } + return r; +} + +}} // Tizen::Io + diff --git a/src/io/FIoLocalMessagePort.cpp b/src/io/FIoLocalMessagePort.cpp new file mode 100644 index 0000000..e14a5c8 --- /dev/null +++ b/src/io/FIoLocalMessagePort.cpp @@ -0,0 +1,68 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoLocalMessagePort.cpp + * @brief This is the implementation file for the LocalMessagePort class. + * + */ + +#include +#include +#include "FIo_LocalMessagePortImpl.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +LocalMessagePort::LocalMessagePort(void) + : __pLocalMessagePortImpl(null) +{ +} + +LocalMessagePort::~LocalMessagePort(void) +{ + delete __pLocalMessagePortImpl; +} + +result +LocalMessagePort::AddMessagePortListener(IMessagePortListener& listener) +{ + return __pLocalMessagePortImpl->AddMessagePortListener(listener); +} + +result +LocalMessagePort::RemoveMessagePortListener(IMessagePortListener& listener) +{ + return __pLocalMessagePortImpl->RemoveMessagePortListener(listener); +} + +String +LocalMessagePort::GetName(void) const +{ + return __pLocalMessagePortImpl->GetName(); +} + +bool +LocalMessagePort::IsTrusted(void) const +{ + return __pLocalMessagePortImpl->IsTrusted(); +} + +} } // Tizen::Io diff --git a/src/io/FIoMemoryMappedFile.cpp b/src/io/FIoMemoryMappedFile.cpp new file mode 100644 index 0000000..fb1c5b8 --- /dev/null +++ b/src/io/FIoMemoryMappedFile.cpp @@ -0,0 +1,109 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoMemoryMappedFile.cpp + * @brief This is the implementation file for MemoryMappedFile class. + */ + +#include +#include + +#include +#include +#include + +#include "FIo_MemoryMappedFileImpl.h" + +namespace Tizen { namespace Io +{ + +MemoryMappedFile::MemoryMappedFile(void) + : __pMemoryMappedFileImpl(null) +{ +} + +MemoryMappedFile::~MemoryMappedFile(void) +{ + delete __pMemoryMappedFileImpl; +} + +result +MemoryMappedFile::Construct(const File& file) +{ + result r = E_SUCCESS; + + SysAssertf(__pMemoryMappedFileImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + std::unique_ptr<_MemoryMappedFileImpl> pMemoryMappedFileImpl(new (std::nothrow) _MemoryMappedFileImpl); + SysTryReturnResult(NID_IO, pMemoryMappedFileImpl != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + r = pMemoryMappedFileImpl->Construct(file); + SysTryReturn(NID_IO, !(IsFailed(r)), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pMemoryMappedFileImpl = pMemoryMappedFileImpl.release(); + + return E_SUCCESS; +} + +void* +MemoryMappedFile::Map(void* address, long long length, unsigned long protection, unsigned long flag, long long offset) +{ + SysAssertf(__pMemoryMappedFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, length > 0, null, E_INVALID_ARG, + "[E_INVALID_ARG] The specified length parameter is not positive."); + SysTryReturn(NID_IO, flag != (MEMORY_MAPPED_FILE_FLAG_PRIVATE | MEMORY_MAPPED_FILE_FLAG_SHARED), null, E_INVALID_ARG, + "[E_INVALID_ARG] The specified flag parameter is invalid."); + + if ((address == null) && (flag & MEMORY_MAPPED_FILE_FLAG_FIXED) == MEMORY_MAPPED_FILE_FLAG_FIXED) + { + SysLogException(NID_IO, E_INVALID_ARG, "[E_INVALID_ARG] The specified address or flag parameter is invalid."); + return null; + } + else if ((address != null) && (flag & MEMORY_MAPPED_FILE_FLAG_FIXED) == 0x0) + { + SysLogException(NID_IO, E_INVALID_ARG, "[E_INVALID_ARG] The specified address or flag parameter is invalid."); + return null; + } + + return __pMemoryMappedFileImpl->Map(address, length, protection, flag, offset); +} + +result +MemoryMappedFile::Unmap(void* address, long long length) +{ + SysAssertf(__pMemoryMappedFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, length > 0, E_INVALID_ARG, + "The specified length parameter is not positive."); + return __pMemoryMappedFileImpl->Unmap(address, length); +} + +result +MemoryMappedFile::Sync(void* address, long long length, MemoryMappedFileSyncFlag syncFlag) +{ + SysAssertf(__pMemoryMappedFileImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, length > 0, E_INVALID_ARG, + "The specified length parameter is not positive."); + SysTryReturnResult(NID_IO, (syncFlag == MEMORY_MAPPED_FILE_SYNC_FLAG_SYNC || syncFlag == MEMORY_MAPPED_FILE_SYNC_FLAG_ASYNC), + E_INVALID_ARG, "The specified syncFlag parameter is invalid."); + + return __pMemoryMappedFileImpl->Sync(address, length, syncFlag); +} + +}} // Tizen::Io + diff --git a/src/io/FIoMessagePortManager.cpp b/src/io/FIoMessagePortManager.cpp new file mode 100644 index 0000000..7b45d88 --- /dev/null +++ b/src/io/FIoMessagePortManager.cpp @@ -0,0 +1,81 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoMessagePortManager.cpp + * @brief This is the implementation file for the MessagePortManager class. + * + */ + +#include +#include +#include +#include +#include "FIo_MessagePortManagerImpl.h" + + +using namespace Tizen::Base; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +MessagePortManager::MessagePortManager(void) +{ +} + +MessagePortManager::~MessagePortManager(void) +{ +} + +LocalMessagePort* +MessagePortManager::RequestLocalMessagePort(const String& localMessagePortName) +{ + _MessagePortManagerImpl* pImpl = _MessagePortManagerImpl::GetInstance(); + SysTryReturn(NID_IO, pImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + return pImpl->RequestLocalMessagePort(localMessagePortName); +} + +RemoteMessagePort* +MessagePortManager::RequestRemoteMessagePort(const AppId& remoteAppId, const String& remoteMessagePortName) +{ + _MessagePortManagerImpl* pImpl = _MessagePortManagerImpl::GetInstance(); + SysTryReturn(NID_IO, pImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + return pImpl->RequestRemoteMessagePort(remoteAppId, remoteMessagePortName); +} + +LocalMessagePort* +MessagePortManager::RequestTrustedLocalMessagePort(const String& localMessagePortName) +{ + _MessagePortManagerImpl* pImpl = _MessagePortManagerImpl::GetInstance(); + SysTryReturn(NID_IO, pImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + return pImpl->RequestTrustedLocalMessagePort(localMessagePortName); +} + +RemoteMessagePort* +MessagePortManager::RequestTrustedRemoteMessagePort(const AppId& remoteAppId, const String& remoteMessagePortName) +{ + _MessagePortManagerImpl* pImpl = _MessagePortManagerImpl::GetInstance(); + SysTryReturn(NID_IO, pImpl != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + return pImpl->RequestTrustedRemoteMessagePort(remoteAppId, remoteMessagePortName); +} + +} } // Tizen::Io diff --git a/src/io/FIoMmcStorageManager.cpp b/src/io/FIoMmcStorageManager.cpp new file mode 100644 index 0000000..ff34cf6 --- /dev/null +++ b/src/io/FIoMmcStorageManager.cpp @@ -0,0 +1,154 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoMmcStorageManager.cpp + * @brief This is the implementation file for MmcStorageManager class. + */ + +#include +#include +#include + +#include +#include + +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Security; + +namespace Tizen { namespace Io +{ + +MmcStorageManager* MmcStorageManager::__pMmcStorageManagerInstance = null; + +MmcStorageManager::MmcStorageManager(void) + : __pMmcStorageManagerImpl(null) +{ +} + +MmcStorageManager::~MmcStorageManager(void) +{ + delete __pMmcStorageManagerImpl; +} + +void +MmcStorageManager::InitSingleton(void) +{ + MmcStorageManager* pInst = new (std::nothrow) MmcStorageManager(); + SysTryReturnVoidResult(NID_IO, pInst != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pInst->__pMmcStorageManagerImpl = _MmcStorageManagerImpl::GetInstance(); + SysTryCatch(NID_IO, pInst->__pMmcStorageManagerImpl != null, , GetLastResult(), + "[%s] Propagated.", GetErrorMessage(GetLastResult())); + + __pMmcStorageManagerInstance = pInst; + + std::atexit(DestroySingleton); + return; + +CATCH: + delete pInst; +} + +void +MmcStorageManager::DestroySingleton(void) +{ + delete __pMmcStorageManagerInstance; +} + +MmcStorageManager* +MmcStorageManager::GetInstance(void) +{ + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + if (__pMmcStorageManagerInstance == null) + { + ClearLastResult(); + pthread_once(&onceBlock, InitSingleton); + result r = GetLastResult(); + if (IsFailed(r)) + { + onceBlock = PTHREAD_ONCE_INIT; + SysPropagate(NID_IO, r); + } + } + + return __pMmcStorageManagerInstance; +} + +result +MmcStorageManager::Mount(void) +{ + SysAssertf(__pMmcStorageManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pMmcStorageManagerImpl->Mount(); +} + +result +MmcStorageManager::Unmount(void) +{ + SysAssertf(__pMmcStorageManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pMmcStorageManagerImpl->Unmount(); +} + +result +MmcStorageManager::Format(void) +{ + SysAssertf(__pMmcStorageManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pMmcStorageManagerImpl->Format(); +} + +result +MmcStorageManager::AddMmcStorageMountListener(IMmcStorageMountListener& listener) +{ + SysAssertf(__pMmcStorageManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pMmcStorageManagerImpl->AddMmcStorageMountListener(listener); +} + +result +MmcStorageManager::RemoveMmcStorageMountListener(IMmcStorageMountListener& listener) +{ + SysAssertf(__pMmcStorageManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pMmcStorageManagerImpl->RemoveMmcStorageMountListener(listener); +} + +result +MmcStorageManager::AddMmcStorageFormatListener(IMmcStorageFormatListener& listener) +{ + SysAssertf(__pMmcStorageManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pMmcStorageManagerImpl->AddMmcStorageFormatListener(listener); +} + +result +MmcStorageManager::RemoveMmcStorageFormatListener(IMmcStorageFormatListener& listener) +{ + SysAssertf(__pMmcStorageManagerImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pMmcStorageManagerImpl->RemoveMmcStorageFormatListener(listener); +} + +}} // Tizen::Io + diff --git a/src/io/FIoRegistry.cpp b/src/io/FIoRegistry.cpp new file mode 100644 index 0000000..a928e2e --- /dev/null +++ b/src/io/FIoRegistry.cpp @@ -0,0 +1,550 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoRegistry.cpp + * @brief This is the implementation file for %Registry class. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "FIo_RegistryImpl.h" + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +Registry::Registry(void) + : __pRegistryImpl(null) +{ +} + +Registry::~Registry(void) +{ + delete __pRegistryImpl; + __pRegistryImpl = null; +} + +// This method will be removed in a future release. +result +Registry::Construct(const String& regPath, bool createIfNotExist) +{ + SysAssertf(__pRegistryImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + long openMode = REG_OPEN_READ_WRITE; + if (createIfNotExist) + { + openMode |= REG_OPEN_CREATE; + } + + return Construct(regPath, openMode, null); +} + +// This method will be removed in a future release. +result +Registry::Construct(const String& regPath, long openMode, long option) +{ + SysAssertf(__pRegistryImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, regPath.GetLength() > 0 && regPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The length of the specified regPath is zero or exceeds system limitations."); + + unique_ptr<_RegistryImpl> pRegistryImpl(new (std::nothrow) _RegistryImpl()); + SysTryReturnResult(NID_IO, pRegistryImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pRegistryImpl->Construct(regPath, openMode, null); + if (IsFailed(r)) + { + if (r == E_SYSTEM && Tizen::App::_AppInfo::IsOspCompat() == true) + { + r = E_IO; + } + SysPropagate(NID_IO, r); + return r; + } + __pRegistryImpl = pRegistryImpl.release(); + + return E_SUCCESS; +} + +result +Registry::Construct(const String& regPath, const char* pOpenMode) +{ + SysAssertf(__pRegistryImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, regPath.GetLength() > 0 && regPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The length of the specified regPath is zero or exceeds system limitations."); + + unique_ptr<_RegistryImpl> pRegistryImpl(new (std::nothrow) _RegistryImpl()); + SysTryReturnResult(NID_IO, pRegistryImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pRegistryImpl->Construct(regPath, pOpenMode, null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pRegistryImpl = pRegistryImpl.release(); + + return E_SUCCESS; +} + +result +Registry::Construct(const String& regPath, const char* pOpenMode, const ByteBuffer& key) +{ + SysAssertf(__pRegistryImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysTryReturnResult(NID_IO, regPath.GetLength() > 0 && regPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "The length of the specified regPath is zero or exceeds system limitations."); + + unique_ptr<_RegistryImpl> pRegistryImpl(new (std::nothrow) _RegistryImpl()); + SysTryReturnResult(NID_IO, pRegistryImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + result r = pRegistryImpl->Construct(regPath, pOpenMode, &key); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pRegistryImpl = pRegistryImpl.release(); + + return E_SUCCESS; +} + +result +Registry::Flush(void) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + result r = E_SUCCESS; + + r = __pRegistryImpl->Flush(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Flush failed.", GetErrorMessage(r)); + + return r; +} + +result +Registry::AddSection(const String& sectionName) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + + return __pRegistryImpl->AddSection(sectionName); +} + +result +Registry::RemoveSection(const String& sectionName) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + + return __pRegistryImpl->RemoveSection(sectionName); +} + +IList* +Registry::GetAllSectionNamesN(void) const +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + result r = E_SUCCESS; + IList* pList = null; + + r = __pRegistryImpl->GetSectionListN(&pList); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagating to caller...", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return pList; +} + +IList* +Registry::GetAllEntryNamesN(const String& sectionName) const +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryImpl->GetAllEntryNamesN(sectionName); +} + +result +Registry::AddValue(const String& sectionName, const String& entryName, int value) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->AddValue(sectionName, entryName, Integer::ToString(value)); +} + +result +Registry::AddValue(const String& sectionName, const String& entryName, double value) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->AddValue(sectionName, entryName, Double::ToString(value)); +} + +result +Registry::AddValue(const String& sectionName, const String& entryName, float value) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->AddValue(sectionName, entryName, Float::ToString(value)); +} + +result +Registry::AddValue(const String& sectionName, const String& entryName, const String& value) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->AddValue(sectionName, entryName, value); +} + +result +Registry::AddValue(const String& sectionName, const String& entryName, const UuId& value) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->AddValue(sectionName, entryName, value.ToString()); +} + +result +Registry::AddValue(const String& sectionName, const String& entryName, const ByteBuffer& value) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + int size = value.GetLimit(); + SysTryReturnResult(NID_IO, size > 0, E_INVALID_ARG, "invalid buffer length"); + + String strValEncoded; + String strVal; + result r = E_SUCCESS; + byte* pValue = const_cast< byte* >(value.GetPointer()); + SysAssert(pValue); + + for (int i = 0; i < size; i++) + { + r = strValEncoded.Format(3, L"%02x", (static_cast< unsigned char* >(pValue)[i])); + if (IsFailed(r)) + { + SysLog(NID_IO, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + r = strVal.Append(strValEncoded); + if (IsFailed(r)) + { + SysLog(NID_IO, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + } + + return __pRegistryImpl->AddValue(sectionName, entryName, strVal); +} + +result +Registry::GetValue(const String& sectionName, const String& entryName, int& retVal) const +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + result r = E_SUCCESS; + String valStr; + + r = __pRegistryImpl->GetValue(sectionName, entryName, valStr); + if (!IsFailed(r)) + { + r = Integer::Parse(valStr, retVal); + if (IsFailed(r)) + { + r = E_PARSING_FAILED; + } + } + + return r; +} + +result +Registry::GetValue(const String& sectionName, const String& entryName, double& retVal) const +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + result r = E_SUCCESS; + String valStr; + + r = __pRegistryImpl->GetValue(sectionName, entryName, valStr); + if (!IsFailed(r)) + { + r = Double::Parse(valStr, retVal); + if (IsFailed(r)) + { + r = E_PARSING_FAILED; + } + } + + return r; +} + +result +Registry::GetValue(const String& sectionName, const String& entryName, float& retVal) const +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + result r = E_SUCCESS; + String valStr; + + r = __pRegistryImpl->GetValue(sectionName, entryName, valStr); + if (!IsFailed(r)) + { + r = Float::Parse(valStr, retVal); + if (IsFailed(r)) + { + r = E_PARSING_FAILED; + } + } + + return r; +} + +result +Registry::GetValue(const String& sectionName, const String& entryName, String& retVal) const +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->GetValue(sectionName, entryName, retVal); +} + +result +Registry::GetValue(const String& sectionName, const String& entryName, UuId& retVal) const +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + result r = E_SUCCESS; + String valStr; + + r = __pRegistryImpl->GetValue(sectionName, entryName, valStr); + if (!IsFailed(r)) + { + r = UuId::Parse(valStr, retVal); + if (IsFailed(r)) + { + r = E_PARSING_FAILED; + } + } + + return r; +} + +result +Registry::GetValue(const String& sectionName, const String& entryName, ByteBuffer& retVal) const +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + int size = retVal.GetLimit(); + SysTryReturnResult(NID_IO, size > 0, E_INVALID_ARG, "Invalid buffer length"); + + result r = E_SUCCESS; + String valStr; + + r = __pRegistryImpl->GetValue(sectionName, entryName, valStr); + if (!IsFailed(r)) + { + int length = valStr.GetLength(); + int length2 = (size * 2); + int parseSize = (length2 <= length) ? length2 : length; + byte* pRetVal = const_cast< byte* >(retVal.GetPointer()); + SysAssert(pRetVal); + for (int i = 0, j = 0; i < parseSize; i++) + { + unsigned long ul = 0; + wchar_t ch = valStr[i]; + wchar_t tmp[3]; + + if ((ch >= L'0' && ch <= L'9') || (ch >= L'a' && ch <= L'f') || (ch >= L'A' && ch <= L'F')) + { + tmp[i % 2] = ch; + if (i % 2) + { + tmp[2] = L'\0'; + ul = wcstoul(tmp, null, 16); + (static_cast< unsigned char* >(pRetVal))[j++] = static_cast< unsigned char >(ul); + } + } + else + { + return E_PARSING_FAILED; + } + + } + + parseSize = parseSize/2; + SysAssertf(parseSize <= size, "The specified ByteBuffer is not enough to get the entry value from registry file."); + if (parseSize < size) + { + // resize buffer limit + r = retVal.SetLimit(parseSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + } + } + return r; +} + +result +Registry::SetValue(const String& sectionName, const String& entryName, int newValue) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->SetValue(sectionName, entryName, Integer::ToString(newValue)); +} + +result +Registry::SetValue(const String& sectionName, const String& entryName, double newValue) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->SetValue(sectionName, entryName, Double::ToString(newValue)); +} + +result +Registry::SetValue(const String& sectionName, const String& entryName, float newValue) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->SetValue(sectionName, entryName, Float::ToString(newValue)); +} + +result +Registry::SetValue(const String& sectionName, const String& entryName, const String& newValue) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName is empty"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName is empty"); + //SysTryReturnResult(NID_IO, newValue.GetLength() > 0, E_INVALID_ARG, "newValue is empty"); + + return __pRegistryImpl->SetValue(sectionName, entryName, newValue); +} + +result +Registry::SetValue(const String& sectionName, const String& entryName, const UuId& newValue) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->SetValue(sectionName, entryName, newValue.ToString()); +} + +result +Registry::SetValue(const String& sectionName, const String& entryName, const ByteBuffer& newValue) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + int size = newValue.GetLimit(); + SysTryReturnResult(NID_IO, size > 0, E_INVALID_ARG, "invalid buffer length"); + + String strValEncoded; + String strVal; + result r = E_SUCCESS; + byte* pNewValue = const_cast< byte* >(newValue.GetPointer()); + SysAssert(pNewValue); + + for (int i = 0; i < size; i++) + { + r = strValEncoded.Format(3, L"%02x", (static_cast< unsigned char* >(pNewValue)[i])); + if (IsFailed(r)) + { + SysLog(NID_IO, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + r = strVal.Append(strValEncoded); + if (IsFailed(r)) + { + SysLog(NID_IO, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + } + + return __pRegistryImpl->SetValue(sectionName, entryName, strVal); +} + +result +Registry::RemoveValue(const String& sectionName, const String& entryName) +{ + SysAssertf(__pRegistryImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, sectionName.GetLength() > 0, E_INVALID_ARG, "sectionName.GetLength() <= 0"); + SysTryReturnResult(NID_IO, entryName.GetLength() > 0, E_INVALID_ARG, "entryName.GetLength() <= 0"); + + return __pRegistryImpl->RemoveValue(sectionName, entryName); +} + +result +Registry::Remove(const String& regPath) +{ + SysTryReturnResult(NID_IO, regPath.GetLength() > 0 && regPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "regPath.GetLength <= 0 or long name was given."); + + return _RegistryImpl::Remove(regPath); +} + +result +Registry::ConvertToSecureRegistry(const String& plainRegPath, const String& secureRegPath, const ByteBuffer& key) +{ + SysTryReturnResult(NID_IO, plainRegPath.GetLength() > 0 && plainRegPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "plainRegPath.GetLength <= 0 or long name was given."); + SysTryReturnResult(NID_IO, secureRegPath.GetLength() > 0 && secureRegPath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "secureRegPath.GetLength <= 0 or long name was given."); + SysTryReturnResult(NID_IO, key.GetLimit() > 0, E_INVALID_ARG, "key.GetLimit <= 0."); + + return _RegistryImpl::ConvertToSecureRegistry(plainRegPath, secureRegPath, &key); +} + +}} // Tizen::Io + diff --git a/src/io/FIoRemoteMessagePort.cpp b/src/io/FIoRemoteMessagePort.cpp new file mode 100644 index 0000000..c687679 --- /dev/null +++ b/src/io/FIoRemoteMessagePort.cpp @@ -0,0 +1,80 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoRemoteMessagePort.cpp + * @brief This is the implementation file for the RemoteMessagePort class. + * + */ + +#include +#include +#include +#include "FIo_RemoteMessagePortImpl.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +RemoteMessagePort::RemoteMessagePort(void) + : __pRemoteMessagePortImpl(null) +{ +} + +RemoteMessagePort::~RemoteMessagePort(void) +{ + delete __pRemoteMessagePortImpl; +} + +String +RemoteMessagePort::GetName(void) const +{ + return __pRemoteMessagePortImpl->GetName(); +} + +String +RemoteMessagePort::GetAppId(void) const +{ + return __pRemoteMessagePortImpl->GetAppId(); +} + +bool +RemoteMessagePort::IsTrusted(void) const +{ + return __pRemoteMessagePortImpl->IsTrusted(); +} + +result +RemoteMessagePort::SendMessage(const IMap* pMessage) +{ + SysAssertf(__pRemoteMessagePortImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pRemoteMessagePortImpl->SendMessage(pMessage); +} + +result +RemoteMessagePort::SendMessage(const LocalMessagePort* pLocalMessagePort, const IMap* pMessage) +{ + SysAssertf(__pRemoteMessagePortImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pRemoteMessagePortImpl->SendMessage(pLocalMessagePort, pMessage); +} + +} } // Tizen::Io diff --git a/src/io/FIoSerialPort.cpp b/src/io/FIoSerialPort.cpp new file mode 100644 index 0000000..e818997 --- /dev/null +++ b/src/io/FIoSerialPort.cpp @@ -0,0 +1,74 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://floralicense.org/license/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoSerialPort.cpp + * @brief This is the implementation file for SerialPort class. + */ + +#include + +#include +#include +#include + +#include + +#include "FIo_SerialPortImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +SerialPort::SerialPort(void) + : __pSerialPortImpl(null) +{ +} + +SerialPort::~SerialPort(void) +{ +} + +result +SerialPort::Construct(ISerialPortEventListener& listener) +{ + SysAssertf(__pSerialPortImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + __pSerialPortImpl = new (std::nothrow) _SerialPortImpl(listener); + SysTryReturnResult(NID_IO, __pSerialPortImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + return E_SUCCESS; +} + +result +SerialPort::Write(const ByteBuffer& byteBuffer) +{ + SysAssertf(__pSerialPortImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pSerialPortImpl->Write(byteBuffer); +} + +int +SerialPort::GetWriteBufferSize(void) const +{ + SysAssertf(__pSerialPortImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pSerialPortImpl->GetWriteBufferSize(); +} + +} } // Tizen::Io diff --git a/src/io/FIoServerChannel.cpp b/src/io/FIoServerChannel.cpp new file mode 100644 index 0000000..96ffb82 --- /dev/null +++ b/src/io/FIoServerChannel.cpp @@ -0,0 +1,126 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoServerChannel.cpp + * @brief This is the implementation file for the ServerChannel class. + * + */ + +#include +#include + +#include +#include +#include +#include "FIo_ServerChannelImpl.h" + +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +ServerChannel* ServerChannel::__pServerChannelInstance = null; + +//////////////////////////////////////////////////////////////////////////////// +/// Lifecycle + +ServerChannel::ServerChannel(void) + : __pServerChannelImpl(null) +{ +} + +ServerChannel::~ServerChannel(void) +{ + delete __pServerChannelImpl; +} + +void +ServerChannel::SetChannelRequestEventListener(IChannelRequestEventListener* pRequestListener) +{ + SysAssertf(__pServerChannelImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + __pServerChannelImpl->SetChannelRequestEventListener(pRequestListener); +} + +result +ServerChannel::SendResponse(const String& clientChannelId, RequestId reqId, const IList* pArgs) +{ + SysAssertf(__pServerChannelImpl != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysTryReturnResult(NID_IO, !clientChannelId.IsEmpty(), E_OBJ_NOT_FOUND, "The client channel is not found."); + + return __pServerChannelImpl->SendResponse(clientChannelId, pArgs, reqId); +} + +ServerChannel* +ServerChannel::GetInstance(void) +{ + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + if (__pServerChannelInstance == null) + { + ClearLastResult(); + + pthread_once(&onceBlock, InitSingleton); + result r = GetLastResult(); + if (IsFailed(r)) + { + onceBlock = PTHREAD_ONCE_INIT; + SysPropagate(NID_IO, r); + } + } + + return __pServerChannelInstance; +} + +ServerChannel* +ServerChannel::GetInstance(const String& channelName) +{ + ServerChannel* pServerChannel = _ServerChannelImpl::GetServerChannel(channelName); + SysTryReturn(NID_IO, pServerChannel != null, null, E_SYSTEM, "[E_SYSTEM] Failed to create a server channel."); + + return pServerChannel; +} + +void +ServerChannel::InitSingleton(void) +{ + ServerChannel* pInst = new (std::nothrow) ServerChannel(); + SysTryReturnVoidResult(NID_IO, pInst != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pInst->__pServerChannelImpl = _ServerChannelImpl::GetInstance(pInst); + SysTryCatch(NID_IO, pInst->__pServerChannelImpl != null, ,E_SYSTEM, + "[E_SYSTEM] Failed to initialize the server channel."); + + __pServerChannelInstance = pInst; + std::atexit(DestroySingleton); + return; + +CATCH: + delete pInst; +} + +void +ServerChannel::DestroySingleton(void) +{ + delete __pServerChannelInstance; +} + +} } // Tizen::Io diff --git a/src/io/FIoSqlStatementBuilder.cpp b/src/io/FIoSqlStatementBuilder.cpp new file mode 100644 index 0000000..5a658e9 --- /dev/null +++ b/src/io/FIoSqlStatementBuilder.cpp @@ -0,0 +1,239 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoSqlStatementBuilder.cpp + * @brief This is the implementation for the %SqlStatementBuilder class. + */ +#include + +#include +#include +#include +#include + +#include + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +String +SqlStatementBuilder::CreateSelectStatement(const String& table, const IList* pColumnList, const String* pWhere, + const String* pOrder, const String* pLimit, const String* pGroup, const String* pHaving) +{ + String sql(L"SELECT "); + String empty; + + if (pColumnList != null) + { + int columnCount = pColumnList->GetCount(); + SysTryReturn(NID_IO, columnCount > 0, empty, E_INVALID_ARG, + "[E_INVALID_ARG] The specified pColumnList parameter is empty."); + + int i = 0; + while (i < columnCount) + { + const String* pColumn = dynamic_cast< const String* >(pColumnList->GetAt(i)); + SysTryReturn(NID_IO, pColumn != null, empty, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not a String class."); + + sql.Append(*pColumn); + + if (i < columnCount - 1) + { + sql.Append(L", "); + } + i++; + } + } + else + { + sql.Append(L'*'); + } + + sql.Append(L" FROM "); + sql.Append(table); + + if (pWhere != null) + { + sql.Append(L" WHERE "); + sql.Append(*pWhere); + } + + if (pOrder != null) + { + sql.Append(L" ORDER BY "); + sql.Append(*pOrder); + } + SysTryReturn(NID_IO, !(pOrder == null && pLimit != null), empty, E_INVALID_ARG, + "[E_INVALID_ARG] The specified pOrder parameter is null and pLimit parameter is not null."); + + if (pLimit != null) + { + sql.Append(L" LIMIT "); + sql.Append(*pLimit); + } + + if (pGroup != null) + { + sql.Append(L" GROUP BY "); + sql.Append(*pGroup); + } + SysTryReturn(NID_IO, !(pGroup == null && pHaving != null), empty, E_INVALID_ARG, + "[E_INVALID_ARG] The specified pGroup parameter is null and pHaving parameter is not null."); + + if (pHaving != null) + { + sql.Append(L" HAVING "); + sql.Append(*pHaving); + } + + SysLog(NID_IO, "SQL statement: %ls", sql.GetPointer()); + + SetLastResult(E_SUCCESS); + return sql; +} + +String +SqlStatementBuilder::CreateInsertStatement(const String& table, const IMap& insertMap) +{ + String sql(L"INSERT INTO "); + String sqlValue(L" VALUES ("); + String empty; + String* pColumn = null; + String* pValue = null; + int columnCount = 0; + int i = 0; + + columnCount = insertMap.GetCount(); + SysTryReturn(NID_IO, columnCount > 0, empty, E_INVALID_ARG, + "[E_INVALID_ARG] The specified insertMap parameter is empty."); + + sql.Append(table); + sql.Append(L" ("); + + std::unique_ptr pMapEnum(const_cast< IMap* >(&insertMap)->GetMapEnumeratorN()); + while (pMapEnum->MoveNext() == E_SUCCESS) + { + pColumn = dynamic_cast< String* >(pMapEnum->GetKey()); + SysTryReturn(NID_IO, pColumn != null, empty, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not a String class."); + + sql.Append(*pColumn); + + pValue = dynamic_cast< String* >(pMapEnum->GetValue()); + SysTryReturn(NID_IO, pValue != null, empty, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not a String class."); + + sqlValue.Append(*pValue); + + if (i < columnCount - 1) + { + sql.Append(L", "); + sqlValue.Append(L", "); + } + i++; + } + + sql.Append(L')'); + sqlValue.Append(L')'); + + sql.Append(sqlValue); + + SysLog(NID_IO, "SQL statement: %ls", sql.GetPointer()); + + SetLastResult(E_SUCCESS); + return sql; +} + +String +SqlStatementBuilder::CreateUpdateStatement(const String& table, const IMap& updateMap, const String* pWhere) +{ + String sql(L"UPDATE "); + String empty; + String* pColumn = null; + String* pValue = null; + int columnCount = 0; + int i = 0; + + columnCount = updateMap.GetCount(); + SysTryReturn(NID_IO, columnCount > 0, empty, E_INVALID_ARG, + "[E_INVALID_ARG] The specified insertMap parameter is empty."); + + sql.Append(table); + sql.Append(L" SET "); + + std::unique_ptr pMapEnum(const_cast< IMap* >(&updateMap)->GetMapEnumeratorN()); + while (pMapEnum->MoveNext() == E_SUCCESS) + { + pColumn = dynamic_cast< String* >(pMapEnum->GetKey()); + SysTryReturn(NID_IO, pColumn != null, empty, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not a String class."); + + sql.Append(*pColumn); + sql.Append(L" = "); + + pValue = dynamic_cast< String* >(pMapEnum->GetValue()); + SysTryReturn(NID_IO, pValue != null, empty, E_INVALID_ARG, + "[E_INVALID_ARG] The object is not a String class."); + + sql.Append(*pValue); + + if (i < columnCount - 1) + { + sql.Append(L", "); + } + i++; + } + + if (pWhere != null) + { + sql.Append(L" WHERE "); + sql.Append(*pWhere); + } + + SysLog(NID_IO, "SQL statement: %ls", sql.GetPointer()); + + SetLastResult(E_SUCCESS); + return sql; +} + +String +SqlStatementBuilder::CreateDeleteStatement(const String& table, const String* pWhere) +{ + String sql(L"DELETE FROM "); + result r = E_SUCCESS; + + sql.Append(table); + + if (pWhere != null) + { + sql.Append(L" WHERE "); + sql.Append(*pWhere); + } + + SysLog(NID_IO, "SQL statement: %ls", sql.GetPointer()); + + SetLastResult(r); + return sql; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_Channel.cpp b/src/io/FIo_Channel.cpp new file mode 100644 index 0000000..731125f --- /dev/null +++ b/src/io/FIo_Channel.cpp @@ -0,0 +1,178 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_Channel.cpp + * @brief This is the implementation file for the _Channel class. + * + */ + +#include + +#include +#include +#include +#include "FIo_Channel.h" +#include "FIo_IChannelService.h" +#include "FIo_IChannelResponseEventListener.h" +#include "FIo_IChannelRequestEventListener.h" +#include "FIo_ChannelServiceManager.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +_Channel::_Channel(void) + : __pIChannelService(null) + , __pResponseEventListener(null) + , __pRequestEventListener(null) +{ +} + +_Channel::~_Channel(void) +{ +} + +result +_Channel::Construct(const String& channelId, _IChannelService& channelService) +{ + SysAssertf(__pIChannelService == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + result r = E_SUCCESS; + __channelId = channelId; + __pIChannelService = &channelService; + + SysLog(NID_IO, "Channel created : [%ls]", channelId.GetPointer()); + + r = __pIChannelService->RegisterChannel(channelId, *this); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to register a channel with channelId(%ls)." + , GetErrorMessage(r), channelId.GetPointer()); + + return E_SUCCESS; +} + +result +_Channel::SendRequest(const String& channelId, const Tizen::Base::Collection::ArrayList& args, RequestId& reqId) +{ + SysAssertf(__pIChannelService != null, "Channel service has not been initialized.\n"); + + //SysLog(NID_IO, "Sent a request: [%ls] ----> [%ls]", __channelId.GetPointer(), channelId.GetPointer()); + + reqId = GetRequestId(); + + result r = __pIChannelService->SendRequest(__channelId, channelId, args, reqId); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to send a request.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_Channel::SendNullRequest(const String& channelId, RequestId& reqId) +{ + SysAssertf(__pIChannelService != null, "Channel service has not been initialized.\n"); + + //SysLog(NID_IO, "Sent a null request: [%ls] ----> [%ls]", __channelId.GetPointer(), channelId.GetPointer()); + + reqId = GetRequestId(); + + result r = __pIChannelService->SendNullRequest(__channelId, channelId, reqId); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to send a request.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_Channel::SendResponse(const String& channelId, const Tizen::Base::Collection::ArrayList& args, RequestId reqId) +{ + SysAssertf(__pIChannelService != null, "Channel service has not been initialized.\n"); + + //SysLog(NID_IO, "Sent a response: [%ls] ----> [%ls]", __channelId.GetPointer(), channelId.GetPointer()); + + result r = __pIChannelService->SendResponse(__channelId, channelId, args, reqId); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to send a response.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_Channel::SendNullResponse(const String& channelId, RequestId reqId) +{ + SysAssertf(__pIChannelService != null, "Channel service has not been initialized.\n"); + + //SysLog(NID_IO, "Sent a null response: [%ls] ----> [%ls]", __channelId.GetPointer(), channelId.GetPointer()); + + result r = __pIChannelService->SendNullResponse(__channelId, channelId, reqId); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to send a response.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +void +_Channel::SetChannelRequestEventListener(const _IChannelRequestEventListener& listener) +{ + __pRequestEventListener = const_cast <_IChannelRequestEventListener*>(&listener); +} + +void +_Channel::SetChannelResponseEventListener(const _IChannelResponseEventListener& listener) +{ + __pResponseEventListener = const_cast <_IChannelResponseEventListener*>(&listener); +} + + +bool +_Channel::OnChannelRequestReceivedN(const String& src, const String& dest, int requestId, Collection::ArrayList* pArgs) +{ + SysLog(NID_IO, "Request received: [%ls] ----> [%ls]", src.GetPointer(), dest.GetPointer()); + + if (__pRequestEventListener) + { + __pRequestEventListener->OnChannelRequestReceivedN(requestId, src, pArgs); + + return true; + } + + return false; +} + + +bool +_Channel::OnChannelResponseReceivedN(const String& src, const String& dest, int requestId, Collection::ArrayList* pArgs) +{ + SysLog(NID_IO, "Response received: [%ls] ----> [%ls]", src.GetPointer(), dest.GetPointer()); + + if (__pResponseEventListener) + { + __pResponseEventListener->OnChannelResponseReceivedN(requestId, src, pArgs); + + return true; + } + + return false; +} + +int +_Channel::GetRequestId(void) +{ + static int count = 0; + + return count++; +} + +} } // Tizen::Io diff --git a/src/io/FIo_ChannelCAppStub.cpp b/src/io/FIo_ChannelCAppStub.cpp new file mode 100644 index 0000000..6a29aac --- /dev/null +++ b/src/io/FIo_ChannelCAppStub.cpp @@ -0,0 +1,557 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelCAppStub.cpp + * @brief This is the implementation file for the _ChannelCAppStub class. + * + */ + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "FIo_ChannelCAppStub.h" + +#define MAX_BUFFER_LENGTH 4096 + +static const int TOKEN_LENGTH = 7; +static const int CAPP_PADDING_LENGTH = 7; + +using namespace std; + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Utility; +using namespace Tizen::Io; +using namespace Tizen::App; + +using namespace std; + +namespace Tizen { namespace Io +{ + +_ChannelCAppStub::_ChannelCAppStub(void) + :__pChannelService(null) + , __pGMainContext(null) + , __pConnectGSource(null) +{ +} + +_ChannelCAppStub::~_ChannelCAppStub(void) +{ + if (__pConnectGSource != null) + { + g_source_destroy(__pConnectGSource); + g_source_unref(__pConnectGSource); + __pConnectGSource = null; + } + __clients.clear(); +} + +_ChannelCAppStub::_ChannelInfo::_ChannelInfo(void) + : pClientInfo(null) + , pGIOChannel(null) + , pGSource(null) + , destroySource(true) +{ + +} +_ChannelCAppStub::_ChannelInfo::~_ChannelInfo(void) +{ + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (pGSource != null) + { + if (destroySource) + { + g_source_destroy(pGSource); + } + + g_source_unref(pGSource); + } +} + +_ChannelCAppStub::_ClientInfo::_ClientInfo(void) + : clientId(-1) + , pChannelStub(null) +{ + +} + +_ChannelCAppStub::_ClientInfo::~_ClientInfo(void) +{ + channels.clear(); +} + +result +_ChannelCAppStub::Construct(void) +{ + GSource* pGSource = null; + GIOChannel* pGIOChannel = null; + const char* pSocketName = "/tmp/osp.io.socketserver.channelmanager\0"; + size_t socketNameLength = 0; + struct sockaddr_un serverAddress; + int serverSocket = -1; + socklen_t serverLen = 0; + int ret = 0; + result r = E_SUCCESS; + + socketNameLength = strlen(pSocketName) + 1; + SysTryReturnResult(NID_IO, socketNameLength < 108, E_SYSTEM, + "Server name is too long."); + + __pGMainContext = g_main_context_get_thread_default(); //get own gmain context except default thread + if (__pGMainContext == null) + { + __pGMainContext = g_main_context_default(); //get gmain context from me (default) + SysTryReturnResult(NID_IO, __pGMainContext != null, E_SYSTEM, + "Failed to get glib context."); + } + + ret = unlink(pSocketName); + SysTryLog(NID_IO, ret == 0, "Unlinking a socket %s has failed.. but it is not a problem.", pSocketName); + + serverSocket = socket(AF_UNIX, SOCK_STREAM, 0); + SysTryReturnResult(NID_IO, serverSocket != -1, E_SYSTEM, + "Failed to create a socket."); + + bzero(&serverAddress, sizeof(serverAddress)); + serverAddress.sun_family = AF_UNIX; + strncpy(serverAddress.sun_path, pSocketName, socketNameLength); + serverLen = sizeof(serverAddress); + + ret = bind(serverSocket, (const struct sockaddr*) &serverAddress, serverLen); + SysTryCatch(NID_IO, ret != -1, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to bind a socket(%d, %s): %s", serverSocket, pSocketName, strerror(errno)); + + ret = chmod(pSocketName, 0666); + SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to change permission of a socket(%d, %s): %s", serverSocket, + pSocketName, strerror(errno)); + + listen(serverSocket, 5); + + pGIOChannel = g_io_channel_unix_new(serverSocket); + SysTryCatch(NID_IO, pGIOChannel != null, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to create GIOChannel for socket."); + + // socket will be closed when pGIOChannel is deleted. + g_io_channel_set_close_on_unref(pGIOChannel, TRUE); + serverSocket = -1; + + pGSource = g_io_create_watch(pGIOChannel, (GIOCondition)(G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP)); + SysTryCatch(NID_IO, pGSource != null, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to create GSource for socket."); + + // channel will be delete when pGSource is deleted. + g_io_channel_unref(pGIOChannel); + pGIOChannel = null; + + g_source_set_callback(pGSource, (GSourceFunc) OnConnectionRequest, this, NULL); + g_source_attach(pGSource, __pGMainContext); + + __pConnectGSource = pGSource; + + return E_SUCCESS; + +CATCH: + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (serverSocket != -1) + { + close(serverSocket); + } + + if (__pGMainContext) + { + g_main_context_unref(__pGMainContext); + __pGMainContext = null; + } + + return r; +} + +void +_ChannelCAppStub::SetChannelService(_ChannelService& service) +{ + __pChannelService = &service; +} + +struct HelloMessage +{ + int pid; + char appId[256]; +}; + +gboolean +_ChannelCAppStub::OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data) +{ + int serverFd = -1; + int clientFd = -1; + struct sockaddr_un clientAddress; + socklen_t clientLen = sizeof(clientAddress); + GSource* pGSource = null; + GIOChannel* pGIOChannel = null; + GError* pGError = null; + _ClientInfo* pClientInfo = null; + _ChannelInfo* pChannelInfo = null; + HelloMessage helloMessage; + int readSize = 0; + + _ChannelCAppStub* pChannelStub = static_cast< _ChannelCAppStub* >(data); + SysTryReturn(NID_IO, pChannelStub != null, FALSE, E_SYSTEM, + "[E_SYSTEM] pChannelStub is null."); + + serverFd = g_io_channel_unix_get_fd(source); + clientFd = accept(serverFd, (struct sockaddr*) &clientAddress, &clientLen); + SysTryReturn(NID_IO, clientFd != -1, E_SYSTEM, FALSE, "[E_SYSTEM] Failed to accept."); + + + readSize = read(clientFd, &helloMessage, sizeof(helloMessage)); + helloMessage.appId[255] = '\0'; + + SysLog(NID_IO, " >> Channel Service: accepted client fd: %d, client pid: %d, appid: %s", + clientFd, helloMessage.pid, helloMessage.appId); + + pGIOChannel = g_io_channel_unix_new(clientFd); + SysTryCatch(NID_IO, pGIOChannel != null, , E_SYSTEM, + "[E_SYSTEM] Failed to create GIOChannel."); + + g_io_channel_set_encoding(pGIOChannel, NULL, &pGError); + g_io_channel_set_flags(pGIOChannel, G_IO_FLAG_NONBLOCK, &pGError); + + g_io_channel_set_close_on_unref(pGIOChannel, TRUE); + clientFd = -1; + + pClientInfo = pChannelStub->__clients[helloMessage.pid]; + if (pClientInfo == null) // first connection request from this client + { + SysLog(NID_IO, "First connection!! [%s]", helloMessage.appId); + + pClientInfo = new (std::nothrow) _ClientInfo; + SysTryCatch(NID_IO, pClientInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pClientInfo->pChannelStub = pChannelStub; + pClientInfo->clientId = helloMessage.pid; + pClientInfo->appId = helloMessage.appId; + + pChannelStub->__clients[helloMessage.pid] = pClientInfo; + } + + pChannelInfo = new (std::nothrow) _ChannelInfo; + SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pGSource = g_io_create_watch(pGIOChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP)); + g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL); + g_source_attach(pGSource, pChannelStub->__pGMainContext); + + pChannelInfo->pClientInfo = pClientInfo; + pChannelInfo->pGIOChannel = pGIOChannel; + pChannelInfo->pGSource = pGSource; + + pClientInfo->channels.push_back(pChannelInfo); + + // Stores client info to _ChannelService + pChannelStub->__pChannelService->RegisterChannel(pClientInfo->appId, helloMessage.pid, pGIOChannel); + + return TRUE; + +CATCH: + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (clientFd != -1) + { + close(clientFd); + } + + return FALSE; +} + +gboolean +_ChannelCAppStub::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data) +{ + gboolean ret = FALSE; + + _ChannelInfo* pChannelInfo = (_ChannelInfo*) data; + _ClientInfo* pClientInfo = pChannelInfo->pClientInfo; + _ChannelCAppStub* pChannelStub = (_ChannelCAppStub*) pClientInfo->pChannelStub; + + ret = pChannelStub->HandleReceivedMessage(source, condition, data); + + return ret; +} + +gboolean +_ChannelCAppStub::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data) +{ + GIOStatus status; + GError* pGError = null; + gsize readBytes = 0; + result r = E_SUCCESS; + + SysLog(NID_IO, "fd: %d, condition :0x%x", g_io_channel_unix_get_fd(source), condition); + + _ChannelInfo* pChannelInfo = (_ChannelInfo*) data; + _ClientInfo* pClientInfo = pChannelInfo->pClientInfo; + _ChannelCAppStub* pChannelStub = pClientInfo->pChannelStub; + + if (condition & G_IO_HUP) + { + SysLog(NID_IO, " G_IO_HUP, the connection is closed"); + int clientId = pClientInfo->clientId; + + g_io_channel_shutdown(source, FALSE, &pGError); + + for (unsigned int i = 0; i < pClientInfo->channels.size(); i++) + { + if (pChannelInfo == pClientInfo->channels[i]) + { + pClientInfo->channels.erase(pClientInfo->channels.begin() + i); + + pChannelInfo->destroySource = false; + delete pChannelInfo; + + break; + } + + } + + if (pClientInfo->channels.size() == 0) + { + SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId); + + pChannelStub->__pChannelService->UnregisterChannel(clientId); + + __clients[clientId] = null; + + delete pClientInfo; + } + + return FALSE; + } + else if (condition & G_IO_IN) + { + unique_ptr pBuffer(new char[MAX_BUFFER_LENGTH]); + pGError = null; + status = g_io_channel_read_chars(source, pBuffer.get(), MAX_BUFFER_LENGTH, &readBytes, &pGError); + if (status != G_IO_STATUS_NORMAL) + { + if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR) + { + if (status == G_IO_STATUS_EOF) + { + SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed."); + } + else + { + SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. "); + } + + pGError = null; + g_io_channel_shutdown(source, FALSE, &pGError); + + int clientId = pClientInfo->clientId; + + for (unsigned int i = 0; i < pClientInfo->channels.size(); i++) + { + if (pChannelInfo == pClientInfo->channels[i]) + { + pClientInfo->channels.erase(pClientInfo->channels.begin() + i); + + //pChannelInfo->destroySource = false; + pChannelInfo->destroySource = true; + delete pChannelInfo; + break; + } + } + + if (pClientInfo->channels.size() == 0) + { + SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId); + + pChannelStub->__pChannelService->UnregisterChannel(clientId); + + __clients[clientId] = null; + + delete pClientInfo; + } + + return FALSE; + } + } + + SysLog(NID_IO, "CAppChannel >> Channel Server: readBytes: %d, readBuf: %s", readBytes, pBuffer.get()); + + SysTryReturn(NID_IO, readBytes != 0, FALSE, E_SYSTEM, "[E_SYSTEM] Received data is empty."); + + String srcAppId = pClientInfo->appId; + + // Parse the header + string buffer(pBuffer.get()); + string tokenStr("::"); + RequestId reqId = 0; + size_t pos = 0; + size_t lastPos = 0; + + lastPos = buffer.find(tokenStr); + + // AppId + String appId((buffer.substr(pos, lastPos-pos)).c_str()); + + SysLog(NID_IO, "CAppChannel >> src = %ls / dest = %ls", srcAppId.GetPointer(), appId.GetPointer()); + + pos = lastPos + tokenStr.length(); + lastPos = buffer.find(tokenStr, pos); + + // Request ID + string requestId(buffer.substr(pos, lastPos-pos)); + reqId = atol(requestId.c_str()); + + SysLog(NID_IO, "CAppChannel >> requestId = %d", reqId); + + pos = lastPos + tokenStr.length(); + + // Parse the data + ArrayList list; + list.Construct(); + + size_t bufferSize = buffer.length(); + int tokenCount = 0; + string token; + while (pos < bufferSize) + { + // Get length of each token + token = buffer.substr(pos, TOKEN_LENGTH); + pos += TOKEN_LENGTH; + + if (token == "0000000") + { + SysLog(NID_IO, "CAppChannel >> length = 0, token = empty string"); + list.Add(*(new String())); + } + else + { + tokenCount = atoi(token.c_str()); + token = buffer.substr(pos, tokenCount); + pos += tokenCount; + + SysLog(NID_IO, "CAppChannel >> length = %d, token = %s", tokenCount, token.c_str()); + list.Add(*(new String(token.c_str()))); + } + } + + r = pChannelStub->__pChannelService->SendRequest(srcAppId, appId, list, reqId); + SysTryReturn(NID_IO, !IsFailed(r), FALSE, E_SYSTEM, "[E_SYSTEM] Failed to send request."); + + list.RemoveAll(true); + } + else + { + SysLog(NID_IO, " >> Channel Service: else !!!"); + } + + return TRUE; +} + +bool +_ChannelCAppStub::SendResponse(int requestId, void* pGIOChannel, const ArrayList& args) +{ + gsize writtenBytes = 0; + GError* pGError = null; + + // Parse the data + String str; + String item; + String lengthString; + int count = args.GetCount(); + int itemLength = 0; + int paddingLength = 0; + result r = E_SUCCESS; + SysLog(NID_IO, "item count: %d", count); + + for (int i = 0; i < count; ++i) + { + item = *((String*)args.GetAt(i)); + itemLength = item.GetLength(); + lengthString = Integer::ToString(itemLength); + r = item.Insert(lengthString, 0); + SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to compose the response message."); + + // padding 7 digit + paddingLength = CAPP_PADDING_LENGTH - lengthString.GetLength(); + for (int j = 0; j < paddingLength; j++) + { + r = item.Insert(L'0', 0); + SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to compose the response message."); + } + + str.Append(item); + } + + SysLog(NID_IO, "data: %ls, length: %d", str.GetPointer(), str.GetLength()); + + // Add a RequestId + str.Append(L"|||"); + str.Append(requestId); + str.Append(L"|"); + + // Send a data + unique_ptr pStr(_StringConverter::CopyToCharArrayN(str)); + + itemLength = strlen(pStr.get()); + + g_io_channel_write_chars((GIOChannel*)pGIOChannel, (char*)pStr.get(), itemLength, &writtenBytes, &pGError); + g_io_channel_flush((GIOChannel*)pGIOChannel, &pGError); + + return true; +} + +}} + diff --git a/src/io/FIo_ChannelManager.cpp b/src/io/FIo_ChannelManager.cpp new file mode 100644 index 0000000..bad0ff4 --- /dev/null +++ b/src/io/FIo_ChannelManager.cpp @@ -0,0 +1,185 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelManager.cpp + * @brief This is the implementation file for the _ChannelManager class. + * + */ + +#include +#include +#include + +#include +#include +#include +#include "FIo_Channel.h" +#include "FIo_ChannelManager.h" +#include "FIo_ChannelServiceManager.h" +#include "FIo_IChannelService.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +_ChannelManager* _ChannelManager::__pChannelManagerInst = null; + +_ChannelManager::_ChannelManager(void) + : __pIChannelService(null) +{ + +} + +_ChannelManager::~_ChannelManager(void) +{ + +} + +result +_ChannelManager::Construct(void) +{ + static _StringHashProvider hashProvider; + static _StringComparer stringComparer; + __channels.Construct(0, 0, hashProvider, stringComparer); + __clientChannels.Construct(0, 0, hashProvider, stringComparer); + __serverChannels.Construct(0, 0, hashProvider, stringComparer); + + _ChannelServiceManager* pManager = _ChannelServiceManager::GetInstance(); + SysTryReturnResult(NID_IO, pManager != null, E_SYSTEM, "Failed to create a channel manager."); + + __pIChannelService = pManager->GetChannelService(); + SysTryReturnResult(NID_IO, __pIChannelService != null, E_SYSTEM, "Failed to get channel service."); + + return E_SUCCESS; +} + +void +_ChannelManager::InitSingleton(void) +{ + _ChannelManager* pInst = new (std::nothrow) _ChannelManager(); + SysTryReturnVoidResult(NID_IO, pInst != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + result r = pInst->Construct(); + SysTryCatch(NID_IO, !IsFailed(r), ,E_SYSTEM, + "[E_SYSTEM] Failed to initialize the channel manager."); + + __pChannelManagerInst = pInst; + std::atexit(DestroySingleton); + return; + +CATCH: + delete pInst; +} + +void +_ChannelManager::DestroySingleton(void) +{ + delete __pChannelManagerInst; +} + +_ChannelManager* +_ChannelManager::GetInstance(void) +{ + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + if (__pChannelManagerInst == null) + { + ClearLastResult(); + + pthread_once(&onceBlock, InitSingleton); + result r = GetLastResult(); + if (IsFailed(r)) + { + onceBlock = PTHREAD_ONCE_INIT; + SysPropagate(NID_IO, r); + } + } + + return __pChannelManagerInst; +} + +_Channel* +_ChannelManager::GetChannel(const String& channelId) +{ + result r = E_SUCCESS; + _Channel* pChannel = null; + + __channels.GetValue(channelId, pChannel); + if (pChannel) + { + return pChannel; + } + + pChannel = new (std::nothrow) _Channel; + SysTryReturn(NID_IO, pChannel != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + r = pChannel->Construct(channelId, *__pIChannelService); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to create _Channel instance", GetErrorMessage(r)); + + __channels.Add(channelId, pChannel); + + return pChannel; + +CATCH: + delete pChannel; + + return null; +} + +ClientChannel* +_ChannelManager::GetClientChannel(const Tizen::Base::String& channelName) +{ + ClientChannel* pChannel = null; + + __clientChannels.GetValue(channelName, pChannel); + if (pChannel) + { + return pChannel; + } + + return null; +} + +ServerChannel* +_ChannelManager::GetServerChannel(const Tizen::Base::String& channelName) +{ + ServerChannel* pChannel = null; + + __serverChannels.GetValue(channelName, pChannel); + if (pChannel) + { + return pChannel; + } + + return null; +} + +void +_ChannelManager::AddClientChannel(const Tizen::Base::String& channelName, ClientChannel* pChannel) +{ + __clientChannels.Add(channelName, pChannel); +} + +void +_ChannelManager::AddServerChannel(const Tizen::Base::String& channelName, ServerChannel* pChannel) +{ + __serverChannels.Add(channelName, pChannel); +} + +}} diff --git a/src/io/FIo_ChannelMessages.cpp b/src/io/FIo_ChannelMessages.cpp new file mode 100644 index 0000000..58a3cc5 --- /dev/null +++ b/src/io/FIo_ChannelMessages.cpp @@ -0,0 +1,26 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelMessages.cpp + * @brief This is the implementation file for the ChannelMessages class. + * + */ + + +#define IPC_MESSAGE_IMPL +#include "FIo_ChannelMessages.h" diff --git a/src/io/FIo_ChannelService.cpp b/src/io/FIo_ChannelService.cpp new file mode 100644 index 0000000..dd79574 --- /dev/null +++ b/src/io/FIo_ChannelService.cpp @@ -0,0 +1,323 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelService.cpp + * @brief This is the implementation file for the _ChannelService class. + * + */ + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include "FIo_ChannelService.h" +#include "FIo_ChannelMessages.h" +#include "FIo_IChannelServiceStub.h" +#include "FIo_ChannelCAppStub.h" +#include "FIo_ChannelWebAppStub.h" + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Io; + + +namespace Tizen { namespace Io +{ + +_ChannelService::_ChannelService(void) + : __pIChannelServiceStub(null) +{ + +} + +_ChannelService::~_ChannelService(void) +{ + +} + +result +_ChannelService::Construct(_IChannelServiceStub& stub) +{ + static _StringHashProvider hashProvider; + static _StringComparer stringComparer; + result r = E_SUCCESS; + + __channels.Construct(0, 0, hashProvider, stringComparer); + + __pIChannelServiceStub = &stub; + + __pIChannelServiceStub->SetChannelService(*this); + + // Create a CAppStub + unique_ptr<_ChannelCAppStub> pCStub(new (std::nothrow) _ChannelCAppStub()); + SysTryReturnResult(NID_IO, pCStub != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pCStub->Construct(); + SysTryReturnResult(NID_IO, r == E_SUCCESS, E_SYSTEM, "Failed to create a CAppStub."); + + pCStub->SetChannelService(*this); + + // Create a WebAppStub + unique_ptr<_ChannelWebAppStub> pWebStub(new (std::nothrow) _ChannelWebAppStub()); + SysTryReturnResult(NID_IO, pWebStub != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pWebStub->Construct(); + SysTryReturnResult(NID_IO, r == E_SUCCESS, E_SYSTEM, "Failed to create a WebAppStub."); + + pWebStub->SetChannelService(*this); + + pCStub.release(); + pWebStub.release(); + + return E_SUCCESS; +} + +result +_ChannelService::RegisterChannel(const String& channelId, const _IChannelServiceEventListener& listener) +{ + return E_SUCCESS; +} + +result +_ChannelService::RegisterChannel(const String& channelId, int clientId, unsigned int type) +{ + result r = E_SUCCESS; + _ChannelInfo* pChannelInfo = null; + + SysLog(NID_IO, "Register a channel : %ls.", channelId.GetPointer()); + + r = __channels.GetValue(channelId, pChannelInfo); + SysTryReturnResult(NID_IO, pChannelInfo == null, E_SYSTEM, "Channel has already been registered."); + + pChannelInfo = new (std::nothrow) _ChannelInfo; + SysTryReturnResult(NID_IO, pChannelInfo != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pChannelInfo->channelId = channelId; + pChannelInfo->clientId = clientId; + pChannelInfo->type = type; + pChannelInfo->pGIOChannel = null; + + __channels.Add(channelId, pChannelInfo); + + return E_SUCCESS; +} + +result +_ChannelService::RegisterChannel(const String& channelId, int clientId, void* pGIOChannel) +{ + result r = E_SUCCESS; + _ChannelInfo* pChannelInfo = null; + + SysLog(NID_IO, "Register a channel : [%ls]", channelId.GetPointer()); + + r = __channels.GetValue(channelId, pChannelInfo); + SysTryReturnResult(NID_IO, pChannelInfo == null, E_SYSTEM, "Channel has already been registered."); + + pChannelInfo = new (std::nothrow) _ChannelInfo; + SysTryReturnResult(NID_IO, pChannelInfo != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pChannelInfo->channelId = channelId; + pChannelInfo->clientId = clientId; + pChannelInfo->type = CAPP_CHANNEL; + pChannelInfo->pGIOChannel = pGIOChannel; + + __channels.Add(channelId, pChannelInfo); + + return E_SUCCESS; +} + +result +_ChannelService::UnregisterChannel(const String& channelId) +{ + return E_SUCCESS; +} + +result +_ChannelService::UnregisterChannel(int clientId) +{ + SysLog(NID_IO, "Unregister - clientId = %d", clientId); + + result r = E_OBJ_NOT_FOUND; + + String key; + _ChannelInfo* pValue = null; + IListT* pKeys = __channels.GetKeysN(); + SysTryReturnResult(NID_IO, pKeys != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + int count = __channels.GetCount(); + + for (int i = 0; i < count; i++) + { + pKeys->GetAt(i, key); + __channels.GetValue(key, pValue); + if (pValue != null && pValue->clientId == clientId) + { + SysLog(NID_IO, "Unregister - ChannelId = %ls", key.GetPointer()); + __channels.Remove(key); + delete pValue; + + r = E_SUCCESS; + } + } + + delete pKeys; + + return r; +} + +result +_ChannelService::SendRequest(const String& src, + const String& dest, + const ArrayList& args, + int requestId) +{ + SysLog(NID_IO, "[%ls] ---> [%ls], Request ID = %d", src.GetPointer(), dest.GetPointer(), requestId); + + _ChannelInfo* pChannelInfo = null; + + __channels.GetValue(dest, pChannelInfo); + SysTryReturnResult(NID_IO, pChannelInfo != null, E_OBJ_NOT_FOUND, + "Destination channel is not found."); + + // Channel for WebApp + if (pChannelInfo->type == WEBAPP_CHANNEL) + { + bool ret = _ChannelWebAppStub::SendResponse(pChannelInfo->clientId, args); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to send the data to a WebApp."); + } + // Channel for OspApp + else + { + result r = __pIChannelServiceStub->SendRequest(pChannelInfo->clientId, src, dest, args, requestId); + SysTryReturnResult(NID_IO, r == E_SUCCESS, E_SYSTEM, "Failed to send the request data."); + } + + return E_SUCCESS; +} + +result +_ChannelService::SendNullRequest(const String& src, + const String& dest, + int requestId) +{ + SysLog(NID_IO, "[%ls] ---> [%ls], Request ID = %d", src.GetPointer(), dest.GetPointer(), requestId); + + _ChannelInfo* pChannelInfo = null; + + __channels.GetValue(dest, pChannelInfo); + SysTryReturnResult(NID_IO, pChannelInfo != null, E_OBJ_NOT_FOUND, + "Destination channel is not found."); + + // Channel for WebApp + if (pChannelInfo->type == WEBAPP_CHANNEL) + { + SysLog(NID_IO, "WebApp Channel, the data are not JSON types"); + return E_SYSTEM; + } + // Channel for OspApp + else + { + __pIChannelServiceStub->SendNullRequest(pChannelInfo->clientId, src, dest, requestId); + } + + return E_SUCCESS; +} + +result +_ChannelService::SendResponse(const String& src, + const String& dest, + const ArrayList& args, + int requestId) +{ + SysLog(NID_IO, "[%ls] ---> [%ls], Request ID = %d", src.GetPointer(), dest.GetPointer(), requestId); + + _ChannelInfo* pChannelInfo = null; + + __channels.GetValue(dest, pChannelInfo); + SysTryReturnResult(NID_IO, pChannelInfo != null, E_OBJ_NOT_FOUND, + "Destination channel not found."); + + // Channel for WebApp + if (pChannelInfo->type == WEBAPP_CHANNEL) + { + bool ret = _ChannelWebAppStub::SendResponse(pChannelInfo->clientId, args); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to send the data to a WebApp."); + } + // Channel for CApp + else if (pChannelInfo->type == CAPP_CHANNEL) + { + bool ret = _ChannelCAppStub::SendResponse(requestId, pChannelInfo->pGIOChannel, args); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to send the data to a CApp."); + } + // Channel for OspApp + else + { + result r = __pIChannelServiceStub->SendResponse(pChannelInfo->clientId, src, dest, args, requestId); + SysTryReturnResult(NID_IO, r == E_SUCCESS, E_SYSTEM, "Failed to send the response data"); + } + + return E_SUCCESS; +} + +result +_ChannelService::SendNullResponse(const String& src, + const String& dest, + int requestId) +{ + SysLog(NID_IO, "[%ls] ---> [%ls], Request ID = %d", src.GetPointer(), dest.GetPointer(), requestId); + + _ChannelInfo* pChannelInfo = null; + + __channels.GetValue(dest, pChannelInfo); + SysTryReturnResult(NID_IO, pChannelInfo != null, E_OBJ_NOT_FOUND, + "Destination channel not found."); + + // Channel for WebApp + if (pChannelInfo->type == WEBAPP_CHANNEL) + { + SysLog(NID_IO, "WebApp Channel, the data are not JSON types"); + return E_SYSTEM; + } + // Channel for OspApp + else + { + __pIChannelServiceStub->SendNullResponse(pChannelInfo->clientId, src, dest, requestId); + } + + return E_SUCCESS; +} + +bool +_ChannelService::IsChannelRegistered(const String& channelId) +{ + bool out = false; + + __channels.ContainsKey(channelId, out); + + return out; +} + +}} diff --git a/src/io/FIo_ChannelServiceManager.cpp b/src/io/FIo_ChannelServiceManager.cpp new file mode 100644 index 0000000..f3605b7 --- /dev/null +++ b/src/io/FIo_ChannelServiceManager.cpp @@ -0,0 +1,96 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelServiceManager.cpp + * @brief This is the implementation file for the _ChannelServiceManager class. + * + */ + +#include +#include "FIo_ChannelServiceManager.h" +#include "FIo_ChannelServiceProxy.h" +#include "FIo_ChannelServiceStub.h" +#include "FIo_ChannelService.h" + +namespace Tizen { namespace Io +{ + +_ChannelServiceManager* _ChannelServiceManager::__pChannnelServiceManager = null; + +_ChannelServiceManager::_ChannelServiceManager(void) + : __pIChannelService(null) +{ + +} + +_ChannelServiceManager::~_ChannelServiceManager(void) +{ + +} + +_ChannelServiceManager* +_ChannelServiceManager::GetInstance(void) +{ + // FIXME: + // Use lock to prevent duplicated creation. + if (__pChannnelServiceManager == null) + { + __pChannnelServiceManager = new (std::nothrow) _ChannelServiceManager; + SysTryReturn(NID_IO, __pChannnelServiceManager != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + } + + return __pChannnelServiceManager; +} + +// This method is called by channel daemon. +// Cahnnel daemon should call this before GetChanelService is called. +void +_ChannelServiceManager::SetChannelService(_IChannelService* pIChannelService) +{ + __pIChannelService = pIChannelService; +} + +// This method returns an _IChannelService interface. +// If this is called by application process a proxy implementation is returned. +// Or if this is called by channel daemon the service implementation is returned. +_IChannelService* +_ChannelServiceManager::GetChannelService(void) +{ + if (__pIChannelService == null) + { + result r = E_SUCCESS; + + _ChannelServiceProxy* pProxy = new (std::nothrow) _ChannelServiceProxy(); + SysTryReturn(NID_IO, pProxy, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pProxy->Construct(); + SysTryCatch(NID_IO, !IsFailed(r), , E_SYSTEM, "[E_SYSTEM] Failed to initialize channel proxy."); + + __pIChannelService = pProxy; + } + + return __pIChannelService; + +CATCH: + delete __pIChannelService; + __pIChannelService = null; + + return null; +} + +}} diff --git a/src/io/FIo_ChannelServiceProxy.cpp b/src/io/FIo_ChannelServiceProxy.cpp new file mode 100644 index 0000000..50645c0 --- /dev/null +++ b/src/io/FIo_ChannelServiceProxy.cpp @@ -0,0 +1,364 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelServiceProxy.cpp + * @brief This is the implementation file for the _ChannelServiceProxy class. + * + */ + +#include +#include + +#include +#include +#include +#include "FIo_IpcClient.h" +#include "FIo_ChannelServiceProxy.h" +#include "FIo_ChannelMessages.h" + +using namespace std; + +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Io; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Io +{ + +_ChannelServiceProxy::_ChannelServiceProxy(void) + : __pIpcClient(null) +{ + +} + +_ChannelServiceProxy::~_ChannelServiceProxy(void) +{ + +} + +result +_ChannelServiceProxy::Construct(void) +{ + SysAssertf(__pIpcClient == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + result r = E_SUCCESS; + static _StringHashProvider hashProvider; + static _StringComparer stringComparer; + + __listeners.Construct(0, 0, hashProvider, stringComparer); + + unique_ptr<_IpcClient> pIpcClient(new (std::nothrow) _IpcClient); + SysTryReturnResult(NID_IO, pIpcClient != null, E_OUT_OF_MEMORY, "Not enough memory."); + + r = pIpcClient->Construct("osp.io.ipcserver.channelmanager", this); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to connect to the IPC server.", GetErrorMessage(r)); + + __pIpcClient = pIpcClient.release(); + + return E_SUCCESS; +} + + +void +_ChannelServiceProxy::OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message) +{ + IPC_BEGIN_MESSAGE_MAP(_ChannelServiceProxy, message) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_sendRequestAsync, &client, OnSendRequestMessage) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_sendNullRequestAsync, &client, OnSendNullRequestMessage) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_sendResponseAsync, &client, OnSendResponseMessage) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_sendNullResponseAsync, &client, OnSendNullResponseMessage) + IPC_END_MESSAGE_MAP_EX() +} + + +result +_ChannelServiceProxy::RegisterChannel(const String& channelId, + const _IChannelServiceEventListener& listener) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "Register a channel : %ls", channelId.GetPointer()); + + result r = E_SUCCESS; + int ret = 0; + bool contain = false; + String key = channelId; + + __listeners.ContainsKey(key, contain); + + if (!contain) + { + __listeners.Add(key, const_cast<_IChannelServiceEventListener*>(&listener)); + + } + else + { + __listeners.SetValue(key, const_cast<_IChannelServiceEventListener*>(&listener)); + } + + unique_ptr pMsg(new (std::nothrow) ChannelServiceMsg_register(channelId, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to register a channel.", GetErrorMessage(r)); + SysTryReturn(NID_IO, ret == E_SUCCESS, ret, ret, "[%s] Failed to register a channel.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +result +_ChannelServiceProxy::UnregisterChannel(const String& channelId) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "Unregister a channel : %ls", channelId.GetPointer()); + + result r = E_SUCCESS; + + String key = channelId; + + r = __listeners.Remove(key); + SysTryReturnResult(NID_IO, !IsFailed(r), E_OBJ_NOT_FOUND, "Failed to unregister a channel."); + + return E_SUCCESS; +} + +result +_ChannelServiceProxy::SendRequest(const String& src, + const String& dest, + const ArrayList& args, + int messageId) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "[%ls] ---> [%ls]", src.GetPointer(), dest.GetPointer()); + + result r = E_SUCCESS; + int ret = 0; + + unique_ptr pMsg(new (std::nothrow) ChannelServiceMsg_sendRequest(src, dest, args, messageId, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to send a request.", GetErrorMessage(r)); + SysTryReturn(NID_IO, ret == E_SUCCESS, ret, ret, "[%s] Failed to send a request.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +result +_ChannelServiceProxy::SendNullRequest(const String& src, + const String& dest, + int messageId) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "[%ls] ---> [%ls]", src.GetPointer(), dest.GetPointer()); + + result r = E_SUCCESS; + int ret = 0; + + unique_ptr pMsg(new (std::nothrow) ChannelServiceMsg_sendNullRequest(src, dest, messageId, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to send a request.", GetErrorMessage(r)); + SysTryReturn(NID_IO, ret == E_SUCCESS, ret, ret, "[%s] Failed to send a request.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +result +_ChannelServiceProxy::SendResponse(const String& src, + const String& dest, + const ArrayList& args, + int messageId) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "[%ls] ---> [%ls]", src.GetPointer(), dest.GetPointer()); + + result r = E_SUCCESS; + int ret = 0; + + unique_ptr pMsg(new (std::nothrow) ChannelServiceMsg_sendResponse(src, dest, args, messageId, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to send a request.", GetErrorMessage(r)); + SysTryReturn(NID_IO, ret == E_SUCCESS, ret, ret, "[%s] Failed to send a request.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +result +_ChannelServiceProxy::SendNullResponse(const String& src, + const String& dest, + int messageId) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "[%ls] ---> [%ls]", src.GetPointer(), dest.GetPointer()); + + result r = E_SUCCESS; + int ret = 0; + + unique_ptr pMsg(new (std::nothrow) ChannelServiceMsg_sendNullResponse(src, dest, messageId, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to send a request.", GetErrorMessage(r)); + SysTryReturn(NID_IO, ret == E_SUCCESS, ret, ret, "[%s] Failed to send a request.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +bool +_ChannelServiceProxy::OnSendRequestMessage(const String& src, const String& dest, const ArrayList& args, int requestId) +{ + SysLog(NID_IO, "[%ls] ---> [%ls]", src.GetPointer(), dest.GetPointer()); + + _IChannelServiceEventListener* pListener = null; + + String key = dest; + + __listeners.GetValue(key, pListener); + + if (pListener) + { + int argCount = args.GetCount(); + Object* pObject = null; + ArrayList* pArrayList = new (std::nothrow) ArrayList; + if (pArrayList == null) + { + const_cast(&args)->RemoveAll(true); + return false; + } + + pArrayList->Construct(); + + for (int i = 0; i < argCount; i++) + { + pObject = (Object*)args.GetAt(i); + pArrayList->Add(*pObject); + } + + pListener->OnChannelRequestReceivedN(src, dest, requestId, pArrayList); + + const_cast(&args)->RemoveAll(false); + + return true; + } + else + { + const_cast(&args)->RemoveAll(true); + } + + return false; +} + +bool +_ChannelServiceProxy::OnSendNullRequestMessage(const String& src, const String& dest, int requestId) +{ + SysLog(NID_IO, "[%ls] ---> [%ls]", src.GetPointer(), dest.GetPointer()); + + _IChannelServiceEventListener* pListener = null; + + String key = dest; + + __listeners.GetValue(key, pListener); + + if (pListener) + { + pListener->OnChannelRequestReceivedN(src, dest, requestId, null); + + return true; + } + + return false; +} + +bool +_ChannelServiceProxy::OnSendResponseMessage(const String& src, const String& dest, const ArrayList& args, int requestId) +{ + SysLog(NID_IO, "[%ls] ---> [%ls]", src.GetPointer(), dest.GetPointer()); + + _IChannelServiceEventListener* pListener = null; + + String key = dest; + + __listeners.GetValue(key, pListener); + + if (pListener) + { + int argCount = args.GetCount(); + Object* pObject = null; + ArrayList* pArrayList = new (std::nothrow) ArrayList; + if (pArrayList == null) + { + const_cast(&args)->RemoveAll(true); + return false; + } + + pArrayList->Construct(); + + for (int i = 0; i < argCount; i++) + { + pObject = (Object*)args.GetAt(i); + pArrayList->Add(*pObject); + } + + pListener->OnChannelResponseReceivedN(src, dest, requestId, pArrayList); + + const_cast(&args)->RemoveAll(false); + + return true; + } + else + { + const_cast(&args)->RemoveAll(true); + } + + return false; +} + +bool +_ChannelServiceProxy::OnSendNullResponseMessage(const String& src, const String& dest, int requestId) +{ + SysLog(NID_IO, "[%ls] ---> [%ls]", src.GetPointer(), dest.GetPointer()); + + _IChannelServiceEventListener* pListener = null; + + String key = dest; + + __listeners.GetValue(key, pListener); + + if (pListener) + { + pListener->OnChannelResponseReceivedN(src, dest, requestId, null); + } + + return false; +} + +}} diff --git a/src/io/FIo_ChannelServiceStub.cpp b/src/io/FIo_ChannelServiceStub.cpp new file mode 100644 index 0000000..f9abe4a --- /dev/null +++ b/src/io/FIo_ChannelServiceStub.cpp @@ -0,0 +1,230 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelServiceStub.cpp + * @brief This is the implementation file for the _ChannelServiceStub class. + * + */ + +#include +#include +#include +#include + +#include +#include +#include "FIo_IpcServer.h" +#include "FIo_ChannelServiceStub.h" +#include "FIo_ChannelMessages.h" +#include "FIo_ChannelService.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Io; + +using namespace std; + +namespace Tizen { namespace Io +{ + +_ChannelServiceStub::_ChannelServiceStub(void) + : __pIpcServer(null) + , __pChannelService(null) +{ + +} + +_ChannelServiceStub::~_ChannelServiceStub(void) +{ + delete __pIpcServer; +} + +result +_ChannelServiceStub::Construct(void) +{ + SysAssertf(__pIpcServer == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + SysLog(NID_IO, "Constructed"); + + result r = E_SUCCESS; + _IpcServer* pIpcServer = null; + + pIpcServer = new (std::nothrow) _IpcServer; + SysTryReturnResult(NID_IO, pIpcServer != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pIpcServer->Construct("osp.io.ipcserver.channelmanager", *this, false); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to create IPC server(ChannelService)", GetErrorMessage(r)); + + __pIpcServer = pIpcServer; + + return E_SUCCESS; + +CATCH: + delete pIpcServer; + + return r; +} + +void +_ChannelServiceStub::SetChannelService(_ChannelService& service) +{ + __pChannelService = &service; +} + +bool +_ChannelServiceStub::OnRegisterChannelMessage(const Tizen::Base::String& appId, int* pResult) +{ + SysAssertf(__pChannelService != null, "Channel service has not been initialized.\n"); + + int clientId = __pIpcServer->GetClientId(); + + *pResult = __pChannelService->RegisterChannel(appId, clientId); + + return true; +} + +bool +_ChannelServiceStub::OnSendRequestMessage(const String& src, + const String& dest, + const ArrayList& args, + int requestId, + int* pResult) +{ + SysAssertf(__pChannelService != null, "Channel service has not been initialized.\n"); + + *pResult = __pChannelService->SendRequest(src, dest, args, requestId); + + const_cast(&args)->RemoveAll(true); + + return true; +} + +bool +_ChannelServiceStub::OnSendNullRequestMessage(const String& src, + const String& dest, + int requestId, + int* pResult) +{ + SysAssertf(__pChannelService != null, "Channel service has not been initialized.\n"); + + *pResult = __pChannelService->SendNullRequest(src, dest, requestId); + + return true; +} + +bool +_ChannelServiceStub::OnSendResponseMessage(const String& src, + const String& dest, + const ArrayList& args, + int requestId, + int* pResult) +{ + SysAssertf(__pChannelService != null, "Channel service has not been initialized.\n"); + + *pResult = __pChannelService->SendResponse(src, dest, args, requestId); + + const_cast(&args)->RemoveAll(true); + + return true; +} + +bool +_ChannelServiceStub::OnSendNullResponseMessage(const String& src, + const String& dest, + int requestId, + int* pResult) +{ + SysAssertf(__pChannelService != null, "Channel service has not been initialized.\n"); + + *pResult = __pChannelService->SendNullResponse(src, dest, requestId); + + return true; +} + +result +_ChannelServiceStub::SendRequest(int clientId, const String& src, const String& dest, const ArrayList& args, int requestId) +{ + SysAssertf(__pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pIpcServer->SendResponse(clientId, new ChannelServiceMsg_sendRequestAsync(src, dest, args, requestId)); +} + +result +_ChannelServiceStub::SendNullRequest(int clientId, const String& src, const String& dest, int requestId) +{ + SysAssertf(__pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pIpcServer->SendResponse(clientId, new ChannelServiceMsg_sendNullRequestAsync(src, dest, requestId)); +} + +result +_ChannelServiceStub::SendResponse(int clientId, const String& src, const String& dest, const ArrayList& args, int requestId) +{ + SysAssertf(__pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pIpcServer->SendResponse(clientId, new ChannelServiceMsg_sendResponseAsync(src, dest, args, requestId)); +} + +result +_ChannelServiceStub::SendNullResponse(int clientId, const String& src, const String& dest, int requestId) +{ + SysAssertf(__pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n"); + + return __pIpcServer->SendResponse(clientId, new ChannelServiceMsg_sendNullResponseAsync(src, dest, requestId)); +} + +void +_ChannelServiceStub::OnIpcRequestReceived(_IpcServer& server, const IPC::Message& message) +{ + IPC_BEGIN_MESSAGE_MAP(_ChannelServiceStub, message) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_register, &server, OnRegisterChannelMessage) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_sendRequest, &server, OnSendRequestMessage) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_sendNullRequest, &server, OnSendNullRequestMessage) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_sendResponse, &server, OnSendResponseMessage) + IPC_MESSAGE_HANDLER_EX(ChannelServiceMsg_sendNullResponse, &server, OnSendNullResponseMessage) + IPC_END_MESSAGE_MAP_EX() +} + +void +_ChannelServiceStub::OnIpcServerStarted(const _IpcServer& server) +{ + +} + +void +_ChannelServiceStub::OnIpcServerStopped(const _IpcServer& server) +{ + +} + +void +_ChannelServiceStub::OnIpcClientConnected(const _IpcServer& server, int clientId) +{ + +} + +void +_ChannelServiceStub::OnIpcClientDisconnected(const _IpcServer& server, int clientId) +{ + SysAssertf(__pChannelService != null, "Channel service has not been initialized.\n"); + SysLog(NID_IO, "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); + __pChannelService->UnregisterChannel(clientId); + SysLog(NID_IO, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); +} + +}} diff --git a/src/io/FIo_ChannelWebAppStub.cpp b/src/io/FIo_ChannelWebAppStub.cpp new file mode 100644 index 0000000..fe2fb6d --- /dev/null +++ b/src/io/FIo_ChannelWebAppStub.cpp @@ -0,0 +1,1125 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelWebAppStub.cpp + * @brief This is the implementation file for the _ChannelWebAppStub class. + * + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "FIo_ChannelWebAppStub.h" + +#define MAX_BUFFER_LENGTH 4096 + +#define htonll(x) ((((uint64_t)htonl(x)) << 32) + htonl(x >> 32)) +#define ntohll(x) ((((uint64_t)ntohl(x)) << 32) + ntohl(x >> 32)) + +using namespace std; + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Utility; +using namespace Tizen::Io; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +static const size_t _MAX_CONNECTIONS = 10; +static const size_t _MAX_BUFFER_SIZE = 1024; +static const int _PORT = 8080; + +//static const char* webSocketServerAddr = "127.0.0.1"; +static const char* webSocketHeaderId("Upgrade"); // web socket header identifier +static const char* webSocketHeaderKey("Sec-WebSocket-Key"); // hybi10 +static const char* webSocketHeaderKey1("Sec-WebSocket-Key1"); // hybi00 +static const char* webSocketHeaderKey2("Sec-WebSocket-Key2"); // hybi00 +static const char* webSocketHeaderIdHybi10("websocket"); +static const char* webSocketHeaderIdHybi00("WebSocket"); +static const char* webSocketMagicString("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); + +static const int _CHALLENGE_NUMBER_SIZE = 4; +static const int _CHALLENGE_THIRD_INFO_SIZE = 8; +static const int _CHALLENGE_RESPONSE_SIZE = 16; + +const unsigned char _SIMPLE_PAYLOAD_MAX_LEN = 125; +const unsigned char _EXTEND_PAYLOAD_TYPE_LEN16 = 0x7e; //126 +const unsigned char _EXTEND_PAYLOAD_TYPE_LEN64 = 0x7f; //127 + +WebSocketType gHeaderType = WS_NONE; + +enum WebSocketOpcode +{ + OPCODE_CONTINUE = 0x0, + OPCODE_TEXT_MESSAGE = 0x1, + OPCODE_BIN_MESSAGE = 0x2, + OPCODE_CONNECTION_CLOSE = 0x8, + OPCODE_PING = 0x9, + OPCODE_PONG = 0xA +}; + + +_ChannelWebAppStub::_WebSocketMessage::_WebSocketMessage(void) + : m_payloadOffset(0) + , m_payloadLen(0) + , m_headerParsed(false) + , m_payload(null) +{ +} + +_ChannelWebAppStub::_WebSocketMessage::~_WebSocketMessage(void) +{ + delete[] m_payload; +} + +size_t +_ChannelWebAppStub::_WebSocketMessage::CreateMessage(std::string& payload, std::string& message) +{ + message.clear(); + uint8_t *pCurrent = reinterpret_cast(const_cast(message.c_str())); + uint8_t *pStart = pCurrent; + + // fin: 1 , opcode: 1 + *pCurrent |= 0x81; + pCurrent++; + // masked : 0 (no mask) + *pCurrent &= 0x00; + + // set payload len + if (payload.size() > _SIMPLE_PAYLOAD_MAX_LEN) + { + if (payload.size() < 64 * 1024) + { + *pCurrent |= _EXTEND_PAYLOAD_TYPE_LEN16; + pCurrent++; + uint16_t length = payload.size(); + + // Change the byte order + length = htons(length); + + memcpy(pCurrent, &length, 2); + pCurrent = pCurrent + 2; + } + else + { + *pCurrent |= _EXTEND_PAYLOAD_TYPE_LEN64; + pCurrent++; + uint64_t length = payload.size(); + + // Change the byte order + length = htonll(length); + + memcpy(pCurrent, &length, 8); + pCurrent = pCurrent + 8; + } + } + else + { + *pCurrent |= payload.size(); + pCurrent++; + } + + memcpy(pCurrent, payload.c_str(), payload.size()); + pCurrent = pCurrent + payload.size(); + //*pCurrent = '\0'; + //pCurrent++; + + return pCurrent - pStart; +} + +int +_ChannelWebAppStub::_WebSocketMessage::ParseHeader(uint8_t* message, int messageLen) +{ + SysTryLogReturn(NID_IO, message != null, -1, "message is null"); + + SysLog(NID_IO, "message = %s, size = %d", message, messageLen); + + uint8_t* pCurrent = message; + + // check 'fin' bit + m_header.factors.fin = 0x1 & *pCurrent >> 7; + // check 'opcode' bit + m_header.factors.opcode = 0xf & *pCurrent; + pCurrent++; + + // check 'masked' bit + m_header.factors.masked = 0x1 & *pCurrent >> 7; + // check 'payload' type bit + m_header.factors.payloadLen = 0x7f & *pCurrent; + pCurrent++; + + // set payload length + m_payloadLen = 0; + if (m_header.factors.payloadLen == _EXTEND_PAYLOAD_TYPE_LEN16) + { + SysLog(NID_IO, "extended payload len 16"); + + uint16_t length = 0; + memcpy(&length, pCurrent, 2); + + // Change the byte order + m_payloadLen = ntohs(length); + + pCurrent = pCurrent + 2; // jump two byte + } + else if (m_header.factors.payloadLen == _EXTEND_PAYLOAD_TYPE_LEN64) + { + SysLog(NID_IO, "extended payload len 64"); + + uint64_t length = 0; + memcpy(&length, pCurrent, 8); + + // Change the byte order + m_payloadLen = ntohll(length); + + pCurrent = pCurrent + 8; // jump eight byte + } + else + { + SysLog(NID_IO, "default payload len"); + m_payloadLen = m_header.factors.payloadLen; + } + + SysLog(NID_IO, "m_payloadLen = %lld", m_payloadLen); + + SysTryLogReturn(NID_IO, m_payloadLen <= (uint64_t)messageLen, -1, "header parsing error!"); + + // set masking-key + if (m_header.factors.masked == 1) + { + memcpy(m_maskingKey, pCurrent, 4); + pCurrent = pCurrent + 4; // jump four byte + } + + m_payloadOffset = pCurrent - message; + m_headerParsed = true; + + SysLog(NID_IO, "m_payloadOffset = %d", m_payloadOffset); + + return 0; +} + +int +_ChannelWebAppStub::_WebSocketMessage::ParsePayload(uint8_t* message, int messageLen) +{ + SysTryLogReturn(NID_IO, message != null, -1, "message is null"); + + SysLog(NID_IO, "message = %s", message); + + SysTryLogReturn(NID_IO, m_payloadLen <= (uint64_t)messageLen, -1, "payloadLen is invalid!"); + SysTryLogReturn(NID_IO, m_headerParsed == true, -1, "header not existed!"); + + // set payload length + m_payload = new (std::nothrow) uint8_t[m_payloadLen + 1]; + SysTryLogReturn(NID_IO, m_payload != null, -1, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + memcpy(m_payload, message + m_payloadOffset, m_payloadLen); + + // apply masking key to payload + if (m_header.factors.masked == 1) + { + uint8_t *payload = m_payload; + for (uint64_t i = 0; i < m_payloadLen; i++) + { + payload[i] ^= m_maskingKey[i % 4]; + } + payload[m_payloadLen] = '\0'; + } + + return 0; +} + +void +_ChannelWebAppStub::_WebSocketMessage::ConsoleMessage(void) const +{ + SysLog(NID_IO, "fin: %d", static_cast(m_header.factors.fin)); + SysLog(NID_IO, "masked: %d", static_cast(m_header.factors.masked)); + SysLog(NID_IO, "opcode: %d", static_cast(m_header.factors.opcode)); + SysLog(NID_IO, "payload: %s", m_payload); + SysLog(NID_IO, "payload len: %d", m_payloadLen); +} + +_ChannelWebAppStub::_ChannelInfo::_ChannelInfo(void) + : pClientInfo(null) + , pGIOChannel(null) + , pGSource(null) + , destroySource(true) +{ +} + +_ChannelWebAppStub::_ChannelInfo::~_ChannelInfo(void) +{ + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (pGSource != null) + { + if (destroySource) + { + g_source_destroy(pGSource); + } + + g_source_unref(pGSource); + } +} + +_ChannelWebAppStub::_ClientInfo::_ClientInfo(void) + : pChannelStub(null) +{ +} + +_ChannelWebAppStub::_ClientInfo::~_ClientInfo(void) +{ + channels.clear(); +} + +_ChannelWebAppStub::_ChannelWebAppStub(void) + : __pChannelService(null) + , __pGMainContext(null) + , __pServerGSource(null) + , __pClientGSource(null) + , __pClients(null) +{ +} + +_ChannelWebAppStub::~_ChannelWebAppStub(void) +{ + if (__pServerGSource != null) + { + g_source_destroy(__pServerGSource); + g_source_unref(__pServerGSource); + __pServerGSource = null; + } +} + +result +_ChannelWebAppStub::Construct(void) +{ + GSource* pGSource = null; + GIOChannel* pGIOChannel = null; + struct sockaddr_in socketInfo; + int serverSocket = -1; + int ret = 0; + result r = E_SUCCESS; + + __pClients = new (std::nothrow) HashMap(); + SysTryReturnResult(NID_IO, __pClients != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + __pClients->Construct(50); + + __pGMainContext = g_main_context_get_thread_default(); //get own gmain context except default thread + if (__pGMainContext == null) + { + __pGMainContext = g_main_context_default(); //get gmain context from me (default) + SysTryReturnResult(NID_IO, __pGMainContext != null, E_SYSTEM, + "Failed to get glib context."); + } + + // create native socket + // set non-blocking socket mode + serverSocket = socket(AF_INET, + SOCK_STREAM | SOCK_NONBLOCK, + IPPROTO_TCP); + + SysTryReturnResult(NID_IO, serverSocket != -1, E_SYSTEM, + "Failed to create a socket."); + + int reuse = 1; + ret = setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)); + SysTryCatch(NID_IO, ret != -1, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to set options on socket(%d, %s): %d", serverSocket, strerror(errno), errno); + + // create native socket of server + memset(&socketInfo, 0, sizeof(socketInfo)); + socketInfo.sin_family = AF_INET; + //socketInfo.sin_addr.s_addr = inet_addr(webSocketServerAddr); + //socketInfo.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + socketInfo.sin_addr.s_addr = htonl(INADDR_ANY); + socketInfo.sin_port = htons(_PORT); + + // bind local address + ret = bind(serverSocket, + (const struct sockaddr*) &socketInfo, + sizeof(struct sockaddr_in)); + SysTryCatch(NID_IO, ret != -1, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to bind a socket(%d, %s): %d", serverSocket, strerror(errno), errno); + + listen(serverSocket, _MAX_CONNECTIONS); + + pGIOChannel = g_io_channel_unix_new(serverSocket); + SysTryCatch(NID_IO, pGIOChannel != null, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to create GIOChannel for socket."); + + // socket will be closed when pGIOChannel is deleted. + g_io_channel_set_close_on_unref(pGIOChannel, TRUE); + serverSocket = -1; + + pGSource = g_io_create_watch(pGIOChannel, (GIOCondition)(G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP)); + SysTryCatch(NID_IO, pGSource != null, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Failed to create GSource for socket."); + + // channel will be delete when pGSource is deleted. + g_io_channel_unref(pGIOChannel); + pGIOChannel = null; + + g_source_set_callback(pGSource, (GSourceFunc) OnConnectionRequest, this, NULL); + g_source_attach(pGSource, __pGMainContext); + + __pServerGSource = pGSource; + + return E_SUCCESS; + +CATCH: + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (serverSocket != -1) + { + close(serverSocket); + } + + if (__pGMainContext) + { + g_main_context_unref(__pGMainContext); + __pGMainContext = null; + } + + return r; +} + +void +_ChannelWebAppStub::SetChannelService(_ChannelService& service) +{ + __pChannelService = &service; +} + +gboolean +_ChannelWebAppStub::OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data) +{ + int serverFd = -1; + int clientFd = -1; + struct sockaddr_in socketInfo; + socklen_t socketInfoLength = sizeof(socketInfo); + GSource* pGSource = null; + GIOChannel* pGIOChannel = null; + GError* pGError = null; + _ClientInfo* pClientInfo = null; + _ChannelInfo* pChannelInfo = null; + WebSocketType headerType; + SoupMessageHeaders* pSoupHeader = null; + int len = -1; + bool out = false; + + AppId srcAppId; + AppId destAppId; + String key; + + _ChannelWebAppStub* pChannelStub = static_cast< _ChannelWebAppStub* >(data); + SysTryReturn(NID_IO, pChannelStub != null, FALSE, E_SYSTEM, + "[E_SYSTEM] pChannelStub is null."); + + serverFd = g_io_channel_unix_get_fd(source); + + clientFd = accept(serverFd, + (struct sockaddr*) &socketInfo, + &socketInfoLength); + SysTryReturn(NID_IO, clientFd != -1, FALSE, E_SYSTEM, "[E_SYSTEM] Failed to accept."); + + // Get a http header + std::string headerData; + char header[_MAX_BUFFER_SIZE + 1] = {0,}; + int headerLength = recv(clientFd, (char*)(header), _MAX_BUFFER_SIZE, 0); + if (headerLength < 0) + { + SysLog(NID_IO, "errno = %d %s", errno, strerror(errno)); + SysLog(NID_IO, "headerLength = %d", headerLength); + SysLog(NID_IO, "Recv header = %s", header); + + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to recv, header length is less than 0."); + goto CATCH; + } + + SysLog(NID_IO, "recv - header length = %d", headerLength); + SysLog(NID_IO, "recv - header data = %s", header); + + pGIOChannel = g_io_channel_unix_new(clientFd); + SysTryCatch(NID_IO, pGIOChannel != null, , E_SYSTEM, "[E_SYSTEM] Failed to create GIOChannel."); + + g_io_channel_set_encoding(pGIOChannel, NULL, &pGError); + g_io_channel_set_flags(pGIOChannel, G_IO_FLAG_NONBLOCK, &pGError); + + g_io_channel_set_close_on_unref(pGIOChannel, TRUE); + //clientFd = -1; + + // Handshake with WebApp + // check if header of app socket is not for websocket + headerData = header; + headerType = VerifyHttpHeaderType(headerData, headerLength); + + SysLog(NID_IO, "VerifyHttpHeader, type = %d", headerType); + + if (headerType == WS_NONE) + { + SysLog(NID_IO, "Unpermitted header type"); + close(clientFd); + } + + // Set the header type + gHeaderType = headerType; + + + // create soup header + pSoupHeader = soup_message_headers_new(SOUP_MESSAGE_HEADERS_REQUEST); + //soup_headers_parse(header.c_str(), headerLength, pSoupHeader); + soup_headers_parse(header, headerLength, pSoupHeader); + + if (headerType == WS_HYBI00) + { + SysLog(NID_IO, "WS_HYBI00"); + + // get third information from http header + unsigned int firstInfo = ExtractChallengeNumber( + soup_message_headers_get_one(pSoupHeader, webSocketHeaderKey1)); + unsigned int secondInfo = ExtractChallengeNumber( + soup_message_headers_get_one(pSoupHeader, webSocketHeaderKey2)); + unsigned char thirdInfo[8]; + //char *pThirdInfoPos = const_cast(header.c_str()) + headerLength - _CHALLENGE_THIRD_INFO_SIZE; + char *pThirdInfoPos = const_cast(header) + headerLength - _CHALLENGE_THIRD_INFO_SIZE; + memcpy(thirdInfo, reinterpret_cast(pThirdInfoPos), _CHALLENGE_THIRD_INFO_SIZE); + + // make challenge response data for hybi00 + const std::string response = MakeHybi00Response(firstInfo, secondInfo, thirdInfo); + // create response header to be sent to app + std::string responseHeader = CreateResponseHeader(clientFd, pSoupHeader, response); + // send response header + len = send(clientFd, responseHeader.c_str(), responseHeader.size(), 0); + + } + else if (headerType == WS_HYBI10) + { + SysLog(NID_IO, "WS_HYBI10"); + + const char* pSecureKeyValue = soup_message_headers_get_one( + pSoupHeader, webSocketHeaderKey); + + std::string secureKey(pSecureKeyValue); + secureKey.append(webSocketMagicString); + + // make Sec-WebSocket-Accept data for hybi10 + const std::string response = MakeHybi10Response(secureKey); + + // create response header to be sent to app + std::string responseHeader = CreateResponseHeader(clientFd, pSoupHeader, response); + + // send response header + SysLog(NID_IO, "Send responseHeader = %s", responseHeader.c_str()); + len = send(clientFd, responseHeader.c_str(), responseHeader.size(), 0); + if (len < 1) + { + SysLog(NID_IO, "errno = %d %s", errno, strerror(errno)); + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to send responseHeader, length is less than 1."); + goto CATCH; + } + } + else + { + SysLog(NID_IO, "ELSE"); + } + + if (len == -1) + { + SysLog(NID_IO, "Failed to send responseHeader"); + SysLog(NID_IO, "errno = %d %s", errno, strerror(errno)); + close(clientFd); + return false; + } + + // Parse and set appId for WebApp + { + String tempStr; + String headerString(header); + + // header = "GET /ipc?src=abcde1234.WebApp&dest=4z6olle215.Dictionary HTTP/1.1^M" + StringTokenizer st(headerString, L" /?=&"); + st.GetNextToken(tempStr); // GET + st.GetNextToken(tempStr); // ipc + st.GetNextToken(tempStr); // src + st.GetNextToken(srcAppId); + st.GetNextToken(tempStr); // dest + st.GetNextToken(destAppId); + } + + // Check the destAppId + out = pChannelStub->__pChannelService->IsChannelRegistered(destAppId); + SysTryCatch(NID_IO, out, , E_SYSTEM, "[E_SYSTEM] Destination channel is not found."); + + // Set a ClientInfo + key = srcAppId; + pChannelStub->__pClients->ContainsKey(key, out); + if (!out) // first connection request from this client + { + SysLog(NID_IO, "First Connection of WebApp - AppId = %ls", srcAppId.GetPointer()); + + pClientInfo = new (std::nothrow) _ClientInfo(); + + pClientInfo->srcAppId = srcAppId; + //pClientInfo->srcAppExecName = srcAppExecName; + pClientInfo->pChannelStub = pChannelStub; + //pClientInfo->clientId = clientFd; + pClientInfo->key = key; + + pChannelStub->__pClients->Add(*(new String(key)), *pClientInfo); + + // Stores client info to _ChannelService + SysLog(NID_IO, "Register Channel for WebApp"); + + pChannelStub->__pChannelService->RegisterChannel(srcAppId, clientFd, WEBAPP_CHANNEL); + } + + SysLog(NID_IO, "srcAppId = %ls, destAppId = %ls", srcAppId.GetPointer(), destAppId.GetPointer()); + + // Set the callbak + pChannelInfo = new (std::nothrow) _ChannelInfo; + SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pGSource = g_io_create_watch(pGIOChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP)); + + g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL); + g_source_attach(pGSource, ((_ChannelWebAppStub*)data)->__pGMainContext); + + pChannelStub->__pClientGSource = pGSource; + + + // Set a ChannelInfo + pChannelInfo->pClientInfo = pClientInfo; + pChannelInfo->pGIOChannel = pGIOChannel; + pChannelInfo->pGSource = pGSource; + pChannelInfo->destAppId = destAppId; + + pClientInfo->channels.push_back(pChannelInfo); + + + return true; + +CATCH: + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (clientFd != -1) + { + close(clientFd); + } + + return true; +} + +gboolean +_ChannelWebAppStub::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data) +{ + SysLog(NID_IO, "Callback"); + + gboolean ret = FALSE; + + _ChannelInfo* pChannelInfo = (_ChannelInfo*) data; + _ClientInfo* pClientInfo = pChannelInfo->pClientInfo; + _ChannelWebAppStub* pChannelStub = (_ChannelWebAppStub*) pClientInfo->pChannelStub; + ret = pChannelStub->HandleReceivedMessage(source, condition, data); + + return ret; +} + +gboolean +_ChannelWebAppStub::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data) +{ + result r = E_SUCCESS; + GError* pGError = null; + int clientFd = g_io_channel_unix_get_fd(source); + + SysLog(NID_IO, "HandleMessage - client = %d", clientFd); + + _ChannelInfo* pChannelInfo = (_ChannelInfo*) data; + _ClientInfo* pClientInfo = pChannelInfo->pClientInfo; + _ChannelWebAppStub* pChannelStub = (_ChannelWebAppStub*) pClientInfo->pChannelStub; + + if (condition & G_IO_HUP) + { + SysLog(NID_IO, "G_IO_HUP - connection closed"); + + g_io_channel_shutdown(source, FALSE, &pGError); + + for (unsigned int i = 0; i < pClientInfo->channels.size(); i++) + { + if (pChannelInfo == pClientInfo->channels[i]) + { + pClientInfo->channels.erase(pClientInfo->channels.begin() + i); + + // Do not destroy a source in a dispatch callback + // because main loop will do it if the callback return FALSE. + pChannelInfo->destroySource = false; + delete pChannelInfo; + + break; + } + } + + if (pClientInfo->channels.size() == 0) + { + SysLog(NID_IO, "All connections of client(%ls) are closed. delete client info", pClientInfo->srcAppId.GetPointer()); + + String key = pClientInfo->srcAppId; + __pClients->Remove(key, false); + + delete pClientInfo; + + pChannelStub->__pChannelService->UnregisterChannel(clientFd); + } + + return FALSE; + } + else if (condition & G_IO_IN) + { + SysLog(NID_IO, "G_IO_IN"); + + unique_ptr pBuffer(new char[MAX_BUFFER_LENGTH]); + int len = recv(clientFd, (char *)pBuffer.get(), MAX_BUFFER_LENGTH, 0); + if (len < 0) + { + SysLog(NID_IO, "recv error: errno = %d %s", errno, strerror(errno)); + SysLog(NID_IO, "headerLength = %d", len); + SysLog(NID_IO, "Recv header = %s", pBuffer.get()); + + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to recv, length is less than 0."); + + return FALSE; + } + else if (len == 0) + { + SysLog(NID_IO, "The peer has performed an orderly shutdown, recv = %d", len); + + g_io_channel_shutdown(source, FALSE, &pGError); + + for (unsigned int i = 0; i < pClientInfo->channels.size(); i++) + { + if (pChannelInfo == pClientInfo->channels[i]) + { + pClientInfo->channels.erase(pClientInfo->channels.begin() + i); + + // Do not destroy a source in a dispatch callback + // because main loop will do it if the callback return FALSE. + pChannelInfo->destroySource = false; + delete pChannelInfo; + + break; + } + } + + if (pClientInfo->channels.size() == 0) + { + SysLog(NID_IO, "All connections of client(%ls) are closed. delete client info", pClientInfo->srcAppId.GetPointer()); + + String key = pClientInfo->srcAppId; + __pClients->Remove(key, false); + + delete pClientInfo; + + pChannelStub->__pChannelService->UnregisterChannel(clientFd); + } + + return FALSE; + } + + if (gHeaderType == WS_HYBI00) + { + // Not supported because of old websocket protocol + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Not supported protocol."); + + return FALSE; + } + else if (gHeaderType == WS_HYBI10) + { + SysLog(NID_IO,"WS_HYBI10 is supported, received data: %s (%d)", pBuffer.get(), len); + + // Current webkit of tizen support + _WebSocketMessage message; + int ret = 0; + ret = message.ParseHeader(reinterpret_cast(pBuffer.get()), len); + SysTryReturn(NID_IO, ret >= 0, FALSE, E_SYSTEM, "[E_SYSTEM] Fail to parse the header!"); + + ret = message.ParsePayload(reinterpret_cast(pBuffer.get()), len); + SysTryReturn(NID_IO, ret >= 0, FALSE, E_SYSTEM, "[E_SYSTEM] Fail to parse the payload!"); + + message.ConsoleMessage(); + + // do something for opcode or custom protocol of payload + if (message.m_header.factors.opcode == OPCODE_CONNECTION_CLOSE) + { + SysLog(NID_IO,"OPCODE_CONNECTION_CLOSE with clientFd: %d", clientFd); + + g_io_channel_shutdown(source, FALSE, &pGError); + + for (unsigned int i = 0; i < pClientInfo->channels.size(); i++) + { + if (pChannelInfo == pClientInfo->channels[i]) + { + pClientInfo->channels.erase(pClientInfo->channels.begin() + i); + + // Do not destroy a source in a dispatch callback + // because main loop will do it if the callback return FALSE. + pChannelInfo->destroySource = false; + delete pChannelInfo; + + break; + } + } + + if (pClientInfo->channels.size() == 0) + { + SysLog(NID_IO, "All connections of client(%ls) are closed. delete client info", pClientInfo->srcAppId.GetPointer()); + + String key = pClientInfo->srcAppId; + __pClients->Remove(key, false); + + delete pClientInfo; + + pChannelStub->__pChannelService->UnregisterChannel(clientFd); + } + + return FALSE; + } + else if (message.m_header.factors.opcode == OPCODE_TEXT_MESSAGE) + { + // Parse the data + RequestId reqId = 0; + + ArrayList list; + list.Construct(); + + list.Add(*(new String((char*)message.m_payload))); + + SysLog(NID_IO, "srcAppId = %ls, destAppId = %ls", pClientInfo->srcAppId.GetPointer(), pChannelInfo->destAppId.GetPointer()); + + r = pChannelStub->__pChannelService->SendRequest(pClientInfo->srcAppId, + pChannelInfo->destAppId, list, reqId); + SysTryReturn(NID_IO, !IsFailed(r), FALSE, E_SYSTEM, "[E_SYSTEM] Failed to send request."); + + list.RemoveAll(true); + } + else + { + // Not yet supported opcode + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Not supported Opcode."); + + return FALSE; + } + } + else + { + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Not supported protocol."); + + return FALSE; + } + + } + else + { + SysLog(NID_IO, "G_IO else"); + return FALSE; + } + + return TRUE; +} + +WebSocketType +_ChannelWebAppStub::VerifyHttpHeaderType(std::string header, int headerLength) +{ + // parse http header + SoupMessageHeaders* pSoupHeader = + soup_message_headers_new(SOUP_MESSAGE_HEADERS_REQUEST); + if (!soup_headers_parse(header.c_str(), headerLength, pSoupHeader)) + { + return WS_NONE; + } + + WebSocketType headerType; + const char* pHeaderValue = + soup_message_headers_get_one(pSoupHeader, webSocketHeaderId); + + if (!pHeaderValue) + { + SysLog(NID_IO, "Not for web socket header."); + return WS_NONE; + } + + if (strcmp(pHeaderValue, webSocketHeaderIdHybi00) == 0) + { + headerType = WS_HYBI00; + } + if (strcmp(pHeaderValue, webSocketHeaderIdHybi10) == 0) + { + headerType = WS_HYBI10; + } + else + { + headerType = WS_NONE; + } + + return headerType; +} + +std::string +_ChannelWebAppStub::CreateResponseHeader(int appSocket, SoupMessageHeaders *header, + const std::string& response) +{ + std::string responseHeader; + + //if (m_appSockets[appSocket] == WS_HYBI00) { + if (gHeaderType == WS_HYBI00) + { + responseHeader.append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"); + responseHeader.append("Upgrade: WebSocket\r\n"); + responseHeader.append("Connection: Upgrade\r\n"); + responseHeader.append("Sec-WebSocket-Origin: "); + responseHeader.append(soup_message_headers_get_one(header, "Origin")); + responseHeader.append("\r\n"); + responseHeader.append("Sec-WebSocket-Location: ws://"); + responseHeader.append(soup_message_headers_get_one(header, "Host")); + responseHeader.append("\r\n"); + responseHeader.append("\r\n"); + responseHeader.append(response.c_str()); + //} else if (m_appSockets[appSocket] == WS_HYBI10) { + } + else if (gHeaderType == WS_HYBI10) + { + responseHeader.append("HTTP/1.1 101 Switching Protocols\r\n"); + responseHeader.append("Upgrade: websocket\r\n"); + responseHeader.append("Connection: Upgrade\r\n"); + responseHeader.append("Sec-WebSocket-Accept: "); + responseHeader.append(response.c_str()); + responseHeader.append("\r\n"); + responseHeader.append("\r\n"); + // TODO Sec-WebSocket-Protocol support + } + else + { + responseHeader = std::string(); + } + + return responseHeader; +} + +std::string +_ChannelWebAppStub::MakeHybi00Response(uint32_t first, uint32_t second, uint8_t* third) +{ + SysAssertf(third != null, "The input parameter third should not be null."); + + if (sizeof(third) != _CHALLENGE_NUMBER_SIZE) + { + SysLog(NID_IO, "Invalid third argument."); + return NULL; + } + + bool result = false; + uint8_t temp[_CHALLENGE_RESPONSE_SIZE]; + result = AppendChallengeNumber(first, &temp[0]); + if (!result) + { + SysLog(NID_IO, "Failed to set challenge number."); + return NULL; + } + + result = AppendChallengeNumber(second, &temp[4]); + if (!result) + { + SysLog(NID_IO, "Failed to set challenge number."); + return NULL; + } + + memcpy(temp + 8, third, _CHALLENGE_THIRD_INFO_SIZE); + SysLog(NID_IO,"Challenge Response before md5 : %s", reinterpret_cast(temp)); + + // set MD5 hash + unsigned char hash[16]; + MD5((unsigned char*) temp, _CHALLENGE_RESPONSE_SIZE, hash); + + return std::string(reinterpret_cast(hash)); +} + +std::string +_ChannelWebAppStub::MakeHybi10Response(std::string& secureAccept) +{ + if (secureAccept.empty()) + { + SysLog(NID_IO, "Invalid argruments"); + return NULL; + } + + unsigned char hash[20]; + SHA1(reinterpret_cast(secureAccept.c_str()), + secureAccept.size(), + hash); + + return std::string(EncodeBase64(hash, 20)); +} + +bool +_ChannelWebAppStub::AppendChallengeNumber(uint32_t number, unsigned char *response) +{ + if (!response) + { + SysLog(NID_IO, "Invalid response string"); + return false; + } + + // by spec, challenge number should be added as big endian + unsigned char* pIdx = response + 3; + for (int i = 0; i < 4; i++) + { + *pIdx = 0xff & number; + pIdx--; + number >>= 8; + } + + return true; +} + +unsigned int +_ChannelWebAppStub::ExtractChallengeNumber(const char* keyString) +{ + if (!keyString) + { + SysLog(NID_IO, "Invalid secure key"); + return 0; + } + + int space = 0; + std::string digits; + std::string secureKey(keyString); + std::string::iterator it; + + for (it = secureKey.begin(); it < secureKey.end(); it++) + { + if (*it == ' ') + { + space++; + } + else if ((*it >= '0') && (*it <= '9')) + { + digits.insert(digits.end(), 1, *it); + } + } + + std::istringstream stream(digits); + unsigned int numFromDigits = 0; + stream >> numFromDigits; + + return space ? (numFromDigits / space) : numFromDigits; +} + +char* +_ChannelWebAppStub::EncodeBase64(unsigned char *string, int len) +{ + BIO* pBmem = null; + BIO* pB64 = null; + BUF_MEM* pBptr = null; + + pB64 = BIO_new(BIO_f_base64()); + pBmem = BIO_new(BIO_s_mem()); + pB64 = BIO_push(pB64, pBmem); + BIO_write(pB64, string, len); + BIO_flush(pB64); + BIO_get_mem_ptr(pB64, &pBptr); + + char* pBuff = (char *)malloc(pBptr->length); + SysTryLogReturn(NID_IO, pBuff != NULL, NULL, "The memory is insufficient."); + memcpy(pBuff, pBptr->data, pBptr->length-1); + pBuff[pBptr->length-1] = 0; + + BIO_free_all(pB64); + return pBuff; +} + +bool +_ChannelWebAppStub::SendResponse(int clientId, const ArrayList& args) +{ + unique_ptr pStr(_StringConverter::CopyToCharArrayN(*((String*)args.GetAt(0)))); + + SysLog(NID_IO, "clientId = %d, data = %s", clientId, pStr.get()); + + string response; + string payload(pStr.get()); + + int respSize = _WebSocketMessage::CreateMessage(payload, response); + int ret = send(clientId, response.c_str(), respSize, 0); + SysTryLogReturn(NID_IO, ret >= 1, false, "Failed to send data. Length is less than 1. errno = %d %s", errno, strerror(errno)); + + SysLog(NID_IO, "response = %s, size = %d", response.c_str(), ret); + + _WebSocketMessage message; + ret = message.ParseHeader(reinterpret_cast(const_cast(response.c_str())), respSize); + SysTryLogReturn(NID_IO, ret >= 0, false, "ParseHeader error!"); + + ret = message.ParsePayload(reinterpret_cast(const_cast(response.c_str())), respSize); + SysTryLogReturn(NID_IO, ret >= 0, false, "ParsePayloadr error!"); + + message.ConsoleMessage(); + + return true; +} + +}} + diff --git a/src/io/FIo_ClientChannelImpl.cpp b/src/io/FIo_ClientChannelImpl.cpp new file mode 100644 index 0000000..ea28465 --- /dev/null +++ b/src/io/FIo_ClientChannelImpl.cpp @@ -0,0 +1,202 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ClientChannelImpl.cpp + * @brief This is the implementation file for the _ClientChannelImpl class. + * + */ + +#include + +#include +#include +#include +#include +#include +#include "FIo_ClientChannelImpl.h" +#include "FIo_Channel.h" +#include "FIo_ChannelManager.h" + +using namespace std; + +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +_ClientChannelImpl::_ClientChannelImpl(void) + : __pClientChannel(null) + , __pResponseListener(null) + , __pChannel(null) +{ + +} + +_ClientChannelImpl::~_ClientChannelImpl(void) +{ +} + +result +_ClientChannelImpl::Construct(ClientChannel* pClientChannel, const Tizen::Base::String& channelName) +{ + const String& appId = _AppInfo::GetAppId(); + const String& appExecutableName = _AppInfo::GetAppExecutableName(); + + String channelId(appId); + channelId.Append(L'.'); + channelId.Append(appExecutableName); + + if (!channelName.IsEmpty()) + { + channelId.Append(L'.'); + channelId.Append(channelName); + } + + // Create a channel + _ChannelManager* pManager = _ChannelManager::GetInstance(); + SysTryReturnResult(NID_IO, pManager != null, E_SYSTEM, "Failed to create a channel manager"); + + _Channel* pChannel = pManager->GetChannel(channelId); + SysTryReturnResult(NID_IO, pChannel != null, E_SYSTEM, "Failed to create a channel: [%ls]", channelId.GetPointer()); + + pChannel->SetChannelResponseEventListener(*this); + + __pClientChannel = pClientChannel; + __pChannel = pChannel; + + return E_SUCCESS; +} + +void +_ClientChannelImpl::SetChannelResponseEventListener(IChannelResponseEventListener* pResponseEventListener) +{ + __pResponseListener = pResponseEventListener; +} + +result +_ClientChannelImpl::SendRequest(const String& serverChannelId, const IList* pArgs, RequestId& reqId) +{ + const int APP_ID_LEN = 10; + + String channelId = serverChannelId; + String execName; + + if (serverChannelId.GetLength() <= APP_ID_LEN) + { + execName = _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(serverChannelId); + channelId.Append(L'.'); + channelId.Append(execName); + } + + if (pArgs == null) + { + return __pChannel->SendNullRequest(channelId, reqId); + } + + const ArrayList* pList = dynamic_cast(pArgs); + if (pList == null) + { + unique_ptr pArrayList(new (std::nothrow) ArrayList()); + pArrayList->Construct(*pArgs); + + return __pChannel->SendRequest(channelId, *pArrayList, reqId); + } + + return __pChannel->SendRequest(channelId, *pList, reqId); +} + +void +_ClientChannelImpl::OnChannelResponseReceivedN(RequestId reqId, const String& channelId, IList* pArgs) +{ + if (__pResponseListener && __pClientChannel) + { + if (_AppInfo::IsOspCompat() == false) + { + __pResponseListener->OnChannelResponseReceivedN(reqId, *__pClientChannel, channelId, pArgs); + + } + else + { + String appId; + channelId.SubString(0, 10, appId); + + __pResponseListener->OnChannelResponseReceivedN(reqId, *__pClientChannel, appId, pArgs); + } + } + else + { + pArgs->RemoveAll(true); + delete pArgs; + } +} + +_ClientChannelImpl* +_ClientChannelImpl::GetInstance(ClientChannel* pChannel) +{ + result r = E_SUCCESS; + static _ClientChannelImpl* pImpl = null; + if (pImpl == null) + { + unique_ptr<_ClientChannelImpl> p(new (std::nothrow) _ClientChannelImpl); + SysTryReturn(NID_IO, p != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = p->Construct(pChannel); + SysTryReturn(NID_IO, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] Failed to initialize channel."); + + pImpl = p.release(); + } + + return pImpl; +} + +ClientChannel* +_ClientChannelImpl::GetClientChannel(const Tizen::Base::String& channelName) +{ + _ChannelManager* pManager = _ChannelManager::GetInstance(); + SysTryReturn(NID_IO, pManager != null, null, E_SYSTEM, "[E_SYSTEM] Failed to create a _ChannelManager."); + + ClientChannel* pChannel = pManager->GetClientChannel(channelName); + if (pChannel == null) + { + // unique_ptr cannot be used because Dtor is private + pChannel = new (std::nothrow) ClientChannel; + SysTryReturn(NID_IO, pChannel != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + unique_ptr<_ClientChannelImpl> pImpl(new (std::nothrow) _ClientChannelImpl); + SysTryCatch(NID_IO, pImpl != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + result r = pImpl->Construct(pChannel, channelName); + SysTryCatch(NID_IO, r == E_SUCCESS, , E_SYSTEM, "[E_SYSTEM] Failed to initialize channel."); + + pChannel->__pClientChannelImpl = pImpl.release(); + + pManager->AddClientChannel(channelName, pChannel); + } + + return pChannel; + +CATCH: + delete pChannel; + + return null; +} + +} } // Tizen::Io diff --git a/src/io/FIo_DataControlResultSetEnumerator.cpp b/src/io/FIo_DataControlResultSetEnumerator.cpp new file mode 100644 index 0000000..5421f05 --- /dev/null +++ b/src/io/FIo_DataControlResultSetEnumerator.cpp @@ -0,0 +1,889 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DataControlResultSetEnumerator.cpp + * @brief This is the implementation for the %_DataControlResultSetEnumerator class. + */ + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +_DataControlResultSetEnumerator::_DataControlResultSetEnumerator(void) + : __pFile(null) + , __rowCount(0) + , __columnCount(0) + , __columnTypeOffset(0) + , __columnNameOffset(0) + , __contentOffset(0) + , __currentOffset(0) + , __currentRowCount(0) +{ +} + +_DataControlResultSetEnumerator::~_DataControlResultSetEnumerator(void) +{ + delete static_cast (__pFile); + __rowOffsetList.RemoveAll(true); +} + +result +_DataControlResultSetEnumerator::SetPath(const String filePath) +{ + result r = E_SUCCESS; + SysAssertf(__pFile == null, "Already Set. Calling SetPath() twice or more on a same instance is not allowed for this class."); + unique_ptr pFile(new (std::nothrow) File); + SysTryReturnResult(NID_IO, pFile != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pFile->Construct(filePath, L"r"); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + __pFile = pFile.release(); + + return E_SUCCESS; +} + +result +_DataControlResultSetEnumerator::MoveNext(void) +{ + int totalColumnNameSize = 0; + result r = E_SUCCESS; + int ret = 0; + Integer* pCurrentOffset = null; + + SysTryReturnResult(NID_IO, __pFile != null, E_OUT_OF_RANGE, "The result set does not exist."); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + if (__currentOffset == 0) + { + r = pFile->Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + ret = pFile->Read(&__rowCount, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + ret = pFile->Read(&__columnCount, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + ret = pFile->Read(&totalColumnNameSize, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + __columnTypeOffset = sizeof(int) * 3; + __columnNameOffset = __columnTypeOffset + __columnCount * sizeof(int); + __contentOffset = __columnNameOffset + totalColumnNameSize; + + __currentOffset = __contentOffset; + + r = __rowOffsetList.Add(* new (std::nothrow) Integer(__currentOffset)); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s]Propagated.", GetErrorMessage(r)); + } + else + { + // check if dataoffset list contains next offset + pCurrentOffset = dynamic_cast < Integer* >(__rowOffsetList.GetAt(__currentRowCount + 1)); + + if (pCurrentOffset == null) // Move to next offset + { + int size = 0; + int i = 0; + + // Reading till EOF is not required as we might have already cached the last content offset. So check and return + SysTryReturnResult(NID_IO, __currentRowCount < (__rowCount -1), E_OUT_OF_RANGE, "Reached to the end of the result set"); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __currentOffset); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + for (i = 0; i < __columnCount; i++) + { + r = pFile->Seek(FILESEEKPOSITION_CURRENT, sizeof(int)); // type + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + ret = pFile->Read(&size, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_OUT_OF_RANGE, "Reached to the end of the result set"); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + r = pFile->Seek(FILESEEKPOSITION_CURRENT, size); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + __currentOffset += sizeof(int) * 2 + size; + } + + r = __rowOffsetList.Add(* new (std::nothrow) Integer(__currentOffset)); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s]Propagated.", GetErrorMessage(r)); + } + else + { + __currentOffset = pCurrentOffset->ToInt(); + } + __currentRowCount++; + + } + + return r; +} + +result +_DataControlResultSetEnumerator::MovePrevious(void) +{ + result r = E_SUCCESS; + Integer* pPreviousOffset = null; + + SysTryReturnResult(NID_IO, __pFile != null, E_OUT_OF_RANGE, "The result set does not exist."); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, __currentRowCount > 0, E_OUT_OF_RANGE, + "The Method has reached out of the result set."); + + pPreviousOffset = dynamic_cast < Integer* >(__rowOffsetList.GetAt(__currentRowCount - 1)); + if (!pPreviousOffset) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !IsFailed(r), r, "[%s]Propagated.", GetErrorMessage(r)); + // should not happen + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error occurred.", GetErrorMessage(r)); + } + + __currentRowCount--; + __currentOffset = pPreviousOffset->ToInt(); + + return r; +} + +result +_DataControlResultSetEnumerator::MoveFirst(void) +{ + if (__currentOffset > 0) + { + __currentOffset = __contentOffset; + __currentRowCount = 0; + return E_SUCCESS; + } + + // MoveFirst is called for the first time before MoveNext() or MoveLast() + __currentOffset = 0; + return this->MoveNext(); +} + +result +_DataControlResultSetEnumerator::MoveLast(void) +{ + result r = E_SUCCESS; + Integer* pRowOffset = null; + int offsetCount = 0; + + SysTryReturnResult(NID_IO, __pFile != null, E_OUT_OF_RANGE, "The result set does not exist."); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + if (__currentRowCount == (__rowCount - 1)) + { + return E_SUCCESS; // Already @ last row + } + + offsetCount = __rowOffsetList.GetCount(); + + if (__currentOffset == 0 && offsetCount == 0) + { + r = this->MoveNext(); // make a first move + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to MoveNext."); + } + + // check if the rowOffsetList contains last row offset + + if (offsetCount == __rowCount) + { + pRowOffset = dynamic_cast < Integer* >(__rowOffsetList.GetAt(__rowCount - 1)); // get last item + if (!pRowOffset) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !IsFailed(r), r, "[%s]Propagated.", GetErrorMessage(r)); + // should not happen + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error occurred.", GetErrorMessage(r)); + } + + __currentOffset = pRowOffset->ToInt(); + __currentRowCount = __rowCount - 1; + } + else + { + // @ this time, List will not be empty. + pRowOffset = dynamic_cast < Integer* >(__rowOffsetList.GetAt(offsetCount - 1)); // get the last item in the list + if (pRowOffset) + { + __currentOffset = pRowOffset->ToInt(); + __currentRowCount = offsetCount - 1; + } + + // Move till last row offset. + for (int i = (__currentRowCount + 1); i < __rowCount; i++) + { + r = this->MoveNext(); // move till last row data offset + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to MoveNext."); + + } + } + + return r; +} + +result +_DataControlResultSetEnumerator::Reset(void) +{ + result r = E_SUCCESS; + + //SysTryReturn(NID_IO, __pFile != null, E_INVALID_STATE, E_INVALID_STATE, + // "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + //SysTryReturn(NID_IO, __columnCount > 0, E_INVALID_STATE, E_INVALID_STATE, + // "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + __currentOffset = 0; + __currentRowCount = 0; + __rowOffsetList.RemoveAll(true); + + return r; +} + +result +_DataControlResultSetEnumerator::GetIntAt(int columnIndex, int& value) const +{ + long long int64Value = 0; + result r = E_SUCCESS; + + r = GetInt64At(columnIndex, int64Value); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + value = (int) int64Value; + + return r; +} + +result +_DataControlResultSetEnumerator::GetInt64At(int columnIndex, long long& value) const +{ + int type = -1; + int size = 0; + long long readInt64 = 0; + int i = 0; + result r = E_SUCCESS; + int ret = 0; + + //SysTryReturnResult(NID_IO, __pFile != null, E_INVALID_STATE, + // "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, __columnCount > 0, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "columnIndex is out of range"); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __currentOffset); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + for (i = 0; i < columnIndex; i++) // move to column index + { + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, size); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + } + + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + + SysTryReturnResult(NID_IO, type == DB_COLUMNTYPE_INT64, E_TYPE_MISMATCH, + "Trying to access column of different type."); + + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + ret = pFile->Read(&readInt64, size); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + value = readInt64; + + return r; +} + +result +_DataControlResultSetEnumerator::GetDoubleAt(int columnIndex, double& value) const +{ + int type = -1; + int size = 0; + double readDouble = 0; + int i = 0; + result r = E_SUCCESS; + int ret = 0; + + //SysTryReturnResult(NID_IO, __pFile != null, E_INVALID_STATE, + // "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, __columnCount > 0, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "columnIndex is out of range"); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __currentOffset); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + for (i = 0; i < columnIndex; i++) // move to column index + { + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, size); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + } + + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "columnIndex is out of range"); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + + SysTryReturnResult(NID_IO, type == DB_COLUMNTYPE_DOUBLE, E_TYPE_MISMATCH, + "Trying to access column of different type."); + + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + ret = pFile->Read(&readDouble, size); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + value = readDouble; + + return r; +} + +result +_DataControlResultSetEnumerator::GetStringAt(int columnIndex, String& value) const +{ + int type = -1; + int size = 0; + int i = 0; + String retString; + result r = E_SUCCESS; + int ret = 0; + + //SysTryReturnResult(NID_IO, __pFile != null, E_INVALID_STATE, + // "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, __columnCount > 0, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "columnIndex is out of range"); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __currentOffset); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + for (i = 0; i < columnIndex; i++) // move to column index + { + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, size); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + } + + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + + SysTryReturnResult(NID_IO, type == DB_COLUMNTYPE_TEXT, E_TYPE_MISMATCH, + "Trying to access column of different type."); + + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + unique_ptr pReadBuffer(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pReadBuffer != null, E_OUT_OF_MEMORY, "Failed to allocate memory for the read buffer."); + + memset(pReadBuffer.get(), 0, size + 1); + ret = pFile->Read(pReadBuffer.get(), size); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + value = String(pReadBuffer.get()); + + return E_SUCCESS; +} + +result +_DataControlResultSetEnumerator::GetBlobAt(int columnIndex, ByteBuffer& value) const +{ + int type = -1; + int size = 0; + int i = 0; + String retString; + result r = E_SUCCESS; + int ret = 0; + + //SysTryReturnResult(NID_IO, __pFile != null, E_INVALID_STATE, + // "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, __columnCount > 0, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "columnIndex is out of range"); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __currentOffset); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + for (i = 0; i < columnIndex; i++) // move to column index + { + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, size); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + } + + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + SysTryReturnResult(NID_IO, type == DB_COLUMNTYPE_BLOB, E_TYPE_MISMATCH, + "Trying to access column of different type."); + + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + unique_ptr pReadBuffer(new (std::nothrow) byte[size + 1]); + SysTryReturnResult(NID_IO, pReadBuffer != null, E_OUT_OF_MEMORY, "Failed to allocate memory for the read buffer."); + + memset(pReadBuffer.get(), 0, size + 1); + ret = pFile->Read(pReadBuffer.get(), size); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + r = value.SetArray(pReadBuffer.get(), 0, size); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_DataControlResultSetEnumerator::GetBlobAt(int columnIndex, void* buffer, int bufSize) const +{ + int type = -1; + int size = 0; + int i = 0; + String retString; + result r = E_SUCCESS; + int ret = 0; + + //SysTryReturnResult(NID_IO, __pFile != null, E_INVALID_STATE, + // "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, __columnCount > 0, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "columnIndex is out of range"); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __currentOffset); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + for (i = 0; i < columnIndex; i++) // move to column index + { + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, size); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + } + + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "The columnIndex is out of range."); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + SysTryReturnResult(NID_IO, type == DB_COLUMNTYPE_BLOB, E_TYPE_MISMATCH, + "Trying to access column of different type."); + + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + SysTryReturnResult(NID_IO, size <= bufSize, E_OVERFLOW, "The output buffer is insufficient."); + + unique_ptr pReadBuffer(new (std::nothrow) byte[size + 1]); + SysTryReturnResult(NID_IO, pReadBuffer != null, E_OUT_OF_MEMORY, "Failed to allocate memory for the read buffer."); + + memset(pReadBuffer.get(), 0, size + 1); + ret = pFile->Read(pReadBuffer.get(), size); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + memcpy(buffer, pReadBuffer.get(), size); + + return E_SUCCESS; +} + +result +_DataControlResultSetEnumerator::GetDateTimeAt(int columnIndex, DateTime& value) const +{ + int type = -1; + int size = 0; + char* pReadBuffer = null; + int i = 0; + String retString; + result r = E_SUCCESS; + int ret = 0; + + //SysTryReturnResult(NID_IO, __pFile != null, E_INVALID_STATE, + // "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, __columnCount > 0, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "columnIndex is out of range"); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturnResult(NID_IO, pFile != null, E_INVALID_STATE, + "This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __currentOffset); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + + for (i = 0; i < columnIndex; i++) // move to column index + { + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "columnIndex is out of range"); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + ret = pFile->Read(&size, sizeof(int)); + SysTryReturnResult(NID_IO, ret, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, size); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "Failed to seek."); + } + + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "columnIndex is out of range"); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + SysTryReturnResult(NID_IO, type == DB_COLUMNTYPE_TEXT, E_TYPE_MISMATCH, + "Trying to access column of different type."); + + ret = pFile->Read(&size, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "columnIndex is out of range"); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + + pReadBuffer = (char*) malloc(size + 1); + SysTryReturn(NID_IO, pReadBuffer != NULL, E_SYSTEM, E_SYSTEM, "[E_OUT_OF_MEMORY] system error occurred."); + memset(pReadBuffer, 0, size + 1); + + ret = pFile->Read(pReadBuffer, size); + if (ret == 0) + { + r = GetLastResult(); + free(pReadBuffer); + SysTryReturnResult(NID_IO, !(r == E_END_OF_FILE), E_INVALID_ARG, "columnIndex is out of range"); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + + r = DateTime::Parse(pReadBuffer, value); + free(pReadBuffer); + + return r; +} + +int +_DataControlResultSetEnumerator::GetColumnCount(void) const +{ + //SysTryReturn(NID_IO, __pFile != null, -1, E_INVALID_STATE, + // "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, __columnCount > 0, -1, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SetLastResult(E_SUCCESS); + return __columnCount; +} + +DbColumnType +_DataControlResultSetEnumerator::GetColumnType(int columnIndex) const +{ + DbColumnType columnType = DB_COLUMNTYPE_UNDEFINED; + int type = -1; + result r = E_SUCCESS; + int ret = 0; + + //SysTryReturn(NID_IO, __pFile != null, columnType, E_INVALID_STATE, + // "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, __columnCount > 0, columnType, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, columnType, E_INVALID_ARG, + "[E_INVALID_ARG] columnIndex is out of range"); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturn(NID_IO, pFile != null, columnType, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __columnTypeOffset + columnIndex * sizeof(int)); + SysTryReturn(NID_IO, !IsFailed(r), columnType, E_SYSTEM, "Failed to seek."); + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturn(NID_IO, !(r == E_END_OF_FILE), DB_COLUMNTYPE_UNDEFINED, E_INVALID_ARG, + "[E_INVALID_ARG] columnIndex is out of range"); + SysTryReturn(NID_IO, false, DB_COLUMNTYPE_UNDEFINED, E_SYSTEM, "[%s] system error, errno: %d", GetErrorMessage(r), errno); + } + + switch (type) + { + case 1: // int64 + columnType = DB_COLUMNTYPE_INT64; + break; + + case 2: // double + columnType = DB_COLUMNTYPE_DOUBLE; + break; + + case 3: // text + columnType = DB_COLUMNTYPE_TEXT; + break; + + case 4: // blob + columnType = DB_COLUMNTYPE_BLOB; + break; + + default: + SetLastResult(E_INVALID_STATE); + break; + } + + SetLastResult(E_SUCCESS); + return columnType; +} + +String +_DataControlResultSetEnumerator::GetColumnName(int columnIndex) const +{ + String columnName; + int i = 0; + result r = E_SUCCESS; + + //SysTryReturn(NID_IO, __pFile != null, columnName, E_INVALID_STATE, + // "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, __columnCount > 0, columnName, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, columnName, E_INVALID_ARG, + "[E_INVALID_ARG] columnIndex is out of range"); + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturn(NID_IO, pFile != null, columnName, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __columnNameOffset); + SysTryReturn(NID_IO, !IsFailed(r), columnName, E_SYSTEM, "Failed to seek."); + for (i = 0; i < columnIndex + 1; i++) + { + r = pFile->Read(columnName); + if (IsFailed(r)) + { + SysTryReturn(NID_IO, !(r == E_END_OF_FILE), L"", E_INVALID_ARG, "[E_INVALID_ARG] columnIndex is out of range"); + SysTryReturn(NID_IO, false, L"", E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + } + columnName.SetLength(columnName.GetLength() - 1); + + SetLastResult(E_SUCCESS); + return columnName; +} + +int +_DataControlResultSetEnumerator::GetColumnSize(int columnIndex) const +{ + //SysTryReturn(NID_IO, __pFile != null, -1, E_INVALID_STATE, + // "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, __columnCount > 0, -1, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] columnIndex is out of range"); + + int type = -1; + int size = 0; + int i = 0; + int ret = 0; + result r = E_SUCCESS; + + _FileImpl* pFile = _FileImpl::GetInstance(*(static_cast< File* >(__pFile))); + + SysTryReturn(NID_IO, pFile != null, -1, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, __currentOffset); + SysTryReturn(NID_IO, !IsFailed(r), -1, E_SYSTEM, "Failed to seek."); + + for (i = 0; i < columnIndex; i++) // move to column index + { + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturn(NID_IO, !(r == E_END_OF_FILE), -1, E_INVALID_ARG, "[E_INVALID_ARG] columnIndex is out of range"); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + ret = pFile->Read(&size, sizeof(int)); + SysTryReturn(NID_IO, ret, -1, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, size); + SysTryReturn(NID_IO, !IsFailed(r), -1, E_SYSTEM, "Failed to seek."); + } + + ret = pFile->Read(&type, sizeof(int)); + if (ret == 0) + { + r = GetLastResult(); + SysTryReturn(NID_IO, !(r == E_END_OF_FILE), -1, E_INVALID_ARG, "[E_INVALID_ARG] columnIndex is out of range"); + SysTryReturn(NID_IO, false, E_SYSTEM, E_SYSTEM, "[%s] system error", GetErrorMessage(r)); + } + ret = pFile->Read(&size, sizeof(int)); + SysTryReturn(NID_IO, ret, -1, E_SYSTEM, "Failed to read data from the result set of the data control provider."); + + SetLastResult(E_SUCCESS); + return size; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DataControlResultSetImpl.cpp b/src/io/FIo_DataControlResultSetImpl.cpp new file mode 100644 index 0000000..33174ef --- /dev/null +++ b/src/io/FIo_DataControlResultSetImpl.cpp @@ -0,0 +1,409 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DataControlResultSetImpl.cpp + * @brief This is the implementation for the %_DataControlResultSetImpl class. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::App; + +const char* _DATACONTROL_RESULTSET_DIR = "/tmp/osp/DataControlResultSet/\0"; + +namespace Tizen { namespace Io +{ + +_DataControlResultSetImpl::_DataControlResultSetImpl(RequestId reqId) + : __constructed(true) + , __pageNo(1) + , __countPerPage(0) + , __result(E_SUCCESS) + , __tmpPath("") + , __reqId(reqId) +{ +} + +_DataControlResultSetImpl::~_DataControlResultSetImpl(void) +{ + __constructed = false; +} + +// header +// [sizeof(int)] row count +// [sizeof(int)] column count +// [sieeof(int)] total size of column names +// +// column info. +// [sizeof(int)] column type x N +// [ variant ] column name x N +// +// column elements +// [sizeof(int)] type +// [sizeof(int)] size +// [ varient ] content +result +_DataControlResultSetImpl::FillWith(IDbEnumerator* pDbEnum) +{ + String tempFilePath(_DATACONTROL_RESULTSET_DIR); + String columnName; + String* pAppId = null; + String* pRequestType = null; + String* pReqId = null; + String* pNo = null; + String* pCount = null; + String* pColumnCount = null; + result r = E_SUCCESS; + _DataControlRequestType requestType = _DATACONTROL_REQUEST_TYPE_UNDEFINED; + int columnCount = 0; + int rowCount = 0; + int totalSizeOfColumnTypes = 0; + int totalSizeOfColumnNames = 0; + int cursorOffset = 0; + int pageNo = 0; + int countPerPage = 0; + int type = 0; + int i = 0; + int pageNoIndex = 0; + + SysAssertf(__constructed == true, "Not yet constructed. Construct() should be called before use.\n\n"); + + _AppControlManager* pAppMgr = _AppControlManager::GetInstance(); + SysTryReturnResult(NID_APP, pAppMgr, E_SYSTEM, "Failed to get instance."); + + _ResultInfo* pResultInfo = pAppMgr->__resultManager.FindItem(static_cast< int >(__reqId)); + SysTryReturnResult(NID_APP, pResultInfo, E_OBJ_NOT_FOUND, + "The data control request specified with the reqId (%ld) did not exist.", __reqId); + + const _AppArg& arg = pResultInfo->arg; + + std::unique_ptr pList(arg.GetArgListN(0)); + SysTryReturnResult(NID_APP, pList, E_SYSTEM, "Invalid result object."); + + // key-based request + pAppId = dynamic_cast< String* >(pList->GetAt(0)); // key[0] + SysTryReturnResult(NID_APP, pAppId, E_SYSTEM, "Invalid request."); + + pRequestType = dynamic_cast< String* >(pList->GetAt(1)); // key[1] + SysTryReturnResult(NID_APP, pRequestType, E_SYSTEM, "Invalid request."); + Integer::Parse(*pRequestType, type); + requestType = static_cast< _DataControlRequestType >(type); + SysTryReturnResult(NID_APP, requestType == _DATACONTROL_REQUEST_TYPE_SQL_QUERY, E_INVALID_ARG, + "The reqId should be for the data control query request."); + + pReqId = dynamic_cast< String* >(pList->GetAt(2)); // key[2] + SysTryReturnResult(NID_APP, pReqId, E_SYSTEM, "Invalid request."); + + // list-based request + pColumnCount = dynamic_cast< String* >(pList->GetAt(5)); + SysTryReturnResult(NID_APP, pColumnCount, E_SYSTEM, "Invalid result object."); + Integer::Parse(*pColumnCount, columnCount); + + pageNoIndex = 5 + columnCount + 2 + 1; + + pNo = dynamic_cast< String* >(pList->GetAt(pageNoIndex)); + SysTryReturnResult(NID_APP, pNo, E_SYSTEM, "Invalid result object."); + Integer::Parse(*pNo, pageNo); + + pCount = dynamic_cast< String* >(pList->GetAt(pageNoIndex + 1)); + SysTryReturnResult(NID_APP, pCount, E_SYSTEM, "Invalid result object."); + Integer::Parse(*pCount, countPerPage); + + this->SetCapacity(pageNo, countPerPage); + tempFilePath.Append(*pAppId); + tempFilePath.Append(*pReqId); + __tmpPath = tempFilePath; + + // initialize + r = pDbEnum->Reset(); + SysTryReturnResult(NID_IO, r == E_SUCCESS, E_DATABASE, + "The database engine has failed to execute reset."); + + cursorOffset = (__pageNo - 1) * __countPerPage; + for (i = 0; i < cursorOffset; i++) // move cursor to the specific page to be requested + { + r = pDbEnum->MoveNext(); + if (r == E_OUT_OF_RANGE) // the previous pages do not exist + { + __result = E_OUT_OF_RANGE; + SysTryReturnResult(NID_APP, false, E_SUCCESS, "Out of range error."); + } + SysTryReturnResult(NID_IO, !IsFailed(r), E_DATABASE, + "The database engine has failed to enumerator result set."); + } + + // XXX: must call MoveNext() before calling GetColumnCount() + r = pDbEnum->MoveNext(); + if (r == E_OUT_OF_RANGE) // the specific page is empty + { + __result = E_OUT_OF_RANGE; + SysTryReturnResult(NID_APP, false, E_SUCCESS, "Out of range error."); + } + SysTryReturnResult(NID_IO, !IsFailed(r), E_DATABASE, + "The database engine has failed to enumerate the result set."); + + // if has the result set + std::unique_ptr pFile(new (std::nothrow) File()); + + SysTryReturnResult(NID_IO, pFile != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pFile->Construct(__tmpPath, "w+", true); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to create temp file (%ls) for result set.", + GetErrorMessage(r), __tmpPath.GetPointer()); + + columnCount = pDbEnum->GetColumnCount(); + SysLog(NID_IO, "column count is %d.\n", columnCount); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&columnCount, sizeof(int)); // pack column count + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + // pack column type + for (i = 0; i < columnCount; i++) + { + int type = -1; + DbColumnType columnType = pDbEnum->GetColumnType(i); + switch (columnType) + { + case DB_COLUMNTYPE_INT: + { + type = 1; // int64 type + break; + } + + case DB_COLUMNTYPE_DOUBLE: + { + type = 2; // double type + break; + } + + case DB_COLUMNTYPE_TEXT: + { + type = 3; // text type + break; + } + + case DB_COLUMNTYPE_BLOB: + { + type = 4; // blob type + break; + } + + default: + SysLog(NID_IO, "type: UNDEFINDE (%d)", type); + break; + } + r = pFile->Write(&type, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + totalSizeOfColumnTypes += sizeof(int); + } + //totalSizeOfColumnTypes = columnCount * sizeof(int); + + totalSizeOfColumnNames = 0; + for (i = 0; i < columnCount; i++) + { + char* pColumnName = null; + int byte = 0; + + columnName = pDbEnum->GetColumnName(i); + columnName.Append('\n'); + r = pFile->Write(columnName); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + pColumnName = _StringConverter::CopyToCharArrayN(columnName); + byte = strlen(pColumnName); + totalSizeOfColumnNames += byte; + + SysLog(NID_IO, "[%d] column name: %s", i, pColumnName); + delete[] pColumnName; + } + r = pFile->Seek(FILESEEKPOSITION_BEGIN, sizeof(int) * 2); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&totalSizeOfColumnNames, sizeof(int)); // pack + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Seek(FILESEEKPOSITION_CURRENT, totalSizeOfColumnTypes + totalSizeOfColumnNames); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + do + { + for (i = 0; i < columnCount; i++) + { + DbColumnType columnType = pDbEnum->GetColumnType(i); + switch (columnType) + { + case DB_COLUMNTYPE_INT: + { + long long int64Value = 0; + int type = 1; // int64 + int size = 0; + + r = pDbEnum->GetInt64At(i, int64Value); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + size = sizeof(long long); + + r = pFile->Write(&type, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&size, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&int64Value, sizeof(long long)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + break; + } + + case DB_COLUMNTYPE_DOUBLE: + { + double doubleValue = 0; + int type = 2; // double + int size = 0; + + r = pDbEnum->GetDoubleAt(i, doubleValue); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + size = sizeof(double); + + r = pFile->Write(&type, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&size, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&doubleValue, sizeof(double)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + break; + } + + case DB_COLUMNTYPE_TEXT: + { + String textValue; + int type = 3; // text + int size = 0; + + r = pDbEnum->GetStringAt(i, textValue); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + std::unique_ptr pContent(_StringConverter::CopyToCharArrayN(textValue)); + size = strlen(pContent.get()); + + r = pFile->Write(&type, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&size, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(pContent.get(), size); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + break; + } + + case DB_COLUMNTYPE_BLOB: // XXX: need test !! + { + ByteBuffer blobValue; + int type = 4; // blob + int size = 0; + + size = pDbEnum->GetColumnSize(i); + r = blobValue.Construct(size); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pDbEnum->GetBlobAt(i, blobValue); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&type, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&size, sizeof(int)); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(blobValue); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + break; + } + + default: + SysTryReturnResult(NID_IO, false, E_DATABASE, + "The column type is invalid."); + break; + } + } + rowCount++; + } + while (pDbEnum->MoveNext() == E_SUCCESS && rowCount < __countPerPage); + + SysLog(NID_IO, "row count is %d.\n", rowCount); + r = pFile->Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + r = pFile->Write(&rowCount, sizeof(int)); // pack row count + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] System error was occurred.", GetErrorMessage(r)); + + return r; +} + +result +_DataControlResultSetImpl::SetCapacity(int pageNo, int countPerPage) +{ + result r = E_SUCCESS; + + SysAssertf(__constructed == true, "Not yet constructed. Construct() should be called before use.\n\n"); + + __pageNo = pageNo; + __countPerPage = countPerPage; + + return r; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DataRouter.cpp b/src/io/FIo_DataRouter.cpp new file mode 100644 index 0000000..1d309ec --- /dev/null +++ b/src/io/FIo_DataRouter.cpp @@ -0,0 +1,195 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DataRouter.cpp + * @brief This is the implementation file for %_DataRouter class. + */ + +#include +#include + +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +const char* _VCONF_KEY_DATA_ROUTER_READY_EVENT = "memory/data_router/osp_serial_open"; + +static serial_h gSerialHandle = 0; +static _DataRouter* gp_DataRouter = null; + +void +SerialStateChangedCallback(serial_error_e result, serial_state_e state, void* userData) +{ + + if (gp_DataRouter != null) + { + if (state == SERIAL_STATE_OPENED) + { + gp_DataRouter->StateChanged(_DATA_ROUTER_STATE_OPENED); + } + else + { + gp_DataRouter->StateChanged(_DATA_ROUTER_STATE_CLOSED); + } + } +} + +bool +SerialDataReceivedCallback(const char* data, int length, void* userData) +{ + + if (gp_DataRouter != null) + { + gp_DataRouter->DataReceived(data, length); + } + + return true; +} + +void +SerialStateReadyCallback(keynode_t* node, void* userData) +{ + result r = E_SUCCESS; + int ret = 0; + + if (strcmp(_VCONF_KEY_DATA_ROUTER_READY_EVENT, vconf_keynode_get_name(node)) == 0) + { + int dataRouterStatus = 0; + ret = vconf_get_int(_VCONF_KEY_DATA_ROUTER_READY_EVENT, &dataRouterStatus); + SysTryCatch(NID_IO, ret == 0, r= E_SYSTEM, r, "[%s] Failed to get vconf status"); + + if(dataRouterStatus == 1) + { + ret = serial_create(&gSerialHandle); + SysTryCatch(NID_IO, ret == SERIAL_ERROR_NONE, r = E_SYSTEM, r, "[%s] Failed to initialize data router module. Error:%d", ret); + + ret = serial_set_state_changed_cb(gSerialHandle, SerialStateChangedCallback, null); + SysTryCatch(NID_IO, ret == SERIAL_ERROR_NONE, r = E_SYSTEM, r, "[%s] Failed to set callback function for state change", GetErrorMessage(r)); + + ret = serial_set_data_received_cb(gSerialHandle, SerialDataReceivedCallback, null); + SysTryCatch(NID_IO, ret == SERIAL_ERROR_NONE, r = E_SYSTEM, r, "[%s] Failed to set callback function for data receive", GetErrorMessage(r)); + + ret = serial_open(gSerialHandle); + SysTryCatch(NID_IO, ret == SERIAL_ERROR_NONE, r = E_SYSTEM, r, "[%s] Failed to set callback function for data receive", GetErrorMessage(r)); + } + } + +CATCH: + if (r != E_SUCCESS) + { + ret = serial_close(gSerialHandle); + ret = serial_unset_state_changed_cb(gSerialHandle); + ret = serial_unset_data_received_cb(gSerialHandle); + ret = serial_destroy(gSerialHandle); + } +} + +_DataRouter::_DataRouter(void) + : __pDataRouterEventListener(null) + , __initialized(false) +{ +} +_DataRouter::~_DataRouter(void) +{ + int ret = 0; + ret = serial_close(gSerialHandle); + if (ret != SERIAL_ERROR_NONE) + { + SysLogException(NID_IO, E_SYSTEM, "Failed to close handle of serial. Error:%d", ret); + } + + ret = serial_destroy(gSerialHandle); + if (ret != SERIAL_ERROR_NONE) + { + SysLogException(NID_IO, E_SYSTEM, "Failed to release handle of serial. Error:%d", ret); + } +} + +result +_DataRouter::Construct(_IDataRouterEventListener& listener) +{ + result r = E_SUCCESS; + + int ret = 0; + SysAssertf(__initialized == false, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + __pDataRouterEventListener = &listener; + __initialized = true; + + ret = vconf_notify_key_changed(_VCONF_KEY_DATA_ROUTER_READY_EVENT, SerialStateReadyCallback, null); + SysTryCatch(NID_SYS, ret == 0, r = E_SYSTEM, r, "Failed to register vconf event for data router ready"); + +CATCH: + return r; +} + +result +_DataRouter::Write(const char* data, int length) +{ + int ret = 0; + ret = serial_write(gSerialHandle, data, length); + + SysTryReturnResult(NID_IO, ret >= 0, E_SYSTEM, "Write is failed %d", ret); + return E_SUCCESS; +} + +void +_DataRouter::DataReceived(const char* data, int length) +{ + if (__pDataRouterEventListener != null) + { + __pDataRouterEventListener->OnDataRouterDataReceivedN(data, length); + } +} + +void +_DataRouter::StateChanged(_DataRouterState state) +{ + if (__pDataRouterEventListener != null) + { + __pDataRouterEventListener->OnDataRouterStateChanged(state); + } +} +_DataRouter* +_DataRouter::GetInstance(void) +{ + if (gp_DataRouter == null) + { + gp_DataRouter = new (std::nothrow) _DataRouter(); + SysTryReturn(NID_IO, gp_DataRouter != null, null, E_OUT_OF_MEMORY, "The memory is insufficient."); + return gp_DataRouter; + } + return null; +} + +void +_DataRouter::ReleaseInstance(void) +{ + if (gp_DataRouter != null) + { + delete gp_DataRouter; + gp_DataRouter = null; + } +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DatabaseImpl.cpp b/src/io/FIo_DatabaseImpl.cpp new file mode 100644 index 0000000..eda5577 --- /dev/null +++ b/src/io/FIo_DatabaseImpl.cpp @@ -0,0 +1,1716 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DatabaseImpl.cpp + * @brief This is the implementation file for _DatabaseImpl class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::App; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Utility; +using namespace Tizen::System; + +namespace Tizen { namespace Io +{ + +// maximum argument count that can be passed to register user defined functions +const int MAX_FUNCTION_ARGUMENT_COUNT = 127; +const int MAX_UTF8_BYTES = 255; // maximum length of UTF8 bytes +const int MAX_MUTEX_NAME_LENGTH = 32; // maximum length of mutex name +const int MAX_DATABASE_AES_KEY_LENGTH = 16; //default key size for AES 128 +const int MAX_DATABASE_SQL_LENGTH = 4096; //buffer length required to make sql query +const int MAX_SQLCIPHER_SCHEMA_PREFIX_SIZE = 13;//size of sqlCipher_ schema prefix name. + +static const size_t _MAX_DB_OPENMODE_LENGTH = 2; +static const char _DATABASE_LIBRARY_PATH[] = "/usr/lib/libsqlite3.so.0"; +static const char _DATABASE_ENCRYPTION_SYMBOL[] = "sqlite3_key"; + +_DatabaseImpl::_DatabaseImpl(void) + : __pDatabase(null) + , __transactionGoingOn(false) +{ +} + +_DatabaseImpl::~_DatabaseImpl(void) +{ + result r = E_SUCCESS; + sqlite3_stmt* pSqlStmt = null; + + if (__pDatabase) + { + pSqlStmt = sqlite3_next_stmt((sqlite3*) __pDatabase, 0); + while (pSqlStmt != null) + { + sqlite3_finalize(pSqlStmt); + pSqlStmt = sqlite3_next_stmt((sqlite3*) __pDatabase, 0); + } + + int ret = sqlite3_close((sqlite3*) __pDatabase); + if (ret != SQLITE_OK) + { + r = __ConvertNativeSqliteErrorToResult(ret); + SysLog(NID_IO, "[%s] ERROR Message: [%s], Failed to close database.", GetErrorMessage(r), + sqlite3_errmsg((sqlite3*) __pDatabase)); + } + else + { + __pDatabase = null; + __transactionGoingOn = false; + } + } + + // release user context info + __userFunctionContextList.RemoveAll(true); + __userCollationContextList.RemoveAll(true); + +} + +bool +_DatabaseImpl::IsDirectory(const String& databasePath) +{ + FileAttributes attr; + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(databasePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", databasePath.GetPointer()); + + r = _FileImpl::GetAttributes(databasePath, attr); + if (IsFailed(r)) + { + SetLastResult(r); + return false; + } + + SetLastResult(E_SUCCESS); + return attr.IsDirectory(); +} + +bool +_DatabaseImpl::VerifyDatabaseOpenMode(const char* pOpenMode, long& legacyMode) +{ + if (pOpenMode == null) + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode is null."); + return false; + } + + if (strlen(pOpenMode) > _MAX_DB_OPENMODE_LENGTH) + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + + if (pOpenMode[0] == 'r') + { + if (pOpenMode[1] == '\0') + { + legacyMode = DB_OPEN_READ_ONLY; + } + else if (pOpenMode[1] == '+') + { + if (pOpenMode[2] == '\0') + { + legacyMode = DB_OPEN_READ_WRITE; + } + } + } + else if (pOpenMode[0] == 'a' && pOpenMode[1] == '+' && pOpenMode[2] == '\0') + { + legacyMode = (DB_OPEN_CREATE | DB_OPEN_READ_WRITE); + } + else + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + + return true; +} + +result +_DatabaseImpl::Construct(const String& dbPath, bool createIfNotExist) +{ + long openMode = DB_OPEN_READ_WRITE; + + if (!_FileImpl::IsFileExist(dbPath)) + { + SysTryReturn(NID_IO, createIfNotExist == true, E_FILE_NOT_FOUND, E_FILE_NOT_FOUND, + "[E_FILE_NOT_FOUND] Database file does not exist. Create it first."); + openMode = DB_OPEN_READ_WRITE | DB_OPEN_CREATE; + } + + return Construct(dbPath, openMode, null); +} + +result +_DatabaseImpl::Construct(const String& dbPath, long openMode, const ByteBuffer* pSecretKey) +{ + SysAssertf(__pDatabase == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(dbPath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", dbPath.GetPointer()); + SysTryReturnResult(NID_IO, !(pSecretKey && pSecretKey->GetRemaining() <= 0), E_INVALID_ARG, + "The specified secretKey is invalid."); + + result r = E_SUCCESS; + int ret = 0; + int openFlags = 0; + sqlite3* pDb = null; + bool isFilePathExist = false; + bool isParentDirPathExist = false; + int lastIndex = -1; + String parentDirPath; + + switch (openMode) + { + case (DB_OPEN_READ_WRITE): + openFlags = SQLITE_OPEN_READWRITE; + break; + + case (DB_OPEN_READ_ONLY): + openFlags = SQLITE_OPEN_READONLY; + break; + + case (DB_OPEN_READ_WRITE | DB_OPEN_CREATE): + openFlags = (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); + break; + + default: + SysLog(NID_IO, "[E_INVALID_ARG] The specified open mode flags are invalid."); + return E_INVALID_ARG; + } + + // extract directory path from a given Db file path + // Find index of last occurrence of character '/' in dbPath + r = dbPath.LastIndexOf(L'/', dbPath.GetLength() - 1, lastIndex); + SysTryReturnResult(NID_IO, !IsFailed(r), + E_INVALID_ARG, "Missing directory path. SHOULD not happen."); + + // extract directory path from dbPath starting from index 0 to lastIndex. + r = dbPath.SubString(0, lastIndex, parentDirPath); + SysTryReturnResult(NID_IO, !IsFailed(r), + E_INVALID_ARG, "Missing directory path. SHOULD not happen."); + + // TODO: Test sqlite3_open_v3() without parent directory. + //check existence of parent directory + isParentDirPathExist = _FileImpl::IsFileExist(String(parentDirPath)); + SysTryReturnResult(NID_IO, isParentDirPathExist == true, E_INVALID_ARG, + "Parent Directory does not exist."); + + unique_ptr pDbPath(_StringConverter::CopyToCharArrayN(dbPath)); + r = GetLastResult(); + SysTryCatch(NID_IO, pDbPath, , r, "[%s] pDbPath is null.", GetErrorMessage(r)); + + // check existence of file + isFilePathExist = _FileImpl::IsFileExist(dbPath); + if (isFilePathExist == true) + { + if (openMode == (DB_OPEN_READ_WRITE | DB_OPEN_CREATE)) + { + SysLog(NID_IO, "[E_FILE_ALREADY_EXIST] File already exists."); + r = E_FILE_ALREADY_EXIST; + goto CATCH; + } + + //check if it is a directory + if (IsDirectory(dbPath)) + { + SysLog(NID_IO, "[E_DATABASE] Given path is not a File."); + r = E_DATABASE; + goto CATCH; + } + +#if 0 + _DatabaseMode dbMode = DATABASE_MODE_NONE; + dbMode = _SecureIoUtil::GetDatabaseMode(pDbPath.get()); + SysTryCatch(NID_IO, dbMode != DATABASE_MODE_ERROR, r = E_IO, E_IO, "[E_IO] GetDatabaseMode function failed."); + + if (pSecretKey && _SecureIoUtil::IsNormalDatabase(dbMode)) + { + SysTryCatch(NID_IO, false, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Trying to open a normal database in secure mode."); + } + else if (!pSecretKey && _SecureIoUtil::IsSecureDatabase(dbMode)) + { + SysTryCatch(NID_IO, false, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Trying to open a secure database in normal mode."); + } + else + { + //Do Nothing + } +#endif + } + else + { + if (openMode == DB_OPEN_READ_WRITE || openMode == DB_OPEN_READ_ONLY) + { + SysLog(NID_IO, "[E_FILE_NOT_FOUND] File not found when opened in DB_OPEN_READ_WRITE/DB_OPEN_READ_ONLY mode."); + r = E_FILE_NOT_FOUND; + goto CATCH; + } + } + + // open/create the database + ret = sqlite3_open_v2(pDbPath.get(), &pDb, openFlags, null); + if (ret != SQLITE_OK) + { + r = __ConvertNativeSqliteErrorToResult(ret); + SysLog(NID_IO, "[%s] sqlite3_open_v2() failed (%d, %s).", GetErrorMessage(r), ret, sqlite3_errmsg(pDb)); + goto CATCH; + } + + if (pSecretKey) + { + unique_ptr pDbKey(_SecureIoUtil::GenerateDatabaseKeyN(pSecretKey)); + SysTryReturnResult(NID_IO, pDbKey != null, E_IO, "GenerateDatabaseKeyN returned null."); + +#if 0 + bool secure = false; + r = SystemInfo::GetValue(L"http://tizen.org/feature/database.encryption", secure); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "The method cannot proceed due to a severe system error."); + SysTryReturnResult(NID_IO, secure == true, E_UNSUPPORTED_OPERATION, "This operation is not supported."); + + ret = sqlite3_key(pDb, pDbKey.get(), MAX_DATABASE_AES_KEY_LENGTH * 2); +#else + int (* sqlite3_key_func)(sqlite3*, const void*, int) = null; + void* handle = dlopen(_DATABASE_LIBRARY_PATH, RTLD_LAZY | RTLD_LOCAL); + SysTryReturnResult(NID_IO, handle != null, E_SYSTEM, + "Failed to dlopen database library file (%s)", dlerror()); + + sqlite3_key_func = reinterpret_cast< int (*)(sqlite3*, const void*, int) >(dlsym(handle, _DATABASE_ENCRYPTION_SYMBOL)); + if (sqlite3_key_func == null) + { + SysLog(NID_IO, "This operation is not supported. (%s)", dlerror()); + dlclose(handle); + r = E_UNSUPPORTED_OPERATION; + goto CATCH; + } + + ret = sqlite3_key_func(pDb, pDbKey.get(), MAX_DATABASE_AES_KEY_LENGTH * 2); + dlclose(handle); +#endif + if (ret != SQLITE_OK) + { + r = __ConvertNativeSqliteErrorToResult(ret); + SysLog(NID_IO, "[%s] sqlite3_key() failed (%d, %s).", GetErrorMessage(r), ret, sqlite3_errmsg(pDb)); + goto CATCH; + } + } + + __pDatabase = pDb; + __dbName = dbPath; + + return E_SUCCESS; + +CATCH: + return r; +} + +result +_DatabaseImpl::Construct(const String& dbPath, const char* pOpenMode, const ByteBuffer* pSecretKey) +{ + SysAssertf(__pDatabase == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(dbPath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, "The specified dbPath (%ls) is invalid.", dbPath.GetPointer()); + SysTryReturnResult(NID_IO, !(pSecretKey && pSecretKey->GetRemaining() <= 0), E_INVALID_ARG, + "The specified secretKey is invalid."); + + long legacyMode = 0; + bool isValidOpenMode = _DatabaseImpl::VerifyDatabaseOpenMode(pOpenMode, legacyMode); + SysTryReturnResult(NID_IO, isValidOpenMode == true, E_INVALID_ARG, "The specified openMode is invalid. (%s)", pOpenMode); + + int ret = 0; + int openFlags = 0; + sqlite3* pDb = null; + bool isFilePathExist = false; + bool isParentDirPathExist = false; + int lastIndex = -1; + String parentDirPath; + + switch (legacyMode) + { + case DB_OPEN_READ_WRITE: + openFlags = SQLITE_OPEN_READWRITE; + break; + case DB_OPEN_READ_ONLY: + openFlags = SQLITE_OPEN_READONLY; + break; + case (DB_OPEN_READ_WRITE | DB_OPEN_CREATE): + openFlags = (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); + break; + default: + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return E_INVALID_ARG; + } + + // extract directory path from a given Db file path + // Find index of last occurrence of character '/' in dbPath + result r = dbPath.LastIndexOf(L'/', dbPath.GetLength() - 1, lastIndex); + SysTryReturnResult(NID_IO, !IsFailed(r), E_INVALID_ARG, + "Missing directory path. SHOULD not happen."); + + // extract directory path from dbPath starting from index 0 to lastIndex. + r = dbPath.SubString(0, lastIndex, parentDirPath); + SysTryReturnResult(NID_IO, !IsFailed(r), E_INVALID_ARG, + "Missing directory path. SHOULD not happen."); + + // TODO: Test sqlite3_open_v3() without parent directory. + //check existence of parent directory + isParentDirPathExist = _FileImpl::IsFileExist(String(parentDirPath)); + SysTryReturnResult(NID_IO, isParentDirPathExist == true, E_INVALID_ARG, + "Parent Directory dose not exist."); + + unique_ptr pDbPath(_StringConverter::CopyToCharArrayN(dbPath)); + SysTryReturn(NID_IO, pDbPath, GetLastResult(), GetLastResult(), "[%s] pDbPath is null.", GetErrorMessage(GetLastResult())); + + //check existence of file + isFilePathExist = _FileImpl::IsFileExist(dbPath); + if (isFilePathExist == true) + { + //check if it is a directory + SysTryReturnResult(NID_IO, !IsDirectory(dbPath), E_INVALID_ARG, "Given path is not a File."); + +#if 0 + _DatabaseMode dbMode = DATABASE_MODE_NONE; + dbMode = _SecureIoUtil::GetDatabaseMode(pDbPath.get()); + SysTryReturnResult(NID_IO, dbMode != DATABASE_MODE_ERROR, E_INVALID_FORMAT, + "GetDatabaseMode function failed."); + + if (pSecretKey && _SecureIoUtil::IsNormalDatabase(dbMode)) + { + SysTryReturnResult(NID_IO, false, E_INVALID_ARG, + "Trying to open a normal database in secure mode."); + } + else if (!pSecretKey && _SecureIoUtil::IsSecureDatabase(dbMode)) + { + SysTryReturnResult(NID_IO, false, E_INVALID_ARG, + "Trying to open a secure database in normal mode."); + } + else + { + //Do Nothing + } +#endif + } + else + { + if (legacyMode == DB_OPEN_READ_WRITE || legacyMode == DB_OPEN_READ_ONLY) + { + SysLog(NID_IO, "[E_FILE_NOT_FOUND] File not found."); + r = E_FILE_NOT_FOUND; + goto CATCH; + } + } + + // open/create the database + ret = sqlite3_open_v2(pDbPath.get(), &pDb, openFlags, null); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_INVALID_ARG: + case E_OBJECT_LOCKED: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to open database file (%s). (%d, %s).", GetErrorMessage(r), pDbPath.get(), + ret, sqlite3_errmsg(static_cast< sqlite3* >(pDb))); + goto CATCH; + } + + if (pSecretKey) + { + unique_ptr pDbKey(_SecureIoUtil::GenerateDatabaseKeyN(pSecretKey)); + SysTryReturnResult(NID_IO, pDbKey != null, E_IO, "GenerateDatabaseKeyN returned null."); + +#if 0 + bool secure = false; + r = SystemInfo::GetValue(L"http://tizen.org/feature/database.encryption", secure); + SysTryReturnResult(NID_IO, !IsFailed(r), E_SYSTEM, "The method cannot proceed due to a severe system error."); + SysTryReturnResult(NID_IO, secure == true, E_UNSUPPORTED_OPERATION, "This operation is not supported."); + + ret = sqlite3_key(pDb, pDbKey.get(), MAX_DATABASE_AES_KEY_LENGTH * 2); +#else + int (* sqlite3_key_func)(sqlite3*, const void*, int) = null; + void* handle = dlopen(_DATABASE_LIBRARY_PATH, RTLD_LAZY | RTLD_LOCAL); + SysTryReturnResult(NID_IO, handle != null, E_SYSTEM, + "Failed to dlopen database library file (%s)", dlerror()); + + sqlite3_key_func = reinterpret_cast< int (*)(sqlite3*, const void*, int) >(dlsym(handle, _DATABASE_ENCRYPTION_SYMBOL)); + if (sqlite3_key_func == null) + { + SysLog(NID_IO, "This operation is not supported. (%s)", dlerror()); + dlclose(handle); + r = E_UNSUPPORTED_OPERATION; + goto CATCH; + } + + ret = sqlite3_key_func(pDb, pDbKey.get(), MAX_DATABASE_AES_KEY_LENGTH * 2); + dlclose(handle); +#endif + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = E_INVALID_ARG; + } + else + { + r = E_DATABASE; + } + + SysLog(NID_IO, "[%s] Failed to create secret key (%d, %s).", GetErrorMessage(r), ret, + sqlite3_errmsg(static_cast< sqlite3* >(pDb))); + goto CATCH; + } + } + + __pDatabase = pDb; + __dbName = dbPath; + + return E_SUCCESS; + +CATCH: + return r; +} + +DbStatement* +_DatabaseImpl::CreateStatementN(const String& statement) +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + + int ret = 0; + char* pStrStmt = null; + sqlite3_stmt* pSqlStmt = null; + result r = E_SUCCESS; + + unique_ptr pDbStatement(_DbStatementImpl::CreateDbStatementInstanceN()); + + SysTryReturn(NID_IO, pDbStatement != null, null, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + unique_ptr pUnTrimStatement(_StringConverter::CopyToCharArrayN(statement)); + if (pUnTrimStatement == null) + { + r = GetLastResult(); + goto CATCH; + } + + // trim leading spaces + pStrStmt = pUnTrimStatement.get(); + while ((*pStrStmt == ' ') || (*pStrStmt == '\t')) + { + pStrStmt++; + } + + // prepare the sql statement + ret = sqlite3_prepare_v2((sqlite3*) __pDatabase, pStrStmt, strlen(pStrStmt), &pSqlStmt, null); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (ret) + { + case E_ILLEGAL_ACCESS: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to prepare SQL statement (%s). (%d, %s).", GetErrorMessage(r), pStrStmt, + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } + + // register the sql stmt in DbStatement + // accessing private variable of DbStatement. + _DbStatementImpl::GetInstance(*pDbStatement)->__pStmt = pSqlStmt; + _DbStatementImpl::GetInstance(*pDbStatement)->__pDatabase = __pDatabase; + + // "SELECT" or other statement? + if (strncasecmp(pStrStmt, "select", 5) == 0) + { + _DbStatementImpl::GetInstance(*pDbStatement)->__stmtType = DB_STATEMENT_TYPE_SELECT; + } + else + { + _DbStatementImpl::GetInstance(*pDbStatement)->__stmtType = DB_STATEMENT_TYPE_OTHER; + } + + ClearLastResult(); + return pDbStatement.release(); + +CATCH: + SetLastResult(r); + return null; +} + +DbEnumerator* +_DatabaseImpl::ExecuteStatementN(const DbStatement& statement) +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, _DbStatementImpl::GetInstance(statement)->__pStmt != null, null, E_INVALID_ARG, + "[E_INVALID_ARG] Invalid DbStatement was passed.(null handle was assigned)"); + + int ret = 0; + DbEnumerator* pDbEnum = null; + result r = E_SUCCESS; + + ret = sqlite3_reset((sqlite3_stmt*) _DbStatementImpl::GetInstance(statement)->__pStmt); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (ret) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to reset SQL statement. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } + +REDO_SQLITE_STEP: + ret = sqlite3_step((sqlite3_stmt*) _DbStatementImpl::GetInstance(statement)->__pStmt); + switch (ret) + { + case SQLITE_OK: + case SQLITE_DONE: + ret = sqlite3_reset((sqlite3_stmt*) _DbStatementImpl::GetInstance(statement)->__pStmt); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (ret) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to reset SQL statement. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } + break; + + case SQLITE_ROW: + if (_DbStatementImpl::GetInstance(statement)->__stmtType == DB_STATEMENT_TYPE_SELECT) + { + unique_ptr pTempDbEnum(_DbEnumeratorImpl::CreateDbEnumeratorInstanceN()); + + SysTryReturn(NID_IO, pTempDbEnum != null, null, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + _DbEnumeratorImpl::GetInstance(*pTempDbEnum)->__pEnum = _DbStatementImpl::GetInstance(statement)->__pStmt; + _DbEnumeratorImpl::GetInstance(*pTempDbEnum)->__pDatabase = _DbStatementImpl::GetInstance(statement)->__pDatabase; + +#if 1 + ret = sqlite3_reset((sqlite3_stmt*) _DbStatementImpl::GetInstance(statement)->__pStmt); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (ret) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to reset SQL statement. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } +#endif + + pDbEnum = pTempDbEnum.release(); + + } + else + { + goto REDO_SQLITE_STEP; + } + break; + + default: + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to execute SQL statement. (%d, %s).", GetErrorMessage(r), ret, + sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } + + SetLastResult(E_SUCCESS); + return pDbEnum; + +CATCH: + SetLastResult(r); + return null; +} + +result +_DatabaseImpl::ExecuteSql(const String& sql, bool autoCommit) +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + + int ret = 0; + char* pSqlStr = null; + result r = E_SUCCESS; + + unique_ptr pUnTrimStatement(_StringConverter::CopyToCharArrayN(sql)); + if (pUnTrimStatement == null) + { + r = GetLastResult(); + goto CATCH; + } + + // trim leading spaces + pSqlStr = pUnTrimStatement.get(); + while ((*pSqlStr == ' ') || (*pSqlStr == '\t')) + { + pSqlStr++; + } + + // "SELECT" or other statement? + if (strncasecmp(pSqlStr, "select", 5) == 0) + { + r = E_INVALID_OPERATION; + goto CATCH; + } + + ret = sqlite3_exec((sqlite3*) __pDatabase, pSqlStr, null, null, null); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to execute SQL statement. (%d, %s).", GetErrorMessage(r), ret, + sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } + + return E_SUCCESS; + +CATCH: + return r; +} + +DbEnumerator* +_DatabaseImpl::QueryN(const String& query) +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + + int ret = 0; + char* pQuery = null; + sqlite3_stmt* pSqlStmt = null; + unique_ptr pDbEnum(null); + result r = E_SUCCESS; + + unique_ptr pUnTrimStatement(_StringConverter::CopyToCharArrayN(query)); + if (pUnTrimStatement == null) + { + r = GetLastResult(); + goto CATCH; + } + + // trim leading spaces + pQuery = pUnTrimStatement.get(); + while ((*pQuery == ' ') || (*pQuery == '\t')) + { + pQuery++; + } + + // "SELECT" or other statement? + if (strncasecmp(pQuery, "select", 5) != 0) + { + r = E_INVALID_OPERATION; + goto CATCH; + } + + // prepare the sql statement + ret = sqlite3_prepare_v2((sqlite3*) __pDatabase, pQuery, strlen(pQuery), &pSqlStmt, null); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (ret) + { + case E_ILLEGAL_ACCESS: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to prepare SQL statement (%s). (%d, %s).", GetErrorMessage(r), pQuery, + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } + +// ret = sqlite3_reset((sqlite3_stmt *) pSqlStmt); +// if (ret != SQLITE_OK) +// { +// r = __ConvertNativeSqliteErrorToResult(ret); +// SysLog(NID_IO, "[_DatabaseImpl] ERROR: [%s] Failed to reset SQL statement.", GetErrorMessage(r)); +// goto CATCH; +// } + + ret = sqlite3_step(pSqlStmt); + switch (ret) + { + case SQLITE_OK: + case SQLITE_DONE: + break; + + case SQLITE_ROW: + pDbEnum.reset(_DbEnumeratorImpl::CreateDbEnumeratorInstanceN()); + + SysTryCatch(NID_IO, pDbEnum != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + _DbEnumeratorImpl::GetInstance(*pDbEnum)->__pEnum = pSqlStmt; + _DbEnumeratorImpl::GetInstance(*pDbEnum)->__pDatabase = __pDatabase; + _DbEnumeratorImpl::GetInstance(*pDbEnum)->__shouldReleaseResource = true; + + // doing a reset again, so that enumerator first MoveNext() give the first row. + ret = sqlite3_reset((sqlite3_stmt*) pSqlStmt); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (ret) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to reset SQL statement. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } + break; + + default: + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to exectue SQL statement (%s). (%d, %s).", GetErrorMessage(r), pQuery, + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + goto CATCH; + } + + ClearLastResult(); + return pDbEnum.release(); + +CATCH: + sqlite3_finalize(pSqlStmt); + SetLastResult(r); + return null; +} + +result +_DatabaseImpl::BeginTransaction(void) +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __transactionGoingOn == false, E_INVALID_STATE, + "A transaction is already in progress."); + + result r = E_SUCCESS; + + if (sqlite3_get_autocommit((sqlite3*) __pDatabase) == 0) + { + SysLog(NID_IO, "[E_INVALID_STATE] Already in transaction mode."); + return E_INVALID_STATE; + } + + int ret = sqlite3_exec((sqlite3*) __pDatabase, "BEGIN", null, null, null); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to begin transaction. (%d, %s)", GetErrorMessage(r), ret, + sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + else + { + __transactionGoingOn = true; + } + + return r; +} + +result +_DatabaseImpl::CommitTransaction(void) +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __transactionGoingOn == true, E_INVALID_STATE, + "A transaction is already in progress."); + + int ret = 0; + result r = E_SUCCESS; + + if (sqlite3_get_autocommit((sqlite3*) __pDatabase) != 0) + { + SysLog(NID_IO, "[E_INVALID_STATE] ERROR Message: Not in transaction mode."); + return E_INVALID_STATE; + } + + ret = sqlite3_exec((sqlite3*) __pDatabase, "COMMIT", null, null, null); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_INVALID_OPERATION: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to commit transaction. (%d, %s)", GetErrorMessage(r), ret, + sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + else + { + __transactionGoingOn = false; + } + + return r; +} + +result +_DatabaseImpl::RollbackTransaction(void) +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __transactionGoingOn == true, E_INVALID_STATE, + "No transaction in progress."); + + int ret = 0; + result r = E_SUCCESS; + + if (sqlite3_get_autocommit((sqlite3*) __pDatabase) != 0) + { + SysLog(NID_IO, "[E_SUCCESS] No transaction in progress."); + //return E_INVALID_STATE; + return E_SUCCESS; + } + + ret = sqlite3_exec((sqlite3*) __pDatabase, "ROLLBACK", null, null, null); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_INVALID_OPERATION: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to rollback the transaction. (%d, %s)", GetErrorMessage(r), ret, + sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + else + { + __transactionGoingOn = false; + } + + return r; +} + +String +_DatabaseImpl::GetName(void) const +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + + SetLastResult(E_SUCCESS); + return __dbName; +} + +result +_DatabaseImpl::RegisterUserFunction(const String& functionName, const int argumentCount, void* pUserData, + _IDbUserFunctionListener* pUserFunctionListener, + _IDbUserAggregateListener* pUserAggregateListener) +{ + result r = E_SUCCESS; + int sqliteEncoding = 0; + int ret = 0; + int utf8len = 0; + unique_ptr<_DbContextImpl> pDbContext(null); + _DbContextImpl* pTempDbContext = null; + bool entryFound = false; + int i = 0; + + // Validate input parameters + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, functionName.GetLength() > 0, E_INVALID_ARG, + "Invalid funcName length."); + SysTryReturnResult(NID_IO, argumentCount >= 0 && argumentCount <= MAX_FUNCTION_ARGUMENT_COUNT, E_INVALID_ARG, + "argumentCount < 0 or > 127."); + + if (pUserFunctionListener != null && pUserAggregateListener != null) + { + SysTryReturnResult(NID_IO, 0, E_INVALID_ARG, + "FunctionListener and AggregateListener cannot be registered together"); + } + + //select the equivalent sqlite encoding. + + unique_ptr pFuncNameBuf(StringUtil::StringToUtf8N(functionName)); + SysTryReturn(NID_IO, pFuncNameBuf != null, GetLastResult(), + GetLastResult(), "[%s] Invalid Function name.", GetErrorMessage(GetLastResult())); + + utf8len = pFuncNameBuf->GetLimit(); + SysTryReturnResult(NID_IO, utf8len > 0 && utf8len <= MAX_UTF8_BYTES, E_INVALID_ARG, + "functionName length in utf8 bytes should be >0 && <=255."); + + sqliteEncoding = SQLITE_UTF8; // support only UTF8 + + //check if the (FunctionName, argumentCount) already exist in the list + for (i = 0; i < __userFunctionContextList.GetCount(); i++) + { + pTempDbContext = dynamic_cast<_DbContextImpl*> (__userFunctionContextList.GetAt(i)); + SysTryReturnResult(NID_IO, pTempDbContext, E_IO, "The __userFunctionContextList has an invalid element."); + if ((pTempDbContext->__argumentCount == argumentCount) && + (pTempDbContext->__functionName == functionName)) + { + entryFound = true; + break; + } + } + + if (entryFound && (null != pUserFunctionListener || null != pUserAggregateListener)) + { + SysTryReturnResult(NID_IO, 0, E_INVALID_ARG, + "(functionName, argumentCount) already registered"); + } + + if (pUserFunctionListener != null) // register FunctionListener + { + pDbContext.reset(new (std::nothrow) _DbContextImpl()); + SysTryReturnResult(NID_IO, pDbContext != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + ret = sqlite3_create_function((sqlite3*) __pDatabase, + (const char*) pFuncNameBuf->GetPointer(), argumentCount, sqliteEncoding, pDbContext.get(), + _DatabaseImpl::UserFunctionListener, null, null); + } + else if (pUserAggregateListener != null) // register both FunctionStepListener and FunctionFinalListener + { + pDbContext.reset(new (std::nothrow) _DbContextImpl()); + + SysTryReturnResult(NID_IO, pDbContext != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + ret = sqlite3_create_function((sqlite3*) __pDatabase, + (const char*) pFuncNameBuf->GetPointer(), argumentCount, sqliteEncoding, pDbContext.get(), + null, _DatabaseImpl::UserFunctionStepListener, _DatabaseImpl::UserFunctionFinalListener); + } + else // Delete registered user function/Aggregate + { + ret = sqlite3_create_function((sqlite3*) __pDatabase, + (const char*) pFuncNameBuf->GetPointer(), argumentCount, sqliteEncoding, null, null, null, null); + } + + if (ret != SQLITE_OK) //error + { + r = __ConvertNativeSqliteErrorToResult(ret); + SysLog(NID_IO, "[%s] ERROR Message: [%s], Failed to create/delete user defined SQL function.", GetErrorMessage(r), + sqlite3_errmsg((sqlite3*)__pDatabase)); + return r; + } + + if (entryFound && (!pUserFunctionListener && !pUserAggregateListener)) // delete the user function entry from list + { + r = __userFunctionContextList.Remove(*pTempDbContext, true); + SysTryReturn(NID_IO, !IsFailed(r), GetLastResult(), + GetLastResult(), "[%s] Failed to remove user function context to the list.", GetErrorMessage(GetLastResult())); + } + + if (pDbContext != null) + { + //store listener and user data + pDbContext->__pUserData = pUserData; + pDbContext->__argumentCount = argumentCount; + pDbContext->__functionName = functionName; + if (pUserFunctionListener != null) + { + pDbContext->__pUserFunctionListener = pUserFunctionListener; + } + if (pUserAggregateListener != null) + { + pDbContext->__pUserAggregateListener = pUserAggregateListener; + } + + // add entry to the list + r = __userFunctionContextList.Add(*(pDbContext.release())); + SysTryReturn(NID_IO, !IsFailed(r), GetLastResult(), + GetLastResult(), "[%s] Failed to add user function context to the list.", GetErrorMessage(GetLastResult())); + } + + return E_SUCCESS; +} + +result +_DatabaseImpl::RegisterUserCollation(const String& collationName, void* pUserData, + _IDbUserCollationListener* pUserCollationListener) +{ + result r = E_SUCCESS; + int sqliteEncoding = 0; + int ret = 0; + int utf8len = 0; + unique_ptr<_DbContextImpl> pDbContext(null); + _DbContextImpl* pTempDbContext = null; + bool entryFound = false; + int i = 0; + + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, collationName.GetLength() > 0, E_INVALID_ARG, + "Invalid collationName length."); + + sqliteEncoding = SQLITE_UTF8; // support only UTF8 + + unique_ptr pColNameBuf(StringUtil::StringToUtf8N(collationName)); + SysTryReturn(NID_IO, pColNameBuf != null, GetLastResult(), GetLastResult(), "[%s] Invalid Function name.", + GetErrorMessage(GetLastResult())); + + utf8len = pColNameBuf->GetLimit(); // get UTF_8 bytes length + SysTryReturnResult(NID_IO, utf8len > 0 && utf8len <= MAX_UTF8_BYTES, E_INVALID_ARG, + "functionName length in utf8 bytes should be >0 && <=255."); + + //check if the (FunctionName) already registered + for (i = 0; i < __userCollationContextList.GetCount(); i++) + { + pTempDbContext = dynamic_cast< _DbContextImpl* >(__userCollationContextList.GetAt(i)); + SysTryReturnResult(NID_IO, pTempDbContext, E_IO, "The __userCollationContextList has an invalid element."); + if (pTempDbContext->__collationName == collationName) + { + entryFound = true; + break; + } + } + + if (entryFound && (pUserCollationListener != null)) // check if the operation is to delete the user function + { + SysTryReturnResult(NID_IO, 0, E_INVALID_ARG, "(collationName) already registered"); + } + + if (pUserCollationListener != null) + { + pDbContext.reset(new (std::nothrow) _DbContextImpl()); + SysTryReturnResult(NID_IO, pDbContext != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + // register CollationListener() + ret = sqlite3_create_collation((sqlite3*) __pDatabase, (const char*) pColNameBuf->GetPointer(), sqliteEncoding, pDbContext.get(), + _DatabaseImpl::UserCollationListener); + } + else // delete Collating function + { + ret = sqlite3_create_collation((sqlite3*) __pDatabase, (const char*) pColNameBuf->GetPointer(), sqliteEncoding, null, null); + } + + if (ret != SQLITE_OK) + { + r = __ConvertNativeSqliteErrorToResult(ret); + SysLog(NID_IO, "[%s] ERROR Message: [%s], Failed to create/delete user defined SQL Collation.", GetErrorMessage(r), + sqlite3_errmsg((sqlite3*)__pDatabase)); + return r; + } + + if (entryFound && !pUserCollationListener) // delete the user collation entry from list + { + r = __userCollationContextList.Remove(*pTempDbContext, true); + SysTryReturn(NID_IO, !IsFailed(r), GetLastResult(), + GetLastResult(), "[%s] Failed to remove user collation context from the list.", GetErrorMessage(GetLastResult())); + } + + if (pDbContext != null) + { + //store listener and user data + pDbContext->__pUserData = pUserData; + pDbContext->__collationName = collationName; + pDbContext->__pUserCollationListener = pUserCollationListener; + // add entry to the list + r = __userCollationContextList.Add((*(pDbContext.release()))); + SysTryReturn(NID_IO, !IsFailed(r), GetLastResult(), + GetLastResult(), "[%s] Failed to add user collation context to the list.", GetErrorMessage(GetLastResult())); + + } + + return E_SUCCESS; +} + +long long +_DatabaseImpl::GetLastInsertRowId(void) const +{ + SysAssertf(__pDatabase != null, "Not yet constructed. Construct() should be called before use.\n"); + + // Retrieve last inserted row Id of the specified Db connection. + // sqlite rowIds starts from 1 to max. 0 means no rows available in the database. + // even if we delete the last inserted row, it still returns the rowid of last insert. + // and does not care about any deletions happened. + long long insertRowId = sqlite3_last_insert_rowid(static_cast< sqlite3* >(__pDatabase)); + if (insertRowId == 0) + { + return -1; + } + else + { + return insertRowId; + } +} + +result +_DatabaseImpl::Delete(const String& databasePath) +{ + result r = E_SUCCESS; + int ret = 0; + + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(databasePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", databasePath.GetPointer()); + + unique_ptr pDbPath(_StringConverter::CopyToCharArrayN(databasePath)); + if (pDbPath == null) + { + return GetLastResult(); + } + + // remove the file + ret = unlink(pDbPath.get()); + if (ret != 0) + { + r = __ConvertNativeErrorToResult(errno); + } + + return r; +} + +bool +_DatabaseImpl::Exists(const String& databasePath) +{ + return _FileImpl::IsFileExist(databasePath); +} + +void +_DatabaseImpl::UserFunctionListener(sqlite3_context* pContext, int argumentCount, sqlite3_value** pArgList) +{ + _DbContextImpl* pDbContext = null; + + pDbContext = static_cast< _DbContextImpl* >(sqlite3_user_data(pContext)); + + SysTryReturnVoidResult(NID_IO, pDbContext, E_INVALID_STATE, "[E_INVALID_STATE] pDbContext is null."); + SysTryReturnVoidResult(NID_IO, pDbContext->__pUserFunctionListener, E_INVALID_STATE, + "[E_INVALID_STATE] UserAggregateListener is null."); + + //Set DbContext data + if (pDbContext->__pContext != (void*) pContext) + { + pDbContext->__pContext = (void*) pContext; + } + + if (pDbContext->__argumentCount != argumentCount) + { + SysLog(NID_IO, "Message: __argumentCount mismatch."); + pDbContext->__argumentCount = argumentCount; + } + + if (pDbContext->__pArgList != (void**) pArgList) + { + pDbContext->__pArgList = (void**) pArgList; + } + // Invoke the user listener method + pDbContext->__pUserFunctionListener->OnDbUserFunction(*pDbContext, argumentCount); + + SetLastResult(E_SUCCESS); +} + +void +_DatabaseImpl::UserFunctionStepListener(sqlite3_context* pContext, int argumentCount, sqlite3_value** pArgList) +{ + _DbContextImpl* pDbContext = null; + + pDbContext = static_cast< _DbContextImpl* >(sqlite3_user_data(pContext)); + + SysTryReturnVoidResult(NID_IO, pDbContext, E_INVALID_STATE, "[E_INVALID_STATE] pDbContext is null."); + SysTryReturnVoidResult(NID_IO, pDbContext->__pUserAggregateListener, E_INVALID_STATE, + "[E_INVALID_STATE] __pDbContextImpl->__pUserAggregateListener is null."); + + //Set DbContext data + if (pDbContext->__pContext != (void*) pContext) + { + pDbContext->__pContext = (void*) pContext; + } + + if (pDbContext->__argumentCount != argumentCount) + { + pDbContext->__argumentCount = argumentCount; + } + + if (pDbContext->__pArgList != (void**) pArgList) + { + pDbContext->__pArgList = (void**) pArgList; + } + + // invoke the user listener method + pDbContext->__pUserAggregateListener->OnDbUserAggregateStep(*pDbContext, argumentCount); + + SetLastResult(E_SUCCESS); +} + +void +_DatabaseImpl::UserFunctionFinalListener(sqlite3_context* pContext) +{ + _DbContextImpl* pDbContext = null; + + pDbContext = static_cast< _DbContextImpl* >(sqlite3_user_data(pContext)); + + SysTryReturnVoidResult(NID_IO, pDbContext, E_INVALID_STATE, "[E_INVALID_STATE] pDbContext is null."); + SysTryReturnVoidResult(NID_IO, pDbContext->__pUserAggregateListener, E_INVALID_STATE, + "[E_INVALID_STATE] UserAggregateListener is null."); + + // set context and user data + if (pDbContext->__pContext != (void*) pContext) + { + pDbContext->__pContext = (void*) pContext; + } + + // invoke the user listener method + pDbContext->__pUserAggregateListener->OnDbUserAggregateFinal(*pDbContext); + + SetLastResult(E_SUCCESS); +} + +int +_DatabaseImpl::UserCollationListener(void* pUserData, int length1, const void* pInput1, int length2, const void* pInput2) +{ + _DbContextImpl* pDbContext = null; + char* pDataInput = null; + String string1(""); + String string2(""); + + pDbContext = static_cast< _DbContextImpl* >(pUserData); + + SysTryReturn(NID_IO, pDbContext, 0, E_INVALID_STATE, "[E_INVALID_STATE] pDbContext is null."); + SysTryReturn(NID_IO, pDbContext->__pUserCollationListener, 0, E_INVALID_STATE, + "[E_INVALID_STATE] UserCollationListener is null."); + + if (length1 > 0 && (const char*) pInput1 != null) + { + pDataInput = (char*) malloc((length1 + 1) * sizeof(char)); + + if (pDataInput == null) + { + return 0; + } + + memset(pDataInput, 0, length1 + 1); + strncpy(pDataInput, (const char*) pInput1, length1); + string1.Clear(); + string1.Append((const char*) pDataInput); + free(pDataInput); + } + + if (length2 > 0 && (const char*) pInput2 != null) + { + pDataInput = (char*) malloc((length2 + 1) * sizeof(char)); + + if (pDataInput == null) + { + return 0; + } + + memset(pDataInput, 0, length2 + 1); + strncpy(pDataInput, (const char*) pInput2, length2); + string2.Clear(); + string2.Append((const char*) pDataInput); + free(pDataInput); + } + + SetLastResult(E_SUCCESS); + + return pDbContext->__pUserCollationListener->OnDbUserCollation(string1, string2, pUserData); +} + +result +_DatabaseImpl::ConvertToSecureDatabase(const String& plainDbPath, const String& secureDbPath, const ByteBuffer* pKey) +{ + result r = E_SUCCESS; + String sql; + String parentDirPath; + FileAttributes attr; + + if (Database::Exists(secureDbPath)) + { + if (GetLastResult() == E_SUCCESS) + { + r = File::GetAttributes(secureDbPath, attr); + if (r == E_SUCCESS) + { + if (attr.IsDirectory()) + { + return E_INVALID_ARG; + } + else + { + return E_FILE_ALREADY_EXIST; + } + } + else + { + return r; + } + } + else + { + return E_SYSTEM; + } + } + + unique_ptrpDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_IO, pDatabase, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pDatabase->Construct(secureDbPath, "a+"); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating to the caller...", GetErrorMessage(r)); + + pDatabase.reset(new (std::nothrow) Database()); + SysTryReturnResult(NID_IO, pDatabase, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pDatabase->Construct(plainDbPath, "r+"); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating to the caller...", GetErrorMessage(r)); + + unique_ptr pSqlStr(new (std::nothrow) String(MAX_DATABASE_SQL_LENGTH)); + SysTryReturnResult(NID_IO, pSqlStr != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + unique_ptr pPhysicalDbPath(_StringConverter::CopyToCharArrayN(secureDbPath)); + SysTryReturn(NID_IO, pPhysicalDbPath != null, GetLastResult(), GetLastResult(), "[%s] Invalid file path.", GetErrorMessage(GetLastResult())); + + unique_ptr pDbKey(_SecureIoUtil::GenerateDatabaseKeyN(pKey)); + SysTryReturnResult(NID_IO, pDbKey != null, E_INVALID_ARG, "GenerateDatabaseKeyN returned null."); + + pSqlStr->Format(MAX_DATABASE_SQL_LENGTH, L"ATTACH DATABASE '%s' AS encrypted KEY '%s'", pPhysicalDbPath.get(), pDbKey.get()); + + sql.Append(*pSqlStr); + r = pDatabase->ExecuteSql(sql, true); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating to the caller...", GetErrorMessage(r)); + sql.Clear(); + + unique_ptr pEnum(pDatabase->QueryN(L"SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type!='meta' ORDER BY tbl_name, type DESC, name")); + r = GetLastResult(); + if (r == E_SUCCESS) + { + if (pEnum) + { + String schema; + String tempQuery(L"encrypted."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetStringAt(0, schema); + if (r != E_SUCCESS) + { + if (r == E_INVALID_STATE || r == E_TYPE_MISMATCH || r == E_INVALID_ENCODING_RANGE) //internal exception by this method + { + r = E_SYSTEM; + } + return r; + } + + if (schema.StartsWith(L"sqlite_", MAX_SQLCIPHER_SCHEMA_PREFIX_SIZE)) + { + continue; + } + + r = schema.Insert(tempQuery, MAX_SQLCIPHER_SCHEMA_PREFIX_SIZE); + if (IsFailed(r)) + { + return E_SYSTEM; + } + + r = pDatabase->ExecuteSql(schema, true); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating to caller...", GetErrorMessage(r)); + } + } + } + else + { + SysPropagate(NID_IO, r); + return r; + } + + pEnum.reset(pDatabase->QueryN(L"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")); + r = GetLastResult(); + if (r == E_SUCCESS) + { + if (pEnum) + { + String tableName; + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetStringAt(0, tableName); + if (r != E_SUCCESS) + { + if (r == E_INVALID_STATE || r == E_TYPE_MISMATCH || r == E_INVALID_ENCODING_RANGE) //internal exception by this method + { + r = E_IO; + } + + return r; + } + + if (tableName.StartsWith(L"sqlite_", 0)) + { + continue; + } + + pSqlStr.reset(new (std::nothrow) String(MAX_DATABASE_SQL_LENGTH)); + SysTryReturnResult(NID_IO, pSqlStr, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pSqlStr->Format(MAX_DATABASE_SQL_LENGTH, L"INSERT INTO encrypted.%ls SELECT * FROM %ls", tableName.GetPointer(), tableName.GetPointer()); + + sql.Append(*pSqlStr); + r = pDatabase->ExecuteSql(sql, true); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating to the caller...", GetErrorMessage(r)); + sql.Clear(); + } + } + } + else + { + SysPropagate(NID_IO, r); + return r; + } + + sql.Append(L"DETACH DATABASE encrypted"); + + r = pDatabase->ExecuteSql(sql, true); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating to the caller...", GetErrorMessage(r)); + + return E_SUCCESS; +} + +_DatabaseImpl* +_DatabaseImpl::GetInstance(Database& database) +{ + return database.__pDatabaseImpl; +} + +const _DatabaseImpl* +_DatabaseImpl::GetInstance(const Database& database) +{ + return database.__pDatabaseImpl; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DbContextImpl.cpp b/src/io/FIo_DbContextImpl.cpp new file mode 100644 index 0000000..0e66131 --- /dev/null +++ b/src/io/FIo_DbContextImpl.cpp @@ -0,0 +1,193 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DbContextImpl.cpp + * @brief This is the implementation file for _DbContextImpl class. + */ + +#include + +#include +#include + +#include +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +// Mapping table for DB error to SQL error codes +static int dbErrorCodeToSqlErrorTable[] = +{ + SQLITE_OK, // DB_OK + SQLITE_ERROR, // DB_ERROR + SQLITE_INTERNAL, // DB_INTERNAL + SQLITE_PERM, // DB_PERM + SQLITE_ABORT, // DB_ABORT + SQLITE_BUSY, // DB_BUSY + SQLITE_LOCKED, // DB_LOCKED + SQLITE_NOMEM, // DB_NOMEM + SQLITE_READONLY, // DB_READONLY + SQLITE_INTERRUPT, // DB_INTERRUPT + SQLITE_IOERR, // DB_IOERR + SQLITE_CORRUPT, // DB_AORRUPT + SQLITE_NOTFOUND, // DB_NOTFOUND + SQLITE_FULL, // DB_FULL + SQLITE_CANTOPEN, // DB_CANTOPEN + SQLITE_PROTOCOL, // DB_PROTOCOL + SQLITE_EMPTY, // DB_EMPTY + SQLITE_SCHEMA, // DB_SCHEMA + SQLITE_TOOBIG, // DB_TOOBIG + SQLITE_CONSTRAINT, // DB_CONSTRAINT + SQLITE_MISMATCH, // DB_MISMATCH + SQLITE_MISUSE, // DB_MISUSE + SQLITE_NOLFS, // DB_NOLFS + SQLITE_AUTH, // DB_AUTH + SQLITE_FORMAT, // DB_FORMAT + SQLITE_RANGE, // DB_RANGE + SQLITE_NOTADB, // DB_NOTADB + SQLITE_ROW, // DB_ROW + SQLITE_DONE // DB_DONE +}; + +int +_DbContextImpl::ConvertDbErrorToNativeSqliteError(int errorCode) +{ + int nativeSqlErrCode = -1; + + if ((errorCode >= 0) && (errorCode < (int) (sizeof(dbErrorCodeToSqlErrorTable) / sizeof(int)))) + { + nativeSqlErrCode = dbErrorCodeToSqlErrorTable[errorCode]; + } + + return nativeSqlErrCode; +} + +_DbContextImpl::_DbContextImpl(void) + : __pContext(null) + , __pArgList(null) + , __pUserData(null) + , __pUserFunctionListener(null) + , __pUserAggregateListener(null) + , __pUserCollationListener(null) + , __argumentCount(0) +{ +} + +_DbContextImpl::~_DbContextImpl(void) +{ +} + +result +_DbContextImpl::GetStringAt(int argumentIndex, String& value) +{ + SysTryReturnResult(NID_IO, __pContext != null, E_INVALID_STATE, + "The Object is not constructed or database context has already been closed."); + SysTryReturnResult(NID_IO, argumentIndex >= 0 && argumentIndex < __argumentCount, E_INVALID_ARG, + "Th argumentIndex parameter is wrong."); + + value = String((const char*) sqlite3_value_text((sqlite3_value*) __pArgList[argumentIndex])); + + return E_SUCCESS; +} + +result +_DbContextImpl::SetResultString(const String& value) +{ + SysTryReturnResult(NID_IO, __pContext != null, E_INVALID_STATE, + "The Object is not constructed or database context has already been closed."); + SysTryReturnResult(NID_IO, value.GetLength() > 0, E_INVALID_ARG, + "value length is 0 or negative."); + + char* pValue = _StringConverter::CopyToCharArrayN(value); //pValue will be released by _DbContextImpl::DestroyListener + if (pValue == null) + { + return GetLastResult(); + } + sqlite3_result_text((sqlite3_context*) __pContext, pValue, -1, _DbContextImpl::DestroyListener); + + return E_SUCCESS; +} + +result +_DbContextImpl::SetResultInt(int value) +{ + SysTryReturnResult(NID_IO, __pContext != null, E_INVALID_STATE, + "The Object is not constructed or database context has already been closed."); + + //set the integer value + sqlite3_result_int((sqlite3_context*) __pContext, value); + + return E_SUCCESS; +} + +result +_DbContextImpl::SetResultDouble(double value) +{ + SysTryReturnResult(NID_IO, __pContext != null, E_INVALID_STATE, + "The Object is not constructed or database context has already been closed."); + + //set the double value + sqlite3_result_double((sqlite3_context*) __pContext, value); + + return E_SUCCESS; +} + +result +_DbContextImpl::SetResultErrorCode(_DbUserListenerErrorCode errorCode) +{ + int sqlErrcode = -1; + + SysTryReturnResult(NID_IO, __pContext != null, E_INVALID_STATE, + "The Object is not constructed or database context has already been closed."); + SysTryReturnResult(NID_IO, errorCode >= DB_USER_LISTENER_OK && errorCode <= DB_USER_LISTENER_NOMEM, E_INVALID_ARG, + "errorCode not in the range."); + + sqlErrcode = _DbContextImpl::ConvertDbErrorToNativeSqliteError((int) errorCode); + //set the error code. + sqlite3_result_error_code((sqlite3_context*) __pContext, sqlErrcode); + + return E_SUCCESS; +} + +void* +_DbContextImpl::GetUserData(void) +{ + SysTryReturn(NID_IO, __pContext != null, null, E_INVALID_STATE, + "[E_INVALID_STATE] The Object is not constructed or database context has already been closed."); + + ClearLastResult(); + + return __pUserData; +} + +void +_DbContextImpl::DestroyListener(void* pData) +{ + if (pData != null) + { + delete[] static_cast< char* >(pData); + pData = null; + } +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DbEnumeratorImpl.cpp b/src/io/FIo_DbEnumeratorImpl.cpp new file mode 100644 index 0000000..365f7d4 --- /dev/null +++ b/src/io/FIo_DbEnumeratorImpl.cpp @@ -0,0 +1,1209 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DbEnumeratorImpl.cpp + * @brief This is the implementation file for _DbEnumeratorImpl class. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Runtime; +using namespace Tizen::System; +using namespace Tizen::App; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ +static const unsigned int _MAX_DB_CACHE_SIZE = 2 * 1024 * 1024; // default cache size is 2MB + +class _DbRow + : public Object +{ +public: + _DbRow(void); + ~_DbRow(void); + LinkedList dbValuesList; + bool hasData; + int dataSize; +}; + +_DbRow::_DbRow(void) + : hasData(false) + , dataSize(0) +{ +} + +_DbRow::~_DbRow(void) +{ + if (this->hasData == true) + { + dbValuesList.RemoveAll(true); + } +} + +class _DbColumn + : public Object +{ +public: + _DbColumn(void); + ~_DbColumn(void); + int type; + int size; + unique_ptr pData; +}; + +_DbColumn::_DbColumn(void) + : type(SQLITE_NULL) + , size(0) + , pData(null) +{ +} + +_DbColumn::~_DbColumn(void) +{ +} + +class _DbEnumeratorCache + : public Object +{ +private: + /** + * This is the default constructor for this class. + */ + _DbEnumeratorCache(void); + ~_DbEnumeratorCache(void); + + unsigned int __currentUsedMemory; + _DbRow* __pCurrentDbRow; + LinkedList __dbColumnNameList; + LinkedList __dbRowList; + + friend class _DbEnumeratorImpl; + +}; + +_DbEnumeratorCache::_DbEnumeratorCache(void) + : __currentUsedMemory(0) + , __pCurrentDbRow(null) +{ +} + +_DbEnumeratorCache::~_DbEnumeratorCache(void) +{ + __dbColumnNameList.RemoveAll(true); + __dbRowList.RemoveAll(true); +} + +_DbEnumeratorImpl::_DbEnumeratorImpl(void) + : __shouldReleaseResource(false) + , __pEnum(null) + , __pDatabase(null) + , __columnCount(0) + , __rowCount(0) + , __currentRowIndex(-1) + , __pDbEnumeratorCache(null) +{ +} + +_DbEnumeratorImpl::~_DbEnumeratorImpl(void) +{ + result r = E_SUCCESS; + int ret = 0; + + if (__shouldReleaseResource && __pEnum) + { + ret = sqlite3_finalize(static_cast (__pEnum)); + if (ret != SQLITE_OK) + { + r = __ConvertNativeSqliteErrorToResult(ret); + SysLog(NID_IO, "[%s] Failed to finalize SQL statement (%d, %s).", GetErrorMessage( + r), ret, sqlite3_errmsg((sqlite3*) __pDatabase)); + } + } + + delete __pDbEnumeratorCache; +} + +result +_DbEnumeratorImpl::CacheRow(bool cacheColumnNamesToo) +{ + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + result r = E_SUCCESS; + + // check if all the rows are been cached already + if (__rowCount > 0) + { + SysTryReturnResult(NID_IO, __currentRowIndex < (__rowCount - 1), E_OUT_OF_RANGE, + "Reached to the end of the result set."); + } + + ret = sqlite3_step((sqlite3_stmt*) __pEnum); + switch (ret) + { + case SQLITE_DONE: + { + // set max rows in the result set + if (__currentRowIndex >= 0) + { + __rowCount = __currentRowIndex + 1; + } + return E_OUT_OF_RANGE; + } + case SQLITE_ROW: + { + int dbRowSize = 0; + unique_ptr<_DbRow> pDbRow(new (std::nothrow) _DbRow); + SysTryReturnResult(NID_IO, pDbRow != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + for (int i = 0; i < __columnCount; i++) + { + // prepare column name list only once + if (cacheColumnNamesToo == true) + { + // get column name + const char* pName = sqlite3_column_name((sqlite3_stmt*) __pEnum, i); + + r = __pDbEnumeratorCache->__dbColumnNameList.Add(* new (std::nothrow) String(pName)); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + unique_ptr<_DbColumn> pDbColumn(new (std::nothrow) _DbColumn); + SysTryReturnResult(NID_IO, pDbColumn != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + int columnType = sqlite3_column_type((sqlite3_stmt*) __pEnum, i); + + pDbColumn->type = columnType; + + switch (columnType) + { + case SQLITE_INTEGER: + { + int size = sizeof(long long); + unique_ptr pData(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pData != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + memset(pData.get(), 0, size + 1); + long long value = sqlite3_column_int64((sqlite3_stmt*) __pEnum, i); + memcpy(pData.get(), &value, size); + pDbColumn->size = size; + pDbColumn->pData = move(pData); + break; + } + case SQLITE_FLOAT: + { + int size = sizeof(double); + unique_ptr pData(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pData != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + memset(pData.get(), 0, size + 1); + double doubleValue = sqlite3_column_double((sqlite3_stmt*) __pEnum, i); + memcpy(pData.get(), &doubleValue, size); + pDbColumn->size = size; + pDbColumn->pData = move(pData); + break; + } + case SQLITE_TEXT: + { + int size = sqlite3_column_bytes((sqlite3_stmt*) __pEnum, i); + unique_ptr pData(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pData != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + memset(pData.get(), 0, size + 1); + char* pTextData = (char*) sqlite3_column_text((sqlite3_stmt*) __pEnum, i); + memcpy(pData.get(), pTextData, size); + pDbColumn->size = size; + pDbColumn->pData = move(pData); + break; + } + case SQLITE_BLOB: + { + int size = sqlite3_column_bytes((sqlite3_stmt*) __pEnum, i); + unique_ptr pData(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pData != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + memset(pData.get(), 0, size + 1); + char* pBlobData = (char*) sqlite3_column_blob((sqlite3_stmt*) __pEnum, i); + memcpy(pData.get(), pBlobData, size); + pDbColumn->size = size; + pDbColumn->pData = move(pData); + break; + } + case SQLITE_NULL: + { + int size = sqlite3_column_bytes((sqlite3_stmt*) __pEnum, i); + pDbColumn->size = size; + break; + } + default: + { + SysTryReturnResult(NID_IO, false, E_DATABASE, "The column type is invalid."); + break; + } + } + dbRowSize += pDbColumn->size; + r = pDbRow->dbValuesList.Add(*pDbColumn.release()); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + __pDbEnumeratorCache->__currentUsedMemory += dbRowSize; + + if (__pDbEnumeratorCache->__currentUsedMemory > _MAX_DB_CACHE_SIZE) + { + // remove old rows in FIFO manner till there is enough space for the current row. + for (int i = 0; i < __pDbEnumeratorCache->__dbRowList.GetCount(); i++) + { + _DbRow* pTmpDbRow = dynamic_cast< _DbRow* >(__pDbEnumeratorCache->__dbRowList.GetAt(i)); + SysTryReturn(NID_IO, pTmpDbRow != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult())); + if (pTmpDbRow->hasData == true) + { + pTmpDbRow->dbValuesList.RemoveAll(true); + pTmpDbRow->hasData = false; + __pDbEnumeratorCache->__currentUsedMemory -= pTmpDbRow->dataSize; + pTmpDbRow->dataSize = 0; + + if (__pDbEnumeratorCache->__currentUsedMemory <= _MAX_DB_CACHE_SIZE) + { + break; + } + } + } + } + + pDbRow->hasData = true; + pDbRow->dataSize = dbRowSize; + _DbRow* pTmpDbRow = pDbRow.release(); + r = __pDbEnumeratorCache->__dbRowList.Add(*pTmpDbRow); + if (IsFailed(r)) + { + pTmpDbRow->dbValuesList.RemoveAll(true); + delete pTmpDbRow; + SysLog(NID_IO, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + + ++__currentRowIndex; + + // set current cursor + __pDbEnumeratorCache->__pCurrentDbRow = pTmpDbRow; + + break; + } + default: + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to move row index. (%d, %s).", GetErrorMessage(r), ret, + sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + + return r; + } + } + + return E_SUCCESS; +} + +result +_DbEnumeratorImpl::CacheRow(_DbRow& dbRow, int rowIndex) +{ + result r = E_SUCCESS; + int ret = 0; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + // reset sqlite result set. + ret = sqlite3_reset((sqlite3_stmt*) __pEnum); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (ret) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to reset SQL statement. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + return r; + } + + // move cursor to desired position. + for (int i = 0; i <= rowIndex; i++) + { + ret = sqlite3_step((sqlite3_stmt*) __pEnum); + if (ret != SQLITE_ROW) + { + SysLog(NID_IO, "Did not yield any result row"); + return E_DATABASE; + } + } + + // ret == SQLITE_ROW, cache the row. + int dbRowSize = 0; + + for (int i = 0; i < __columnCount; i++) + { + unique_ptr<_DbColumn> pDbColumn(new (std::nothrow) _DbColumn); + SysTryReturnResult(NID_IO, pDbColumn != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + int columnType = sqlite3_column_type((sqlite3_stmt*) __pEnum, i); + + pDbColumn->type = columnType; + + switch (columnType) + { + case SQLITE_INTEGER: + { + int size = sizeof(long long); + unique_ptr pData(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pData != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + memset(pData.get(), 0, size + 1); + long long value = sqlite3_column_int64((sqlite3_stmt*) __pEnum, i); + memcpy(pData.get(), &value, size); + pDbColumn->size = size; + pDbColumn->pData = move(pData); + break; + } + case SQLITE_FLOAT: + { + int size = sizeof(double); + unique_ptr pData(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pData != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + memset(pData.get(), 0, size + 1); + double doubleValue = sqlite3_column_double((sqlite3_stmt*) __pEnum, i); + memcpy(pData.get(), &doubleValue, size); + pDbColumn->size = size; + pDbColumn->pData = move(pData); + break; + } + case SQLITE_TEXT: + { + int size = sqlite3_column_bytes((sqlite3_stmt*) __pEnum, i); + unique_ptr pData(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pData != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + memset(pData.get(), 0, size + 1); + char* pTextData = (char*) sqlite3_column_text((sqlite3_stmt*) __pEnum, i); + memcpy(pData.get(), pTextData, size); + pDbColumn->size = size; + pDbColumn->pData = move(pData); + break; + } + case SQLITE_BLOB: + { + int size = sqlite3_column_bytes((sqlite3_stmt*) __pEnum, i); + unique_ptr pData(new (std::nothrow) char[size + 1]); + SysTryReturnResult(NID_IO, pData != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + memset(pData.get(), 0, size + 1); + char* pBlobData = (char*) sqlite3_column_blob((sqlite3_stmt*) __pEnum, i); + memcpy(pData.get(), pBlobData, size); + pDbColumn->size = size; + pDbColumn->pData = move(pData); + break; + } + case SQLITE_NULL: + { + int size = sqlite3_column_bytes((sqlite3_stmt*) __pEnum, i); + pDbColumn->size = size; + break; + } + default: + { + SysTryReturnResult(NID_IO, false, E_DATABASE, "The column type is invalid."); + break; + } + } + + dbRowSize += pDbColumn->size; + r = dbRow.dbValuesList.Add(*pDbColumn.release()); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + } + + __pDbEnumeratorCache->__currentUsedMemory += dbRowSize; + + if (__pDbEnumeratorCache->__currentUsedMemory > _MAX_DB_CACHE_SIZE) + { + // In this case remove old rows in LIFO manner till there is enough space for the current row. + for (int i = __pDbEnumeratorCache->__dbRowList.GetCount() - 1; i >= 0; i--) + { + _DbRow* pTmpDbRow = dynamic_cast< _DbRow* >(__pDbEnumeratorCache->__dbRowList.GetAt(i)); + SysTryCatch(NID_IO, pTmpDbRow != null, r = GetLastResult(), GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult())); + if (pTmpDbRow->hasData == true) + { + pTmpDbRow->dbValuesList.RemoveAll(true); + pTmpDbRow->hasData = false; + __pDbEnumeratorCache->__currentUsedMemory -= pTmpDbRow->dataSize; + pTmpDbRow->dataSize = 0; + + if (__pDbEnumeratorCache->__currentUsedMemory <= _MAX_DB_CACHE_SIZE) + { + break; // found enough space. + } + } + } + } + + dbRow.hasData = true; + dbRow.dataSize = dbRowSize; + __currentRowIndex = rowIndex; + + // set current cursor + __pDbEnumeratorCache->__pCurrentDbRow = &dbRow; + + + return E_SUCCESS; + +CATCH: + dbRow.dbValuesList.RemoveAll(true); + dbRow.hasData = false; + + return r; +} + +result +_DbEnumeratorImpl::MoveNext(void) +{ + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + _DbRow* pDbRow = null; + result r = E_SUCCESS; + + if (__pDbEnumeratorCache == null) // called for the first time + { + __pDbEnumeratorCache = new (std::nothrow) _DbEnumeratorCache; // allocate only once + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + __columnCount = sqlite3_column_count((sqlite3_stmt*) __pEnum); + + SysLog(NID_IO, "__columnCount: %d", __columnCount); + + return this->CacheRow(true); + } + else + { + SysLog(NID_IO, "current used memory:%d", __pDbEnumeratorCache->__currentUsedMemory); + if ((__currentRowIndex + 1 <= __pDbEnumeratorCache->__dbRowList.GetCount() - 1)) + { + pDbRow = dynamic_cast <_DbRow*>(__pDbEnumeratorCache->__dbRowList.GetAt(__currentRowIndex + 1)); + SysTryReturnResult(NID_IO, pDbRow != null, E_SYSTEM, "The method cannot proceed due to a severe system error."); + + if (pDbRow->hasData == true) + { + ++__currentRowIndex; + __pDbEnumeratorCache->__pCurrentDbRow = pDbRow; + } + else + { + return CacheRow(*pDbRow, __currentRowIndex + 1); + } + } + else + { + return this->CacheRow(); + } + } + + return r; +} + +result +_DbEnumeratorImpl::MovePrevious(void) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturn(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, E_INVALID_STATE, + "[E_INVALID_STATE] The method has tried to fetch the column data of a result set that is not activated."); + SysTryReturnResult(NID_IO, __currentRowIndex > 0, E_OUT_OF_RANGE, + "The Method has reached out of the result set."); + + // since no restriction on window size, this case should work all the times. + __pDbEnumeratorCache->__pCurrentDbRow = dynamic_cast< _DbRow* >(__pDbEnumeratorCache->__dbRowList.GetAt(__currentRowIndex - 1)); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + if (__pDbEnumeratorCache->__pCurrentDbRow->hasData == true) + { + __currentRowIndex--; + } + else + { + return CacheRow(*(__pDbEnumeratorCache->__pCurrentDbRow), __currentRowIndex - 1); + } + } + + return r; +} + +result +_DbEnumeratorImpl::MoveFirst(void) +{ + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + if (__pDbEnumeratorCache == null) // if called for the first time + { + return this->MoveNext(); + } + else + { + if (__currentRowIndex == 0) + { + return E_SUCCESS; // __pCurrentDbRow cursor is pointing to first row + } + else + { + __pDbEnumeratorCache->__pCurrentDbRow = dynamic_cast< _DbRow* >(__pDbEnumeratorCache->__dbRowList.GetAt(0)); + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + if (__pDbEnumeratorCache->__pCurrentDbRow->hasData == true) + { + __currentRowIndex = 0; + } + else + { + return CacheRow(*(__pDbEnumeratorCache->__pCurrentDbRow), 0); + } + } + else // this should not happen!! + { + // reset and do MoveNext() + delete __pDbEnumeratorCache; + __pDbEnumeratorCache = null; + __currentRowIndex = -1; + __rowCount = 0; + + result r = this->Reset(); // to call sqlite3_reset() + SysTryReturnResult(NID_IO, r == E_SUCCESS, r, "Propagated."); + + return this->MoveNext(); + } + } + } + + return E_SUCCESS; +} + +result +_DbEnumeratorImpl::MoveLast(void) +{ + result r = E_SUCCESS; + _DbRow* pDbRow = null; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + if (__pDbEnumeratorCache == null) // if called for the first time + { + // make a fisrt move + r = this->MoveNext(); + SysTryReturnResult(NID_IO, r == E_SUCCESS, r, "Propagated."); + + // cache all the rows + while (true) + { + r = this->CacheRow(); + if (r == E_OUT_OF_RANGE) + { + r = E_SUCCESS; + break; + } + } + } + else + { + if (__rowCount > 0 && __currentRowIndex == (__rowCount - 1)) + { + return E_SUCCESS; // already @last row. + } + + // move cursor from __currentRowIndex + 1 to the end of the row list. + for (int i = __currentRowIndex + 1; i < __pDbEnumeratorCache->__dbRowList.GetCount(); i++) + { + // find the missing row index + pDbRow = dynamic_cast< _DbRow* >(__pDbEnumeratorCache->__dbRowList.GetAt(i)); + if (pDbRow != null) + { + if (pDbRow->hasData == true) + { + __pDbEnumeratorCache->__pCurrentDbRow = pDbRow; + __currentRowIndex = i; + } + else + { + r = this->CacheRow(*pDbRow, i); + SysTryReturn(NID_IO, !(IsFailed(r)), r, r, "[%s] Propagated.", GetErrorMessage(r)); + } + } + else + { + break; + } + } + + if (__rowCount > 0 && __currentRowIndex == (__rowCount - 1)) + { + return E_SUCCESS; // __dbRowList contains all the rows and __currentRowIndex is @last row. + } + else + { + // cache remaining rows + while (true) + { + r = this->CacheRow(); + if (r == E_OUT_OF_RANGE) + { + r = E_SUCCESS; + break; + } + } + } + } + + return r; +} + +result +_DbEnumeratorImpl::Reset(void) +{ + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + result r = E_SUCCESS; + + if (__pDbEnumeratorCache != null) + { + // by resetting row offset and current row, can re-use the cache for later purpose. + __pDbEnumeratorCache->__pCurrentDbRow = null; + __currentRowIndex = -1; + } + else + { + ret = sqlite3_reset((sqlite3_stmt*) __pEnum); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (ret) + { + case E_INVALID_ARG: + case E_ILLEGAL_ACCESS: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + case E_INVALID_OPERATION: + case E_UNKNOWN: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to reset SQL statement. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + } + + return r; +} + +result +_DbEnumeratorImpl::GetIntAt(int columnIndex, int& value) const +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "Given column index is out of range."); + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (pDbColumn) + { + if (pDbColumn->type != SQLITE_INTEGER) + { + r = E_TYPE_MISMATCH; + SysLog(NID_IO, "[E_TYPE_MISMATCH] Trying to access column of different type."); + goto CATCH; + } + + value = *((int *)pDbColumn->pData.get()); + } + } + return E_SUCCESS; + +CATCH: + return r; +} + +result +_DbEnumeratorImpl::GetInt64At(int columnIndex, long long& value) const +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "Given column index is out of range."); + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (pDbColumn) + { + if (pDbColumn->type != SQLITE_INTEGER) + { + r = E_TYPE_MISMATCH; + SysLog(NID_IO, "[E_TYPE_MISMATCH] Trying to access column of different type."); + goto CATCH; + } + + value = *((long long *)pDbColumn->pData.get()); + } + } + return E_SUCCESS; + +CATCH: + return r; +} + +result +_DbEnumeratorImpl::GetDoubleAt(int columnIndex, double& value) const +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "Given column index is out of range."); + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (pDbColumn) + { + if (pDbColumn->type != SQLITE_FLOAT) + { + r = E_TYPE_MISMATCH; + SysLog(NID_IO, "[E_TYPE_MISMATCH] Trying to access column of different type."); + goto CATCH; + } + + value = *((double *)pDbColumn->pData.get()); + } + } + return E_SUCCESS; + +CATCH: + return r; +} + +result +_DbEnumeratorImpl::GetStringAt(int columnIndex, String& value) const +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "Given column index is out of range."); + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (pDbColumn) + { + if (pDbColumn->type != SQLITE_TEXT) + { + r = E_TYPE_MISMATCH; + SysLog(NID_IO, "[E_TYPE_MISMATCH] Trying to access column of different type."); + goto CATCH; + } + + value = String((const char*)pDbColumn->pData.get()); + } + } + return E_SUCCESS; + +CATCH: + return r; +} + +result +_DbEnumeratorImpl::GetBlobAt(int columnIndex, ByteBuffer& value) const +{ + result r = E_SUCCESS; + int blobLen = 0; + const byte* pBlob = null; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "Given column index is out of range."); + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (pDbColumn) + { + if (pDbColumn->type != SQLITE_BLOB) + { + r = E_TYPE_MISMATCH; + SysLog(NID_IO, "[E_TYPE_MISMATCH] Trying to access column of different type."); + goto CATCH; + } + + blobLen = pDbColumn->size; + pBlob = (const byte*)pDbColumn->pData.get(); + + r = value.SetArray(pBlob, 0, blobLen); + } + } + + // fall thru +CATCH: + return r; +} + +result +_DbEnumeratorImpl::GetBlobAt(int columnIndex, void* buffer, int size) const +{ + result r = E_SUCCESS; + int blobLen = 0; + const byte* pBlob = null; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "Given column index is out of range."); + SysTryReturnResult(NID_IO, buffer != null, E_INVALID_ARG, "Null pointer was passed."); + SysTryReturnResult(NID_IO, size > 0, E_INVALID_ARG, "Invalid size was passed."); + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (pDbColumn) + { + if (pDbColumn->type != SQLITE_BLOB) + { + r = E_TYPE_MISMATCH; + SysLog(NID_IO, "[E_TYPE_MISMATCH] Trying to access column of different type."); + goto CATCH; + } + + blobLen = pDbColumn->size; + pBlob = (const byte*)pDbColumn->pData.get(); + memcpy(buffer, pBlob, (blobLen < size) ? blobLen : size); + } + } + + if (size < blobLen) + { + r = E_OVERFLOW; + } + + // fall thru +CATCH: + return r; +} + +result +_DbEnumeratorImpl::GetDateTimeAt(int columnIndex, DateTime& value) const +{ + result r = E_SUCCESS; + const char* pStr = null; + + SysTryReturnResult(NID_IO, __pEnum != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + SysTryReturnResult(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, E_INVALID_ARG, + "Given column index is out of range."); + SysTryReturnResult(NID_IO, __pDbEnumeratorCache != null, E_INVALID_STATE, + "The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (pDbColumn) + { + if (pDbColumn->type != SQLITE_TEXT) + { + r = E_TYPE_MISMATCH; + SysLog(NID_IO, "[E_TYPE_MISMATCH] Trying to access column of different type."); + goto CATCH; + } + + pStr = (const char*) pDbColumn->pData.get(); + } + } + + r = DateTime::Parse(pStr, value); + + // fall thru +CATCH: + return r; +} + +int +_DbEnumeratorImpl::GetColumnCount(void) const +{ + SysTryReturn(NID_IO, __pEnum != null, -1, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + SysTryReturn(NID_IO, __pDbEnumeratorCache != null, -1, E_INVALID_STATE, + "[E_INVALID_STATE] The method has tried to fetch the column data of a result set that is not activated."); + + return __columnCount; +} + +DbColumnType +_DbEnumeratorImpl::GetColumnType(int columnIndex) const +{ + DbColumnType type = DB_COLUMNTYPE_UNDEFINED; + + SysTryReturn(NID_IO, __pEnum != null, DB_COLUMNTYPE_UNDEFINED, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, DB_COLUMNTYPE_UNDEFINED, E_INVALID_ARG, + "[E_INVALID_ARG] Given column index is out of range."); + + SysTryReturn(NID_IO, __pDbEnumeratorCache != null, DB_COLUMNTYPE_UNDEFINED, E_INVALID_STATE, + "[E_INVALID_STATE] The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (!pDbColumn) + { + SetLastResult(E_INVALID_STATE); + return DB_COLUMNTYPE_UNDEFINED; + } + switch (pDbColumn->type) + { + case SQLITE_INTEGER: + type = DB_COLUMNTYPE_INT; + break; + + case SQLITE_FLOAT: + type = DB_COLUMNTYPE_DOUBLE; + break; + + case SQLITE_TEXT: + type = DB_COLUMNTYPE_TEXT; + break; + + case SQLITE_BLOB: + type = DB_COLUMNTYPE_BLOB; + break; + + case SQLITE_NULL: + type = DB_COLUMNTYPE_NULL; + break; + + default: + SetLastResult(E_INVALID_STATE); + break; + } + } + + return type; +} + +String +_DbEnumeratorImpl::GetColumnName(int columnIndex) const +{ + SysTryReturn(NID_IO, __pEnum != null, null, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, null, E_INVALID_ARG, + "[E_INVALID_ARG] Given column index is out of range."); + + SysTryReturn(NID_IO, __pDbEnumeratorCache != null, null, E_INVALID_STATE, + "[E_INVALID_STATE] The method has tried to fetch the column data of a result set that is not activated."); + + String* pString = dynamic_cast (__pDbEnumeratorCache->__dbColumnNameList.GetAt(columnIndex)); + + if (!pString) + { + SetLastResult(E_INVALID_STATE); + return String(""); + } + + return String(pString->GetPointer()); +} + +int +_DbEnumeratorImpl::GetColumnSize(int columnIndex) const +{ + int bytes = 0; + + SysTryReturn(NID_IO, __pEnum != null, 0, E_INVALID_STATE, + "[E_INVALID_STATE] This instance has not been properly constructed yet or has already been finalized."); + + SysTryReturn(NID_IO, columnIndex >= 0 && columnIndex < __columnCount, 0, E_INVALID_ARG, + "[E_INVALID_ARG] Given column index is out of range."); + + SysTryReturn(NID_IO, __pDbEnumeratorCache != null, 0, E_INVALID_STATE, + "[E_INVALID_STATE] The method has tried to fetch the column data of a result set that is not activated."); + + if (__pDbEnumeratorCache->__pCurrentDbRow) + { + _DbColumn* pDbColumn = dynamic_cast < _DbColumn* >(__pDbEnumeratorCache->__pCurrentDbRow->dbValuesList.GetAt(columnIndex)); + if (!pDbColumn) + { + SetLastResult(E_INVALID_STATE); + return 0; + } + int columnType = pDbColumn->type; + + switch (columnType) + { + case SQLITE_INTEGER: + if (_AppInfo::IsOspCompat()) + { + bytes = sizeof(int); // for 2.0 compatibility + } + else + { + bytes = sizeof(long long); + } + break; + + case SQLITE_FLOAT: + bytes = sizeof(double); + break; + + case SQLITE_TEXT: + // fall thru + case SQLITE_BLOB: + bytes = pDbColumn->size; + break; + + default: + SetLastResult(E_INVALID_STATE); + break; + } + } + + return bytes; +} + +_DbEnumeratorImpl* +_DbEnumeratorImpl::GetInstance(DbEnumerator& dbEnumerator) +{ + return dbEnumerator.__pDbEnumeratorImpl; +} + +const _DbEnumeratorImpl* +_DbEnumeratorImpl::GetInstance(const DbEnumerator& dbEnumerator) +{ + return dbEnumerator.__pDbEnumeratorImpl; +} + +DbEnumerator* +_DbEnumeratorImpl::CreateDbEnumeratorInstanceN(void) +{ + unique_ptr pDbEnumerator(new (std::nothrow) DbEnumerator()); + SysTryReturn(NID_IO, pDbEnumerator != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + return pDbEnumerator.release(); +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DbStatementImpl.cpp b/src/io/FIo_DbStatementImpl.cpp new file mode 100644 index 0000000..7e26c5f --- /dev/null +++ b/src/io/FIo_DbStatementImpl.cpp @@ -0,0 +1,410 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DbStatementImpl.cpp + * @brief This is the implementation file for _DbStatementImpl class. + */ + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +_DbStatementImpl::_DbStatementImpl(void) + : __shouldReleaseResource(true) + , __pStmt(null) + , __pDatabase(null) +{ + __stmtType = DB_STATEMENT_TYPE_OTHER; +} + +_DbStatementImpl::~_DbStatementImpl(void) +{ + if (__shouldReleaseResource && __pStmt) + { + sqlite3_finalize((sqlite3_stmt*) __pStmt); + } +} + +result +_DbStatementImpl::BindInt(int columnIndex, int value) +{ + SysTryReturnResult(NID_IO, __pStmt != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + result r = E_SUCCESS; + + ret = sqlite3_bind_int((sqlite3_stmt*) __pStmt, columnIndex + 1, value); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to bind int value. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + + return r; +} + +result +_DbStatementImpl::BindInt64(int columnIndex, long long value) +{ + SysTryReturnResult(NID_IO, __pStmt != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + result r = E_SUCCESS; + + ret = sqlite3_bind_int64((sqlite3_stmt*) __pStmt, columnIndex + 1, value); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to bind int64 value. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + + return r; +} + +result +_DbStatementImpl::BindDouble(int columnIndex, double value) +{ + SysTryReturnResult(NID_IO, __pStmt != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + result r = E_SUCCESS; + + ret = sqlite3_bind_double((sqlite3_stmt*) __pStmt, columnIndex + 1, value); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to bind double value. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + + return r; +} + +result +_DbStatementImpl::BindString(int columnIndex, const String& value) +{ + SysTryReturnResult(NID_IO, __pStmt != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + char* pStr = null; + result r = E_SUCCESS; + + pStr = _StringConverter::CopyToCharArrayN(value); + if (pStr == null) + { + return GetLastResult(); + } + + ret = sqlite3_bind_text((sqlite3_stmt*) __pStmt, columnIndex + 1, pStr, strlen(pStr), SQLITE_TRANSIENT); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to bind text value. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + + delete[] pStr; + + return r; +} + +result +_DbStatementImpl::BindBlob(int columnIndex, const ByteBuffer& value) +{ + SysTryReturnResult(NID_IO, __pStmt != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + int size = 0; + result r = E_SUCCESS; + + size = value.GetLimit(); + if (size <= 0) + { + SysLog(NID_IO, + "[E_INVALID_ARG] ERROR Message: Wrong bind parameter. (Size of ByteBuffer should be greater than zero)"); + return E_INVALID_ARG; + } + + ret = sqlite3_bind_blob((sqlite3_stmt*) __pStmt, columnIndex + 1, value.GetPointer(), size, SQLITE_TRANSIENT); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to bind blob data. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + + return r; +} + +result +_DbStatementImpl::BindBlob(int columnIndex, const void* buffer, int size) +{ + SysTryReturnResult(NID_IO, __pStmt != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + result r = E_SUCCESS; + + ret = sqlite3_bind_blob((sqlite3_stmt*) __pStmt, columnIndex + 1, buffer, size, SQLITE_TRANSIENT); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to bind blob data. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + + return r; +} + +result +_DbStatementImpl::BindDateTime(int columnIndex, const DateTime& value) +{ + SysTryReturnResult(NID_IO, __pStmt != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + char* pStr = null; + result r = E_SUCCESS; + + pStr = _StringConverter::CopyToCharArrayN(value.ToString()); + if (pStr == null) + { + return GetLastResult(); + } + + ret = sqlite3_bind_text((sqlite3_stmt*) __pStmt, columnIndex + 1, pStr, strlen(pStr), SQLITE_TRANSIENT); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to bind text value. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + + delete[] pStr; + + return r; +} + +result +_DbStatementImpl::BindNull(int columnIndex) +{ + SysTryReturnResult(NID_IO, __pStmt != null, E_INVALID_STATE, + "The Object is not constructed or the database is already been closed."); + + int ret = 0; + result r = E_SUCCESS; + + ret = sqlite3_bind_null((sqlite3_stmt*) __pStmt, columnIndex + 1); + if (ret != SQLITE_OK) + { + if (!_AppInfo::IsOspCompat()) + { + r = __ConvertNativeSqliteErrorToDetailResult(ret); + switch (r) + { + case E_ILLEGAL_ACCESS: + case E_OBJECT_LOCKED: + case E_IO: + case E_INVALID_FORMAT: + case E_STORAGE_FULL: + r = E_SYSTEM; + break; + } + } + else + { + r = __ConvertNativeSqliteErrorToResult(ret); + } + + SysLog(NID_IO, "[%s] Failed to bind null. (%d, %s).", GetErrorMessage(r), + ret, sqlite3_errmsg(static_cast< sqlite3* >(__pDatabase))); + } + + return r; +} + +_DbStatementImpl* +_DbStatementImpl::GetInstance(DbStatement& dbStatement) +{ + return dbStatement.__pDbStatementImpl; +} + +const _DbStatementImpl* +_DbStatementImpl::GetInstance(const DbStatement& dbStatement) +{ + return dbStatement.__pDbStatementImpl; +} + +DbStatement* +_DbStatementImpl::CreateDbStatementInstanceN(void) +{ + std::unique_ptr pDbStatement(new (std::nothrow) DbStatement()); + SysTryReturn(NID_IO, pDbStatement != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + return pDbStatement.release(); +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DirEntryImpl.cpp b/src/io/FIo_DirEntryImpl.cpp new file mode 100644 index 0000000..e60b8f2 --- /dev/null +++ b/src/io/FIo_DirEntryImpl.cpp @@ -0,0 +1,197 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DirEntryImpl.cpp + * @brief This is the implementation file for _DirEntryImpl class. + */ + +#include +#include +#include +#include +#include + +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +_DirEntryImpl::_DirEntryImpl(void) + : __fileSize(0) + , __directory(false) + , __hidden(false) + , __readOnly(false) +{ +} + +_DirEntryImpl::~_DirEntryImpl(void) +{ +} + +_DirEntryImpl* +_DirEntryImpl::GetInstance(DirEntry* pDirEntry) +{ + if (pDirEntry) + { + return pDirEntry->__pDirEntryImpl; + } + + return null; +} + +const _DirEntryImpl* +_DirEntryImpl::GetInstance(const DirEntry* pDirEntry) +{ + if (pDirEntry) + { + return pDirEntry->__pDirEntryImpl; + } + + return null; +} + +_DirEntryImpl::_DirEntryImpl(const _DirEntryImpl& dirEntryImpl) + : __directory(false) + , __hidden(false) + , __readOnly(false) +{ + __dateTime = dirEntryImpl.__dateTime; + __fileSize = dirEntryImpl.__fileSize; + __name = dirEntryImpl.__name; + __directory = dirEntryImpl.__directory; + __hidden = dirEntryImpl.__hidden; + __readOnly = dirEntryImpl.__readOnly; +} + +_DirEntryImpl& +_DirEntryImpl::operator =(const _DirEntryImpl& dirEntryImpl) +{ + if (&dirEntryImpl != this) + { + __dateTime = dirEntryImpl.__dateTime; + __fileSize = dirEntryImpl.__fileSize; + __name = dirEntryImpl.__name; + __directory = dirEntryImpl.__directory; + __hidden = dirEntryImpl.__hidden; + __readOnly = dirEntryImpl.__readOnly; + } + + return *this; +} + +bool +_DirEntryImpl::Equals(const Object& object) const +{ + const _DirEntryImpl* pOther = dynamic_cast< const _DirEntryImpl* >(&object); + if (pOther == null) + { + return false; + } + + if (__dateTime == pOther->__dateTime && __fileSize == pOther->__fileSize && + __name == pOther->__name && __directory == pOther->__directory && + __hidden == pOther->__hidden && __readOnly == pOther->__readOnly) + { + return true; + } + + return false; +} + +int +_DirEntryImpl::GetHashCode(void) const +{ + String hashCode; + + hashCode.Append(__dateTime.ToString()); + hashCode.Append(static_cast< long >(__fileSize)); + hashCode.Append(__name); + hashCode.Append(static_cast< int >(__directory)); + hashCode.Append(static_cast< int >(__hidden)); + hashCode.Append(static_cast< int >(__readOnly)); + + return hashCode.GetHashCode(); +} + +const Tizen::Base::String +_DirEntryImpl::GetName(void) const +{ + SetLastResult(E_SUCCESS); + return __name; +} + +unsigned long +_DirEntryImpl::GetFileSize(void) const +{ + SetLastResult(E_SUCCESS); + return __fileSize; +} + +bool +_DirEntryImpl::IsDirectory(void) const +{ + SetLastResult(E_SUCCESS); + return __directory; +} + +bool +_DirEntryImpl::IsHidden(void) const +{ + SetLastResult(E_SUCCESS); + return __hidden; +} + +bool +_DirEntryImpl::IsReadOnly(void) const +{ + SetLastResult(E_SUCCESS); + return __readOnly; +} + +Tizen::Base::DateTime +_DirEntryImpl::GetDateTime(void) const +{ + SetLastResult(E_SUCCESS); + return __dateTime; +} + +void +_DirEntryImpl::Set(DateTime dateTime, unsigned long fileSize, String name, + bool dir, bool readOnly, bool hidden) +{ + __dateTime = dateTime; + __fileSize = fileSize; + __name = name; + __directory = dir; + __readOnly = readOnly; + __hidden = hidden; +} + +DirEntry* +_DirEntryImpl::CreateDirEntryInstanceN(void) +{ + std::unique_ptr pDirEntry(new (std::nothrow) DirEntry()); + SysTryReturn(NID_IO, pDirEntry != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + return pDirEntry.release(); +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DirEnumeratorImpl.cpp b/src/io/FIo_DirEnumeratorImpl.cpp new file mode 100644 index 0000000..d3ddf28 --- /dev/null +++ b/src/io/FIo_DirEnumeratorImpl.cpp @@ -0,0 +1,260 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DirEnumeratorImpl.cpp + * @brief This is the implementation file for _DirEnumeratorImpl class. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +static const int _BASE_YEAR = 1900; + +_DirEnumeratorImpl::_DirEnumeratorImpl(const String& dirPath) + : __validAccess(false) + , __pFileFindInfo(null) + , __pCurDirEntry(null) +{ + __validAccess = true; + __absoluteDirPath = dirPath; +} + +_DirEnumeratorImpl::_DirEnumeratorImpl(const _DirEnumeratorImpl& dirEnumeratorImpl) + : __validAccess(false) + , __pFileFindInfo(null) + , __pCurDirEntry(null) +{ + SysLogException(NID_IO, E_UNSUPPORTED_OPERATION, "[E_UNSUPPORTED_OPERATION] This copy constructor is not implemented."); + SetLastResult(E_UNSUPPORTED_OPERATION); +} + +_DirEnumeratorImpl& +_DirEnumeratorImpl::operator =(const _DirEnumeratorImpl& dirEnumeratorImpl) +{ + if (this != &dirEnumeratorImpl) + { + SysLogException(NID_IO, E_UNSUPPORTED_OPERATION, "[E_UNSUPPORTED_OPERATION] This assign operator is not implemented."); + SetLastResult(E_UNSUPPORTED_OPERATION); + } + return *this; +} + +_DirEnumeratorImpl::~_DirEnumeratorImpl(void) +{ + if (__pFileFindInfo) + { + closedir(static_cast (__pFileFindInfo)); + __pFileFindInfo = null; + } + + delete __pCurDirEntry; +} + +DirEntry +_DirEnumeratorImpl::GetCurrentDirEntry(void) const +{ + result r = E_SUCCESS; + + unique_ptr pDirEntry(_DirEntryImpl::CreateDirEntryInstanceN()); + DirEntry dirEntryObject = *pDirEntry; + + SysTryReturn(NID_IO, __pCurDirEntry != null, dirEntryObject, E_INVALID_STATE, + "[E_INVALID_STATE] Instance has not been created yet."); + + _DirEntryImpl::GetInstance(&dirEntryObject)->Set(__pCurDirEntry->GetDateTime(), + __pCurDirEntry->GetFileSize(), __pCurDirEntry->GetName(), __pCurDirEntry->IsDirectory(), + __pCurDirEntry->IsReadOnly(), __pCurDirEntry->IsHidden()); + + SetLastResult(r); + return dirEntryObject; +} + +Object* +_DirEnumeratorImpl::GetCurrent(void) const +{ + SetLastResult(E_SUCCESS); + return __pCurDirEntry; +} + +result +_DirEnumeratorImpl::MoveNext(void) +{ + result r = E_SUCCESS; + struct dirent dirEnt; + struct dirent* pDirEntResult = null; + struct stat statbuf; + struct tm* pTm = null; + DateTime dateTime; + int ret = 0; + String dirEntryPath; + bool hidden = false; + char* pDirEntryName = null; + + SysTryReturnResult(NID_IO, __validAccess == true, E_ILLEGAL_ACCESS, + "Given path cannot be accessed!"); + SysTryReturnResult(NID_IO, __absoluteDirPath.GetLength() > 0 && __absoluteDirPath.GetLength() <= PATH_MAX, + E_INVALID_ARG, "Invalid argument was passed. Given pattern length is not correct!"); + + unique_ptr pAbsDirPath(_StringConverter::CopyToCharArrayN(String(__absoluteDirPath))); + SysTryReturn(NID_IO, (pAbsDirPath != null), GetLastResult(), GetLastResult(), + "[%s] Invalid argument was passed. Given pattern length is not correct!", GetErrorMessage(GetLastResult())); + + if (__pFileFindInfo == null) + { + __pFileFindInfo = opendir(pAbsDirPath.get()); + if (__pFileFindInfo == null) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to open directory (%s), [%s].", GetErrorMessage(r), + GetErrorMessage((result) E_FILE_NOT_FOUND), pAbsDirPath.get()); + return r; + } + } + +//SKIP_DIR: + // move to next entry in the directory + errno = 0; + ret = readdir_r((DIR*) __pFileFindInfo, &dirEnt, &pDirEntResult); + SysTryReturn(NID_IO, (ret == 0), __ConvertNativeErrorToResult(errno), + __ConvertNativeErrorToResult(errno), "[%s] Failed to read next dir entry.", __ConvertNativeErrorToMessage(errno)); + + if (pDirEntResult == null) + { + return E_END_OF_FILE; // Complete reading the directory + } + + //if (dirEnt.d_name[0] == '.') + //{ + // goto SKIP_DIR; + //} + + // prepare entry path + dirEntryPath.Append(__absoluteDirPath); + dirEntryPath.Append(L"/"); + dirEntryPath.Append(dirEnt.d_name); + unique_ptr pAbsDirEntryPath(_StringConverter::CopyToCharArrayN(dirEntryPath)); + SysTryReturn(NID_IO, (pAbsDirEntryPath != null), GetLastResult(), GetLastResult(), + "[%s] Invalid argument was passed. Given pattern length is not correct!", GetErrorMessage(GetLastResult())); + + // get its details + ret = stat(pAbsDirEntryPath.get(), &statbuf); + SysTryReturn(NID_IO, (ret == 0), r = __ConvertNativeErrorToResult(errno), __ConvertNativeErrorToResult(errno), + "[%s] Failed to get attributes for dir entry (%s) whose absolute dirpath is (%s)with errno [%d].", + __ConvertNativeErrorToMessage(errno), dirEnt.d_name, pAbsDirPath.get(), errno); + + // time of last status change + pTm = localtime(&statbuf.st_ctime); + SysTryReturnResult(NID_IO, pTm != null, E_SYSTEM, "Failed to call localtime() (%s).", strerror(errno)); + r = dateTime.SetValue(_BASE_YEAR + pTm->tm_year, 1 + pTm->tm_mon, pTm->tm_mday, pTm->tm_hour, pTm->tm_min, pTm->tm_sec); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + if (__pCurDirEntry == null) + { + __pCurDirEntry = _DirEntryImpl::CreateDirEntryInstanceN(); + SysTryReturnResult(NID_IO, __pCurDirEntry != null, E_OUT_OF_MEMORY, + "DirEntry allocation failed."); + } + + pDirEntryName = &dirEnt.d_name[0]; + + // check for a hidden file/directory including . and .. + if (dirEnt.d_name[0] == '.') + { + hidden = true; + } + + _DirEntryImpl::GetInstance(__pCurDirEntry)->Set(dateTime, statbuf.st_size, String(dirEnt.d_name), + S_ISDIR(statbuf.st_mode), (statbuf.st_mode & S_IWUSR) ? false : true, hidden); + + return E_SUCCESS; +} + +result +_DirEnumeratorImpl::Reset(void) +{ + result r = E_SUCCESS; + + if (__pCurDirEntry) + { + delete __pCurDirEntry; + __pCurDirEntry = null; + } + + // close and reopen the dir + if (__pFileFindInfo) + { + closedir(static_cast (__pFileFindInfo)); + } + + unique_ptr pDirPathName(_StringConverter::CopyToCharArrayN(__absoluteDirPath)); + SysTryReturn(NID_IO, pDirPathName != null, GetLastResult(), GetLastResult(), + "[%s] Failed to close file.", GetErrorMessage(GetLastResult())); + + __pFileFindInfo = opendir(pDirPathName.get()); + if (__pFileFindInfo == null) + { + r = __ConvertNativeErrorToResult(errno); + SysLog(NID_IO, "[%s] Failed to open directory (%s).", GetErrorMessage(r), pDirPathName.get()); + } + + return r; +} + +_DirEnumeratorImpl* +_DirEnumeratorImpl::GetInstance(DirEnumerator& dirEnumerator) +{ + return dirEnumerator.__pDirEnumeratorImpl; +} + +const _DirEnumeratorImpl* +_DirEnumeratorImpl::GetInstance(const DirEnumerator& dirEnumerator) +{ + return dirEnumerator.__pDirEnumeratorImpl; +} + +DirEnumerator* +_DirEnumeratorImpl::CreateDirEnumeratorInstanceN(const String& dirPath) +{ + unique_ptr pDirEnumerator(new (std::nothrow) DirEnumerator(dirPath)); + SysTryReturn(NID_IO, pDirEnumerator != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + return pDirEnumerator.release(); +} + +}} // Tizen::Io + diff --git a/src/io/FIo_DirectoryImpl.cpp b/src/io/FIo_DirectoryImpl.cpp new file mode 100644 index 0000000..673ec90 --- /dev/null +++ b/src/io/FIo_DirectoryImpl.cpp @@ -0,0 +1,504 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DirectoryImpl.cpp + * @brief This is the implementation file for %_DirectoryImpl class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "FIo_FileImpl.h" +#include "FIo_DirectoryImpl.h" +#include "FIo_DirEnumeratorImpl.h" + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::App; +using namespace Tizen::System; + +namespace Tizen { namespace Io +{ + +_DirectoryImpl::_DirectoryImpl(void) + : __pDir(null) +{ +} + +_DirectoryImpl::~_DirectoryImpl(void) +{ + result r = E_SUCCESS; + + if (__pDir) + { + if (closedir(static_cast (__pDir)) != 0) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to close the file.", GetErrorMessage(r)); + } + + __pDir = null; + } +} + +result +_DirectoryImpl::Construct(const String& dirPath) +{ + result r = E_SUCCESS; + + SysAssertf(__pDir == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(dirPath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", dirPath.GetPointer()); + + unique_ptr pDirPath(_StringConverter::CopyToCharArrayN(dirPath)); + SysTryReturn(NID_IO, pDirPath != null, GetLastResult(), GetLastResult(), + "[%s] Invalid dir path.", GetErrorMessage(GetLastResult())); + + __pDir = opendir(pDirPath.get()); + if (__pDir == null) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to open directory (%s).", GetErrorMessage(r), pDirPath.get()); + goto CATCH; + } + + __dirPath = dirPath; + + return E_SUCCESS; + +CATCH: + + return r; +} + +DirEnumerator* +_DirectoryImpl::ReadN(void) +{ + SysAssertf(__pDir != null, "Not yet constructed. Construct() should be called before use.\n"); + + unique_ptr pDirEnum(_DirEnumeratorImpl::CreateDirEnumeratorInstanceN(__dirPath)); + SysTryReturn(NID_IO, pDirEnum != null, null, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + return pDirEnum.release(); +} + +result +_DirectoryImpl::Create(const String& dirPath, bool createParentDirsToo) +{ + result r = E_SUCCESS; + int ret = 0; + + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(dirPath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", dirPath.GetPointer()); + + unique_ptr pTempDirPath(_StringConverter::CopyToCharArrayN(dirPath)); + SysTryReturn(NID_IO, pTempDirPath != null, GetLastResult(), GetLastResult(), + "[%s] Invalid dir path.", GetErrorMessage(GetLastResult())); + + unique_ptr pDirPath(new (std::nothrow) char[strlen(pTempDirPath.get()) + 2]); + SysTryReturnResult(NID_IO, pDirPath != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + strcpy(pDirPath.get(), pTempDirPath.get()); + pDirPath[strlen(pTempDirPath.get())] = '/'; + pDirPath[strlen(pTempDirPath.get()) + 1] = '\0'; + + // By the time we are here.. we assume we have a legal path to create + // the below logic works under the assumption that the path name does not end with '/' + ret = mkdir(pDirPath.get(), S_IRUSR | S_IWUSR | S_IXUSR); + if (ret == -1) + { + // if parent directory does not exist and if we are asked to create them + if ((errno == ENOENT) && (createParentDirsToo == true)) + { + // move till we find the directory which does not exist + char* pPos = pDirPath.get(); + + // if the dir path starts with '/', skip it + if (*pPos == '/') + { + pPos++; + } + + // scan for the next path seperator ie., '/'. + while (1) + { + if (pPos && *pPos == '/') + { + *pPos = '\0'; + if (access(pDirPath.get(), F_OK) != 0) + { + break; + } + *pPos = '/'; + } + pPos++; + } + + // found a dir which is not present and realDirPath has that name + while (1) + { + ret = mkdir(pDirPath.get(), S_IRUSR | S_IWUSR | S_IXUSR); + if (ret == -1 && errno != EEXIST) + { + SysLog(NID_IO, "mkdir() failed. errno: %d (%s), path: %ls", + errno, strerror(errno), dirPath.GetPointer()); + r = _NativeError::ConvertNativeErrorToResult(errno, true); + goto CATCH; + } + + // find for the next dir path + *pPos = '/'; + + while (pPos && *pPos == '/') + { + pPos++; // skip all occurances of consecutive '/' from current position + } + + if (pPos == null) + { + goto CATCH; // E_SUCCESS + } + + pPos = strchr(pPos, '/'); + if (pPos != null) + { + *pPos = '\0'; + } + else + { + goto CATCH; // E_SUCCESS + } + } + } + else + { + if (errno == ENAMETOOLONG) + { + r = E_INVALID_ARG; + } + else + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + } + SysLog(NID_IO, "[%s] Failed to create directory (%s) errno: %d (%s).", + GetErrorMessage(r), dirPath.GetPointer(), errno, strerror(errno)); + goto CATCH; + } + } + + // fall through +CATCH: + + return r; +} + +result +_DirectoryImpl::Remove(const String& dirPath, bool recursive) +{ + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(dirPath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", dirPath.GetPointer()); + + result r = E_SUCCESS; + + if (_FileImpl::IsFileExist(dirPath) == false) + { + r = GetLastResult(); + if (!IsFailed(r)) + { + SysLog(NID_IO, "[E_FILE_NOT_FOUND] The directory path (%s) does not exist.", dirPath.GetPointer()); + r = E_FILE_NOT_FOUND; + } + else + { + SysPropagate(NID_IO, r); + } + return r; + } + + unique_ptr pDirPath(_StringConverter::CopyToCharArrayN(dirPath)); + SysTryReturnResult(NID_IO, pDirPath != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + char resolvedPath[PATH_MAX] = {0,}; + if (realpath(pDirPath.get(), resolvedPath) == null) + { + switch (errno) + { + case EACCES: + r = E_ILLEGAL_ACCESS; + break; + case EINVAL: + // fall through + case ELOOP: + // fall through + case ENAMETOOLONG: + // fall through + case ENOTDIR: + r = E_INVALID_ARG; + break; + case EIO: + r = E_IO; + break; + case ENOENT: + r = E_FILE_NOT_FOUND; + break; + default: + r = E_SYSTEM; + break; + } + + SysLog(NID_IO, "[%s] Failed to produce canonical absolute path (%ls). errno: %d (%s)", + GetErrorMessage(r), dirPath.GetPointer(), errno, strerror(errno)); + + return r; + } + + int ret = rmdir(resolvedPath); + if (ret == -1) + { + switch (errno) + { + case EACCES: + // fall through + case EPERM: + r = E_ILLEGAL_ACCESS; + break; + case EINVAL: + // fall through + case ELOOP: + // fall through + case ENAMETOOLONG: + // fall through + case ENOTDIR: + r = E_INVALID_ARG; + break; + case ENOENT: + r = E_FILE_NOT_FOUND; + break; + case ENOMEM: + r = E_OUT_OF_MEMORY; + break; + case ENOTEMPTY: + if (recursive) + { + r = RemoveRecursively(resolvedPath); + } + else + { + r = E_FILE_ALREADY_EXIST; + } + break; + default: + r = E_SYSTEM; + break; + } + if (IsFailed(r)) + { + SysLog(NID_IO, "[%s] Failed to remove the directory path (%ls). errno: %d (%s)", + GetErrorMessage(r), dirPath.GetPointer(), errno, strerror(errno)); + } + } + + return r; +} + +result +_DirectoryImpl::Rename(const String& orgDirPath, const String& newDirPath) +{ + result r = E_SUCCESS; + int ret = 0; + + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(orgDirPath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", orgDirPath.GetPointer()); + SysTryReturnResult(NID_IO, _FileImpl::VerifyFilePathCompatibility(newDirPath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", newDirPath.GetPointer()); + + if (_FileImpl::IsFileExist(newDirPath)) + { + return E_FILE_ALREADY_EXIST; + } + + unique_ptr pOldpath(_StringConverter::CopyToCharArrayN(orgDirPath)); + SysTryReturn(NID_IO, (null != pOldpath), GetLastResult(), GetLastResult(), "[%s] Invalid old file path.", GetErrorMessage(GetLastResult())); + + unique_ptr pNewpath(_StringConverter::CopyToCharArrayN(newDirPath)); + SysTryReturn(NID_IO, (null != pNewpath), GetLastResult(), GetLastResult(), "[%s] Invalid new file path.", GetErrorMessage(GetLastResult())); + + ret = rename(pOldpath.get(), pNewpath.get()); + if (ret != 0) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "errno[%d], [%s] could not rename dirpath [%s].", errno, GetErrorMessage(r), pOldpath.get()); + } + + return r; +} + +result +_DirectoryImpl::RemoveRecursively(char* pDirPath) +{ + SysTryReturnResult(NID_IO, pDirPath != null, E_INVALID_ARG, "pDirPath is null."); + + DIR* pDir = null; + result r = E_SUCCESS; + + pDir = opendir(pDirPath); + if (pDir == null) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to open directory (%s).", GetErrorMessage(r), pDirPath); + goto CATCH; + } + + while (1) + { + struct dirent dirEnt; + struct dirent* pDirEntResult = null; + char *pDirEntryName = null; + + int ret = readdir_r(pDir, &dirEnt, &pDirEntResult); + if (ret != 0) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to read sub-directories. errno: %d (%s)", + GetErrorMessage(r), errno, strerror(errno)); + goto CATCH; + } + + // Remove all entries in dir. Delete the dir. + if (pDirEntResult == null) + { + ret = rmdir(pDirPath); + if (ret != 0) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to remove a directory. errno: %d (%s)", + GetErrorMessage(r), errno, strerror(errno)); + } + goto CATCH; // both success and fail + } + + pDirEntryName = &dirEnt.d_name[0]; + + // skip . and .. + if ((*pDirEntryName == '.' && *(pDirEntryName + 1) == 0x00) || (*pDirEntryName == '.' && *(pDirEntryName + 1) == '.' && *(pDirEntryName + 2) == 0x00)) + { + continue; + } + + // if the path name has '/' at the end remove it. + size_t len = strlen(pDirPath); + if (pDirPath[len - 1] == '/') + { + pDirPath[len - 1] = '\0'; + } + + // read_dir return relative path. Turn it to absolute + int parentDirLen = strlen(pDirPath); + int currEntryLen = strlen(dirEnt.d_name); + + char absPath[parentDirLen + currEntryLen + 2]; // 2 - for '/' and '\0' + + strcpy(absPath, pDirPath); + strcat(absPath, "/"); + strcat(absPath, dirEnt.d_name); + //SysLog(NID_IO, "entry name: %s", absPath); + + struct stat statbuf; + memset(&statbuf, 0, sizeof(struct stat)); + if (lstat(absPath, &statbuf) == -1) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to get file status. errno: %d (%s)", + GetErrorMessage(r), errno, strerror(errno)); + goto CATCH; + } + if (!S_ISLNK(statbuf.st_mode)) + { + if (stat(absPath, &statbuf) < 0) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to get file status. errno: %d (%s)", + GetErrorMessage(r), errno, strerror(errno)); + goto CATCH; + } + } + + if (S_ISDIR(statbuf.st_mode)) + { + r = _DirectoryImpl::RemoveRecursively(absPath); + if (IsFailed(r)) + { + goto CATCH; + } + } + else + { + ret = remove(absPath); + if (ret < 0) + { + r = _NativeError::ConvertNativeErrorToResult(errno, true); + SysLog(NID_IO, "[%s] Failed to remove file (%s)", GetErrorMessage(r), absPath); + goto CATCH; + } + } + } + + // fall through +CATCH: + if (pDir) + { + closedir(pDir); + } + + return r; +} + +_DirectoryImpl* +_DirectoryImpl::GetInstance(Directory& directory) +{ + return directory.__pDirectoryImpl; +} + +const _DirectoryImpl* +_DirectoryImpl::GetInstance(const Directory& directory) +{ + return directory.__pDirectoryImpl; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_FileAttributesImpl.cpp b/src/io/FIo_FileAttributesImpl.cpp new file mode 100644 index 0000000..61316e8 --- /dev/null +++ b/src/io/FIo_FileAttributesImpl.cpp @@ -0,0 +1,187 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_FileAttributesImpl.cpp + * @brief This is the implementation file for _FileAttributesImpl class. + */ + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +_FileAttributesImpl::_FileAttributesImpl(void) + : __fileSize(0) + , __directory(false) + , __hidden(false) + , __readOnly(false) +{ +} + +_FileAttributesImpl::~_FileAttributesImpl(void) +{ +} + +_FileAttributesImpl::_FileAttributesImpl(const _FileAttributesImpl& fileAttributesImpl) + : __fileSize(0) + , __directory(false) + , __hidden(false) + , __readOnly(false) +{ + __fileSize = fileAttributesImpl.__fileSize; + __directory = fileAttributesImpl.__directory; + __hidden = fileAttributesImpl.__hidden; + __readOnly = fileAttributesImpl.__readOnly; + __creationTime = fileAttributesImpl.__creationTime; + __lastModifiedTime = fileAttributesImpl.__lastModifiedTime; +} + +_FileAttributesImpl& +_FileAttributesImpl::operator =(const _FileAttributesImpl& fileAttributesImpl) +{ + if (&fileAttributesImpl != this) + { + __fileSize = fileAttributesImpl.__fileSize; + __directory = fileAttributesImpl.__directory; + __hidden = fileAttributesImpl.__hidden; + __readOnly = fileAttributesImpl.__readOnly; + __creationTime = fileAttributesImpl.__creationTime; + __lastModifiedTime = fileAttributesImpl.__lastModifiedTime; + } + + return *this; +} + +_FileAttributesImpl* +_FileAttributesImpl::GetInstance(FileAttributes& fileAttributes) +{ + return fileAttributes.__pFileAttributesImpl; +} + +const _FileAttributesImpl* +_FileAttributesImpl::GetInstance(const FileAttributes& fileAttributes) +{ + return fileAttributes.__pFileAttributesImpl; +} + +bool +_FileAttributesImpl::Equals(const Object& object) const +{ + const _FileAttributesImpl* pOther = dynamic_cast< const _FileAttributesImpl* >(&object); + if (pOther == null) + { + return false; + } + + if (__fileSize == pOther->__fileSize && __directory == pOther->__directory && + __hidden == pOther->__hidden && __readOnly == pOther->__readOnly && + __creationTime == pOther->__creationTime && __lastModifiedTime == pOther->__lastModifiedTime) + { + return true; + } + + return false; +} + +int +_FileAttributesImpl::GetHashCode(void) const +{ + String hashCode; + + hashCode.Append(static_cast< long >(__fileSize)); + hashCode.Append(static_cast< int >(__directory)); + hashCode.Append(static_cast< int >(__hidden)); + hashCode.Append(static_cast< int >(__readOnly)); + hashCode.Append(__creationTime.ToString()); + hashCode.Append(__lastModifiedTime.ToString()); + + return hashCode.GetHashCode(); +} + +long long +_FileAttributesImpl::GetFileSize(void) const +{ + SetLastResult(E_SUCCESS); + return __fileSize; +} + +DateTime +_FileAttributesImpl::GetDateTime(void) const +{ + SetLastResult(E_SUCCESS); + return __creationTime; +} + +DateTime +_FileAttributesImpl::GetLastModifiedTime(void) const +{ + SetLastResult(E_SUCCESS); + return __lastModifiedTime; +} + +bool +_FileAttributesImpl::IsDirectory(void) const +{ + SetLastResult(E_SUCCESS); + return __directory; +} + +bool +_FileAttributesImpl::IsHidden(void) const +{ + SetLastResult(E_SUCCESS); + return __hidden; +} + +bool +_FileAttributesImpl::IsReadOnly(void) const +{ + SetLastResult(E_SUCCESS); + return __readOnly; +} + +void +_FileAttributesImpl::Set(const DateTime& dateTime, const DateTime& modifiedTime, long long fileSize, + unsigned long attribute, bool hidden) +{ + __fileSize = fileSize; + __directory = S_ISDIR(attribute) ? true : false; + __hidden = hidden; + __readOnly = (attribute & (S_IWUSR)) ? false : true; + + __creationTime = dateTime; + __lastModifiedTime = modifiedTime; + + SetLastResult(E_SUCCESS); +} + +}} // Tizen::Io + diff --git a/src/io/FIo_FileEventManagerImpl.cpp b/src/io/FIo_FileEventManagerImpl.cpp new file mode 100644 index 0000000..a2ed063 --- /dev/null +++ b/src/io/FIo_FileEventManagerImpl.cpp @@ -0,0 +1,336 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_FileEventManager.cpp + * @brief This is the implementation file for FileEventManager class. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define INOTIFY_BUFFER_LEN (1024*(sizeof(struct inotify_event) + 16)) + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +_FileEventManagerImpl::_FileEventManagerImpl(void) + : __pMonitorFileList(null) + , __pFileEventListener(null) + , __inotifyFd(-1) + , __pGSource(null) + , __pGIOChannel(null) +{ +} + +_FileEventManagerImpl::~_FileEventManagerImpl(void) +{ + if (__inotifyFd != -1) + { + close(__inotifyFd); + } + + if (__pGIOChannel != null) + { + g_io_channel_unref(__pGIOChannel); + } + + if (__pGSource != null) + { + g_source_destroy(__pGSource); + g_source_unref(__pGSource); + } + + if (__pMonitorFileList != null) + { + __pMonitorFileList->RemoveAll(true); + delete __pMonitorFileList; + } +} + +gboolean +_FileEventManagerImpl::OnFileEventOccured(GIOChannel* source, GIOCondition condition, gpointer data) +{ + _FileEventManagerImpl* pFileEventManagerImpl = (_FileEventManagerImpl*)data; + + pFileEventManagerImpl->SendEvent(); + + return true; +} + +result +_FileEventManagerImpl::SendEvent(void) +{ + unsigned long iter = 0; + ssize_t length = 0; + char buffer[INOTIFY_BUFFER_LEN] = {0,}; + + unsigned long event = 0; + String path; + unsigned int eventId = 0; + result r = E_IO; + + SysTryReturnResult(NID_IO, __inotifyFd != -1, E_IO, "Failed to inotify."); + + length = read(__inotifyFd, buffer, INOTIFY_BUFFER_LEN -1); + SysTryReturnResult(NID_IO, length < (long)INOTIFY_BUFFER_LEN, E_IO, "Read buffer has failed."); + + while (iter < static_cast (length)) + { + struct inotify_event* pEvent = (struct inotify_event*)&buffer[iter]; + SysTryReturnResult(NID_IO, pEvent != null, E_IO, "Event info not found."); + event = (unsigned long)pEvent->mask; + eventId = pEvent->cookie; + + if (pEvent->len) + { + path = pEvent->name; + } + else + { + path = GetRegisteredPath(pEvent->wd); + } + + if (__pFileEventListener != null) + { + __pFileEventListener->OnFileEventOccured(event, path, eventId); + r = E_SUCCESS; + } + + iter += sizeof(struct inotify_event) + pEvent->len; + } + + return r; +} + +result +_FileEventManagerImpl::Construct(IFileEventListener& listener) +{ + GMainContext* pGContext = null; + result r = E_SUCCESS; + __inotifyFd = inotify_init(); + + if (__inotifyFd == -1 && errno == EMFILE) + { + SysLogException(NID_IO, E_MAX_EXCEEDED, "The number of opened files has exceeded the maximum limit."); + return E_MAX_EXCEEDED; + } + SysTryReturnResult(NID_IO, __inotifyFd != -1, E_IO, "Failed to init inotify."); + + unique_ptr pMonitorFileList(new (std::nothrow) HashMap()); + SysTryCatch(NID_IO, pMonitorFileList != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to create monitored file list."); + + r = pMonitorFileList->Construct(); + SysTryCatch(NID_IO, r == E_SUCCESS, , r, "[%s] Propagated.", GetErrorMessage(r)); + + pGContext = g_main_context_get_thread_default(); //get own gmain context except default thread + + if (pGContext == null) + { + pGContext = g_main_context_default(); //get gmain context from me (default) + SysTryCatch(NID_IO, pGContext != null, r = E_IO, E_IO, "[E_IO] Failed to get glib context."); + } + + SysLog(NID_IO, "GContext:%x", pGContext); + + __pFileEventListener = &listener; + + __pGIOChannel = g_io_channel_unix_new(__inotifyFd); //fd wrapping + SysTryCatch(NID_IO, __pGIOChannel != null, r = E_IO, E_IO, "[E_IO] Failed to create glib channel."); + SysLog(NID_IO, "__pGIOChannel:%x", __pGIOChannel); + + __pGSource = g_io_create_watch(__pGIOChannel, (GIOCondition)(G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP)); + SysTryCatch(NID_IO, __pGSource != null, r = E_IO, E_IO, "[E_IO] Failed to create glib watch."); + SysLog(NID_IO, "__pGSource:%x", __pGSource); + + g_source_set_callback(__pGSource, (GSourceFunc)OnFileEventOccured, this, NULL); + g_source_attach(__pGSource, pGContext); + SysLog(NID_IO, "Attached fd on g_source"); + + __pMonitorFileList = pMonitorFileList.release(); + + // fall thru +CATCH: + if (r != E_SUCCESS) + { + if (__inotifyFd != -1) + { + close(__inotifyFd); + } + + if (__pGIOChannel != null) + { + g_io_channel_unref(__pGIOChannel); + __pGIOChannel = null; + } + + if (__pGSource != null) + { + g_source_destroy(__pGSource); + g_source_unref(__pGSource); + __pGSource = null; + } + } + + return r; +} + +result +_FileEventManagerImpl::AddPath(const String& path, unsigned long eventsToMonitor) +{ + int monitoredFd = 0; + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, File::IsFileExist(path) == true, E_FILE_NOT_FOUND, + "path[%ls] dose not exist.", path.GetPointer()); + + SysLog(NID_IO, "path:%ls", path.GetPointer()); + + unique_ptr pPath(_StringConverter::CopyToCharArrayN(path)); + SysTryReturnResult(NID_IO, pPath != null, E_IO, "String covert is failed."); + + monitoredFd = inotify_add_watch(__inotifyFd, pPath.get(), eventsToMonitor); + + if (monitoredFd == -1) + { + r = E_IO; + switch (errno) + { + case EACCES: + SysLogException(NID_IO, E_IO, "Read access to the given file[%s] is not permitted.", pPath.get()); + r = E_ILLEGAL_ACCESS; + break; + case EFAULT: + SysLogException(NID_IO, E_IO, "The path[%s] points outside of the process's accessible address space.", pPath.get()); + r = E_ILLEGAL_ACCESS; + break; + case EBADF: + SysLogException(NID_IO, E_IO, "The given file descriptor is not valid."); + break; + case EINVAL: + SysLogException(NID_IO, E_INVALID_ARG, "The given event mask contains no valid events; or fd is not an inotify file descriptor."); + r = E_INVALID_ARG; + break; + case ENOMEM: + SysLogException(NID_IO, E_IO, "Insufficient kernel memory was available."); + break; + case ENOSPC: + SysLogException(NID_IO, E_IO, "The user limit on the total number of inotify watches was reached or the kernel failed to allocate a needed resource"); + break; + default: + break; + } + + return r; + } + + unique_ptr pMonitoredPath(new (std::nothrow) String(path)); + unique_ptr pMonitoredFd(new (std::nothrow) Integer(monitoredFd)); + SysTryReturnResult(NID_IO, pMonitoredPath != null && pMonitoredFd != null, E_IO, "Failed to allocate memory"); + + SysTryReturnResult(NID_IO, __pMonitorFileList != null, E_IO, "Monitored file list is null"); + + r = __pMonitorFileList->Add(*pMonitoredPath.release(), *pMonitoredFd.release()); + SysTryReturnResult(NID_IO, r == E_SUCCESS || r == E_OBJ_ALREADY_EXIST, E_IO, "Failed to add on monitored list."); + + return r; +} + +result +_FileEventManagerImpl::RemovePath(const String& path) +{ + Integer* pMonitoredFd = null; + + SysTryReturnResult(NID_IO, __pMonitorFileList != null, E_IO, "Monitored file list is null"); + + pMonitoredFd = (Integer*)__pMonitorFileList->GetValue(path); + + SysTryReturnResult(NID_IO, pMonitoredFd != null, E_IO, "path[%ls] is not registered.", path.GetPointer()); + + SysTryReturnResult(NID_IO, inotify_rm_watch(__inotifyFd, pMonitoredFd->ToInt()) == 0, + E_IO, "path[%ls] is not registered.", path.GetPointer()); + + SysTryReturnResult(NID_IO, __pMonitorFileList->Remove(path, true) == E_SUCCESS, + E_IO, "path[%ls] is not registered.", path.GetPointer()); + return E_SUCCESS; +} + +String +_FileEventManagerImpl::GetRegisteredPath(int fd) +{ + String* pRegisteredPath = null; + Integer* pRegisteredFD = null; + + if (__pMonitorFileList == null) + { + SysLog(NID_IO, "There is no path for fd:%d", fd); + return ""; + } + + unique_ptr pEnumerator(__pMonitorFileList->GetMapEnumeratorN()); + SysTryReturn(NID_IO, pEnumerator != null, L"", GetLastResult(), "[%s] Monitored file list is empty", GetErrorMessage(GetLastResult())); + + while (pEnumerator && pEnumerator->MoveNext() == E_SUCCESS) + { + pRegisteredPath = static_cast (pEnumerator->GetKey()); + pRegisteredFD = static_cast (pEnumerator->GetValue()); + + if (fd == pRegisteredFD->ToInt()) + { + SysLog(NID_IO, "Path is %ls", pRegisteredPath->GetPointer()); + return *pRegisteredPath; + } + + } + + SysLog(NID_IO, "There is no path for fd:%d", fd); + return ""; +} + +_FileEventManagerImpl* +_FileEventManagerImpl::GetInstance(FileEventManager& fileEventManager) +{ + return fileEventManager.__pFileEventManagerImpl; +} + +const _FileEventManagerImpl* +_FileEventManagerImpl::GetInstance(const FileEventManager& fileEventManager) +{ + return fileEventManager.__pFileEventManagerImpl; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_FileImpl.cpp b/src/io/FIo_FileImpl.cpp new file mode 100644 index 0000000..6b96261 --- /dev/null +++ b/src/io/FIo_FileImpl.cpp @@ -0,0 +1,1383 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_FileImpl.cpp + * @brief This is the implementation file for %_FileImpl class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "FIo_FileImpl.h" +#include "FIo_NormalFile.h" +#include "FIo_DirectoryImpl.h" +#include "FIo_SecureFile.h" +#include "FIo_SecureIoUtil.h" +#include "FIo_IFileCore.h" +#include "FIo_FileUtil.h" + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::App; +using namespace Tizen::System; + +namespace Tizen { namespace Io +{ + +static const int _MAX_PATH_LENGTH = 128; +static const int _APP_UID = 5000; +static const size_t _MAX_FILE_OPENMODE_LENGTH = 3; +static const char _INTERNAL_MOUNT_FLAG[] = "/tmp/osp-compat/mount/internal"; +static const char _EXTERNAL_MOUNT_FLAG[] = "/tmp/osp-compat/mount/external"; + +struct _OspDir +{ + char path[_MAX_PATH_LENGTH]; + mode_t mode; + bool appPrivilege; // false: root privilege +}; + +struct _LinkDir +{ + char srcPath[_MAX_PATH_LENGTH]; + char destPath[_MAX_PATH_LENGTH]; +}; + +struct _PathInfo +{ + char destPath[_MAX_PATH_LENGTH]; +}; + +_FileImpl::_FileImpl(void) + : __pCore(null) + , __read(false) + , __write(false) + , __truncate(false) + , __append(false) +{ +} + +_FileImpl::~_FileImpl(void) +{ + delete __pCore; +} + +_FileImpl::_FileImpl(const _FileImpl& fileImpl) + : __pCore(null) + , __read(false) + , __write(false) + , __truncate(false) + , __append(false) +{ + SysAssertf(false, "_FileImpl class does not support copy constructor.\n"); +} + +_FileImpl& +_FileImpl::operator =(const _FileImpl& fileImpl) +{ + SysAssertf(false, "_FileImpl class does not support '=' operator.\n"); + + if (&fileImpl == this) + { + return *this; + } + + return *this; +} + +bool +_FileImpl::VerifyFileOpenMode(const char* pOpenMode) +{ + if (pOpenMode == null) + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode is null."); + return false; + } + + if (strlen(pOpenMode) > _MAX_FILE_OPENMODE_LENGTH) + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + + switch (pOpenMode[0]) + { + case 'r': + __read = true; + break; + case 'w': + __write = true; + __truncate = true; + break; + case 'a': + __write = true; + __append = true; + break; + default: + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + + switch (pOpenMode[1]) + { + case '\0': + break; + case '+': + if (pOpenMode[2] == '\0' || pOpenMode[2] == 'b') + { + __read = true; + __write = true; + break; + } + else + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + case 'b': + if (pOpenMode[2] == '\0') + { + break; + } + else if (pOpenMode[2] == '+') + { + __read = true; + __write = true; + break; + } + else + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + default: + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + + return true; +} + +result +_FileImpl::Construct(const String& filePath, const String& openMode, bool createParentDirsToo, const ByteBuffer* pSecretKey) +{ + SysAssertf(__pCore == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + result r = E_SUCCESS; + + if (openMode.Contains(L'r') == true) + { + SysTryReturnResult(NID_IO, !createParentDirsToo, E_INVALID_ARG, + "The specified createParentDirsToo cannot be used without file creation mode."); + } + + if (createParentDirsToo == true) + { + String dirPath; + int position = 0; + + r = filePath.LastIndexOf(L'/', filePath.GetLength() - 1, position); + SysTryReturnResult(NID_IO, r != E_OBJ_NOT_FOUND, E_INVALID_ARG, "The specified filePath is invalid."); + SysTryReturnResult(NID_IO, !(position == 0), E_INVALID_ARG, "The specified filePath is invalid."); + + r = filePath.SubString(0, position, dirPath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to extract dir path.", GetErrorMessage(r)); + + r = Directory::Create(dirPath, true); + if (IsFailed(r)) + { + if (r == E_FILE_ALREADY_EXIST) + { + r = E_SUCCESS; + } + else + { + SysPropagate(NID_IO, r); + return r; + } + } + } + + unique_ptr pOpenMode(_StringConverter::CopyToCharArrayN(openMode)); + SysTryReturnResult(NID_IO, pOpenMode != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + return Construct(filePath, pOpenMode.get(), pSecretKey); +} + +result +_FileImpl::Construct(const String& filePath, const char* pOpenMode, const ByteBuffer* pSecretKey) +{ + SysAssertf(__pCore == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + result r = E_SUCCESS; + + bool isValidOpenMode = VerifyFileOpenMode(pOpenMode); + SysTryReturnResult(NID_IO, isValidOpenMode == true, E_INVALID_ARG, "The specified openMode is invalid. (%s)", pOpenMode); + + SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", filePath.GetPointer()); + + if (!__truncate && IsFileExist(filePath)) + { + r = _SecureIoUtil::CheckSecureFileHeader(filePath, pSecretKey); + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + if (pSecretKey == null) + { + unique_ptr<_NormalFile> pNormalFile(new (std::nothrow) _NormalFile()); + SysTryReturnResult(NID_IO, pNormalFile, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pNormalFile->Construct(filePath, pOpenMode); + SysTryReturn(NID_IO, !IsFailed(r), r , r, "[%s] Propagated.", GetErrorMessage(r)); + __pCore = pNormalFile.release(); + } + else + { + unique_ptr<_SecureFile> pSecureFile(new (std::nothrow) _SecureFile(__read, __write, __truncate, __append)); + SysTryReturnResult(NID_IO, pSecureFile, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pSecureFile->Construct(filePath, pOpenMode, pSecretKey); + SysTryReturn(NID_IO, !IsFailed(r), r , r, "[%s] Propagated.", GetErrorMessage(r)); + __pCore = pSecureFile.release(); + } + + return E_SUCCESS; +} + +result +_FileImpl::ReadN(char** buffer, int& length) +{ + result r = E_SUCCESS; + if (__pCore != null) + { + _NormalFile* pNormalFile = dynamic_cast< _NormalFile* > (__pCore); + if (pNormalFile != null) + { + r = pNormalFile->ReadN(buffer, length); + } + } + else + { + r = E_INVALID_OPERATION; + } + + return r; +} + +result +_FileImpl::Read(ByteBuffer& buffer) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __read == true, E_ILLEGAL_ACCESS, "File is not opened for reading."); + return __pCore->Read(buffer); +} + +int +_FileImpl::Read(void* buffer, int length) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, __read == true, 0, E_ILLEGAL_ACCESS, "[E_ILLEGAL_ACCESS] File is not opened for reading."); + return __pCore->Read(buffer, length); +} + +result +_FileImpl::Read(String& buffer) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __read == true, E_ILLEGAL_ACCESS, "File is not opened for reading."); + return __pCore->Read(buffer); +} + +result +_FileImpl::Write(const ByteBuffer& buffer) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __write == true, E_ILLEGAL_ACCESS, "File is not opened for writing."); + return __pCore->Write(buffer); +} + +result +_FileImpl::Write(const void* buffer, int length) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __write == true, E_ILLEGAL_ACCESS, "File is not opened for writing."); + return __pCore->Write(buffer, length); +} + +result +_FileImpl::Write(const String& buffer) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __write == true, E_ILLEGAL_ACCESS, "File is not opened for writing."); + return __pCore->Write(buffer); +} + +result +_FileImpl::Flush(void) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pCore->Flush(); +} + +int +_FileImpl::Tell(void) const +{ + SysTryReturnResult(NID_IO, __pCore != null, -1, "File is not constructed! Construct destined file first! "); + return __pCore->Tell(); +} + +result +_FileImpl::Seek(FileSeekPosition position, long offset) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pCore->Seek(position, offset); +} + +result +_FileImpl::Truncate(int length) +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, __write == true, E_ILLEGAL_ACCESS, "File is not opened for writing."); + return __pCore->Truncate(length); +} + +String +_FileImpl::GetName(void) const +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pCore->GetName(); +} + +FILE* +_FileImpl::GetFilePointer(void) const +{ + SysAssertf(__pCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pCore->GetFilePointer(); +} + +result +_FileImpl::Remove(const String& filePath) +{ + SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", filePath.GetPointer()); + return _FileUtil::Remove(filePath); +} + +result +_FileImpl::Move(const String& oldFilePath, const String& newFilePath) +{ + SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(oldFilePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", oldFilePath.GetPointer()); + + SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(newFilePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", newFilePath.GetPointer()); + return _FileUtil::Move(oldFilePath, newFilePath); +} + +result +_FileImpl::Copy(const String& srcFilePath, const String& destFilePath, bool failIfExist) +{ + SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(srcFilePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", srcFilePath.GetPointer()); + + SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(destFilePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", destFilePath.GetPointer()); + return _FileUtil::Copy(srcFilePath, destFilePath, failIfExist); +} + +result +_FileImpl::GetAttributes(const String& filePath, FileAttributes& attribute) +{ + SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, " [%ls] is not compatible.", filePath.GetPointer()); + return _FileUtil::GetAttributes(filePath, attribute); +} + +String +_FileImpl::GetFileName(const String& filePath) +{ + String fileName; + SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, fileName, E_INVALID_ARG, + "[E_INVALID_ARG] The length of the specified filePath (%ls) is zero or exceeds system limitations.", + filePath.GetPointer()); + + return _FileUtil::GetFileName(filePath); +} + +String +_FileImpl::GetFileExtension(const String& filePath) +{ + String extName; + SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, extName, E_INVALID_ARG, + "[E_INVALID_ARG] The length of the specified filePath (%ls) is zero or exceeds system limitations.", + filePath.GetPointer()); + + return _FileUtil::GetFileExtension(filePath); +} + +bool +_FileImpl::IsFileExist(const String& filePath) +{ + SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, + false, E_INVALID_ARG, "[E_INVALID_ARG] The specified filePath (%ls) is invalid.", filePath.GetPointer()); + + return _FileUtil::IsFileExist(filePath); +} + +result +_FileImpl::ConvertToSecureFile(const String& plainFilePath, const String& secureFilePath, + const ByteBuffer& key) +{ + return _FileUtil::ConvertToSecureFile(plainFilePath, secureFilePath, &key); +} + +bool +_FileImpl::IsAppPath(const String& filePath) +{ + SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, + false, E_INVALID_ARG, "[E_INVALID_ARG] The specified filePath (%ls) is invalid.", filePath.GetPointer()); + + return _FileUtil::IsAppPath(filePath); +} + +bool +_FileImpl::IsMediaPath(const String& filePath) +{ + SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, + false, E_INVALID_ARG, "[E_INVALID_ARG] The specified filePath (%ls) is invalid.", filePath.GetPointer()); + + return _FileUtil::IsMediaPath(filePath); +} + +bool +_FileImpl::IsSystemPath(const String& filePath) +{ + SysTryReturn(NID_IO, VerifyFilePathCompatibility(filePath, _AppInfo::IsOspCompat()) == true, + false, E_INVALID_ARG, "[E_INVALID_ARG] The specified filePath (%ls) is invalid.", filePath.GetPointer()); + + return _FileUtil::IsSystemPath(filePath); +} + +bool +_FileImpl::VerifyFilePath(const String& filePath, _FilePathType pathType) +{ + return _FileUtil::VerifyFilePath(filePath, pathType); +} + +bool +_FileImpl::CleanDirectories(const String& appRootPath, const String& pkgId) +{ + char removeCmd[PATH_MAX] = {0, }; + int ret = 0; + + String ospSharePkgIdPath = _EnvironmentImpl::GetOspCompatSharedPath(); + ospSharePkgIdPath.Append(L"share/"); + ospSharePkgIdPath.Append(pkgId); + + String ospShare2PkgIdPath = _EnvironmentImpl::GetOspCompatSharedPath(); + ospShare2PkgIdPath.Append(L"share2/"); + ospShare2PkgIdPath.Append(pkgId); + +#if 0 + r = Directory::Remove(ospSharePkgIdPath, true); + SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM, "[%s] Failed to remove directory (%ls)", + GetErrorMessage(r), ospSharePkgIdPath.GetPointer()); + + r = Directory::Remove(ospShare2PkgIdPath, true); + SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM, "[%s] Failed to remove directory (%ls)", + GetErrorMessage(r), ospShare2PkgIdPath.GetPointer()); +#else + sprintf(removeCmd, "rm -rf %ls", ospSharePkgIdPath.GetPointer()); + ret = system(removeCmd); + SysTryReturn(NID_IO, ret != -1, false, E_SYSTEM, "Failed to remove directory (%ls)", + ospSharePkgIdPath.GetPointer()); + + memset(removeCmd, 0, PATH_MAX); + + sprintf(removeCmd, "rm -rf %ls", ospShare2PkgIdPath.GetPointer()); + ret = system(removeCmd); + SysTryReturn(NID_IO, ret != -1, false, E_SYSTEM, "Failed to remove directory (%ls)", + ospShare2PkgIdPath.GetPointer()); +#endif + + return true; +} + +// This method is called by package installer backend. +bool +_FileImpl::PrepareDataCaging(const String& appRootPath, const String& pkgId) +{ + int index = 0; + char* pCwd = null; + bool internalInstalled = true; + result r = E_SUCCESS; + + SysLog(NID_IO, "[data_caging] PrepareDataCaging() was called by installer backend, appRootPath: %ls, packageId: %ls", + appRootPath.GetPointer(), pkgId.GetPointer()); + + if (CleanDirectories(appRootPath, pkgId) == false) + { + SysLog(NID_IO, "CleanDirectories() failed."); + return false; + } + + pCwd = get_current_dir_name(); + SysTryCatch(NID_IO, pCwd != null, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] get_current_dir_name() was failed, errno: %d (%s).", errno, strerror(errno)); + + // Check whether package is installed on internal storage or not + r = appRootPath.IndexOf("/opt/storage/sdcard", 0, index); + if (r == E_SUCCESS) + { + internalInstalled = false; + } + else + { + internalInstalled = true; + } + + umask(0000); + + if (internalInstalled == true) + { + unique_ptr pAppRootPath(_StringConverter::CopyToCharArrayN(appRootPath)); + SysTryCatch(NID_IO, pAppRootPath != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] The memory is insufficient."); + + SysTryCatch(NID_IO, chdir(pAppRootPath.get()) == 0, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] chdir() was failed (%s), path: %s", strerror(errno), pAppRootPath.get()); + + SysTryCatch(NID_IO, CreateOspInternalDirectories(pkgId) == true, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] fail to create OSP Internal directories"); + } + else + { + String appExRootPath(appRootPath); + + int ret = 0; + + appExRootPath.Append(pkgId); + unique_ptr pAppExRootPath(_StringConverter::CopyToCharArrayN(appExRootPath)); + SysTryCatch(NID_IO, pAppExRootPath != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] The memory is insufficient."); + + ret = mkdir(pAppExRootPath.get(), 0705); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o", + strerror(errno), pAppExRootPath.get(), 0705); + goto CATCH; + } + + SysTryCatch(NID_IO, chdir(pAppExRootPath.get()) == 0, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] chdir() was failed (%s), path: %s", strerror(errno), pAppExRootPath.get()); + SysTryCatch(NID_IO, CreateOspExternalDirectories(pkgId) == true, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] fail to create OSP External directories"); + } + + SysTryCatch(NID_IO, CreateSlpDirectories() == true, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] fail to create SLP directories"); + SysTryCatch(NID_IO, CreateSymbolicLink() == true, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] Fail to create symbolic link."); + SysTryCatch(NID_IO, chdir(pCwd) == 0, r = E_SYSTEM, E_SYSTEM, + "[E_SYSTEM] chdir() was failed (%s), path: %s", strerror(errno), pCwd); + + r = E_SUCCESS; + SysLog(NID_IO, "[data_caging] PrepareDataCaging() succeeded."); + + // fall thru +CATCH: + if (pCwd != null) + { + free(pCwd); + } + + umask(0022); + + if (IsFailed(r)) + { + SysLog(NID_IO, "[data_caging] PrepareDataCaging() failed."); + return false; + } + + return true; +} + +bool +_FileImpl::FinalizeDataCaging(const String& appRootPath) // for 2.0 app +{ + static const struct _PathInfo mountPath[] = + { + //{ "./bin" }, + //{ "./boot" }, + //{ "./cache" }, + { "./csa" }, + { "./dev/pts" }, + { "./dev/shm" }, + { "./dev" }, + { "./etc" }, + { "./lib" }, + //{ "./lost+found" }, + { "./media" }, + { "./mnt" }, + { "./opt/usr" }, + { "./opt/var/kdb/db" }, + { "./opt/storage/sdcard" }, + { "./opt" }, + //{ "./packaging" }, + { "./proc" }, + { "./sbin" }, + { "./srv" }, + { "./sys/kernel/debug" }, + { "./sys" }, + { "./tmp" }, + { "./usr" }, + { "./var/run" }, + { "./var" }, + + { "./data/Share" }, + { "./data/Share2" }, + { "./Share" }, + { "./Share2" }, + //{ "./Clipboard" }, + //{ "./NPKI" }, + //{ "./System" }, + //{ "./Tmp" }, + { "./Media" }, + + { "./Storagecard/Media" }, + { "./ShareExt" }, + { "./Share2Ext" }, + { "./HomeExt/Share" }, + { "./HomeExt/Share2" }, + { "./HomeExt" } + }; + + unique_ptr< char[] > pAppRootPath(_StringConverter::CopyToCharArrayN(appRootPath)); + SysTryReturn(NID_IO, pAppRootPath != null, false, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + SysTryReturn(NID_IO, chdir(pAppRootPath.get()) == 0, false, E_SYSTEM, + "[E_SYSTEM] chdir() failed (%d, %s), path: %ls", errno, strerror(errno), appRootPath.GetPointer()); + + for (int i = 0; i < sizeof(mountPath) / sizeof(struct _PathInfo); ++i) + { + int ret = umount2(mountPath[i].destPath, MNT_DETACH); + SysTryLog(NID_IO, ret == 0, "umount2() errno: %d (%s)", errno, strerror(errno)); + SysTryReturn(NID_IO, ret == 0 || errno == EINVAL || errno == ENOENT, false, E_SYSTEM, + "[E_SYSTEM] umount2() failed (%d, %s), path: %s", errno, strerror(errno), mountPath[i].destPath); + } + + char* pkgId = strrchr(pAppRootPath.get(), '/'); + char mountFlag[_MAX_PATH_LENGTH] = { 0, }; + sprintf(mountFlag, "%s/%s", _INTERNAL_MOUNT_FLAG, ++pkgId); + int res = unlink(mountFlag); + if (res == -1 && errno != ENOENT) + { + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to remove mount flag (%s), errno: %d (%s)", + mountFlag, errno, strerror(errno)); + return false; + } + + memset(mountFlag, 0, _MAX_PATH_LENGTH); + sprintf(mountFlag, "%s/%s", _EXTERNAL_MOUNT_FLAG, pkgId); + res = unlink(mountFlag); + if (res == -1 && errno != ENOENT) + { + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to remove mount flag (%s), errno: %d (%s)", + mountFlag, errno, strerror(errno)); + return false; + } + + SysLog(NID_IO, "[data_caging] FinalizeDataCaging() succeeded, appRootPath: %ls", appRootPath.GetPointer()); + return true; +} + +int +_FileImpl::GetAvailableUid(void) +{ + return _APP_UID; +} + +bool +_FileImpl::CreateOspApplicationDirectories(const String& appRootPath, const String& pkgId) // for 2.1 app +{ + struct _OspDir appSubDir[] = + { + { "./shared\0", 0755, false }, + //{ "./shared/data\0", 0755, true }, + { "./shared/res\0", 0755, false }, + { "./shared/trusted\0", 0755, true }, + //{ "./cache\0", 0700, true } + }; + int uid = -1; + int ret = 0; + unsigned int i = 0; + result r = E_SUCCESS; + + SysTryReturn(NID_IO, CleanDirectories(appRootPath, pkgId) == true, false, E_SYSTEM, + "[E_SYSTEM] Failed to clean directories for 2.0 application compatibility."); + + unique_ptr pAppRootPath(_StringConverter::CopyToCharArrayN(appRootPath)); + SysTryReturn(NID_IO, pAppRootPath != null, false, E_SYSTEM, "[E_SYSTEM] The memory is insufficient."); + + SysTryReturn(NID_IO, chdir(pAppRootPath.get()) == 0, false, E_SYSTEM, + "[E_SYSTEM] chdir() failed (%d, %s), path: %s", errno, strerror(errno), pAppRootPath.get()); + + uid = GetAvailableUid(); + + umask(0000); + + for (i = 0; i < sizeof(appSubDir) / sizeof(struct _OspDir); ++i) + { + ret = mkdir(appSubDir[i].path, appSubDir[i].mode); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "[E_SYSTEM] mkdir() failed (%d, %s), path: %s, mode: 0%o", + errno, strerror(errno), appSubDir[i].path, appSubDir[i].mode); + goto CATCH; + } + + if (appSubDir[i].appPrivilege) + { + ret = chown(appSubDir[i].path, uid, uid); + SysTryCatch(NID_IO, ret == 0, , E_SYSTEM, + "[E_SYSTEM] chown() failed (%d, %s), path: %s, uid: %d", + errno, strerror(errno), appSubDir[i].path, uid); + } + } + + if (access("./shared/data", F_OK) == 0) + { + SysTryCatch(NID_IO, system("chown -R 5000:5000 ./shared/data") != -1, , E_SYSTEM, + "[E_SYSTEM] chown() failed"); + } + // XXX: Temp code for supporting old share directory. + else if (access("./share", F_OK) == 0) + { + SysTryCatch(NID_IO, system("rm -rf ./shared/data") != -1, , E_SYSTEM, + "[E_SYSTEM] Failed to remove ./shared/data directory"); + + SysTryCatch(NID_IO, rename("./share", "./shared/data") == 0, , E_SYSTEM, + "[E_SYSTEM] Failed to rename share directory (%d, %s)", errno, strerror(errno)); + + SysTryCatch(NID_IO, system("chown -R 5000:5000 ./shared/data") != -1, , E_SYSTEM, + "[E_SYSTEM] chown() failed"); + + SysTryCatch(NID_IO, chmod("./shared/data", 0755) == 0, , E_SYSTEM, "[E_SYSTEM] chmod() failed"); + } + // XXX-end + + umask(0022); + + SysLog(NID_IO, "_FileImpl::CreateOspApplicationDirectories() succeeded."); + return true; + +CATCH: + umask(0022); + + return false; +} + +bool +_FileImpl::CreateOspInternalDirectories(const String& pkgId) // for 2.0 app +{ + unsigned int i = 0; + int ret = 0; + int uid = -1; + struct _OspDir appSubDir[] = + { +// { "./data", 0700, true }, // It is created by installer. + { "./shared", 0755, false }, + { "./data/Share", 0000, true }, // mount from /opt/usr/share/.osp-compat/share/{pkgId} + { "./data/Share2", 0000, true }, // mount from /opt/usr/share/.osp-compat/share2/{pkgId} + { "./Share", 0000, false }, // mount from /opt/usr/share/.osp-compat/share + { "./Share2", 0000, false }, // mount from /opt/usr/share/.osp-compat/share2 +// { "./Clipboard", 0000, false }, +// { "./NPKI", 0000, false }, +// { "./System", 0000, false }, +// { "./Tmp", 0000, false }, + { "./Media", 0000, false }, // mount from /opt/usr/media + { "./Storagecard", 0705, false }, + { "./Storagecard/Media", 0000, false }, // mount from /opt/storage/sdcard + }; +#if 1 + struct _OspDir mediaDir[] = + { + { "/opt/usr/media/Images", 0777, false }, + { "/opt/usr/media/Sounds", 0777, false }, + { "/opt/usr/media/Videos", 0777, false }, + //{ "/opt/usr/media/Themes", 0777, false }, + { "/opt/usr/media/Others", 0777, false } + }; +#endif + String ospCompatSharedPath = _EnvironmentImpl::GetOspCompatSharedPath(); + String ospShareAppIdPath(L"share/"); + String ospShare2AppIdPath(L"share2/"); + result r = E_SUCCESS; + + r = ospShareAppIdPath.Insert(ospCompatSharedPath, 0); + SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM, + "[E_SYSTEM] String::Insert() failed. (error: %s)", GetErrorMessage(r)); + + r = ospShare2AppIdPath.Insert(ospCompatSharedPath, 0); + SysTryReturn(NID_IO, !IsFailed(r), false, E_SYSTEM, + "[E_SYSTEM] String::Insert() failed. (error: %s)", GetErrorMessage(r)); + + uid = GetAvailableUid(); + + for (i = 0; i < sizeof(appSubDir) / sizeof(struct _OspDir); i++) + { + ret = mkdir(appSubDir[i].path, appSubDir[i].mode); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o", + strerror(errno), appSubDir[i].path, appSubDir[i].mode); + return false; + } + if (appSubDir[i].appPrivilege) + { + ret = chown(appSubDir[i].path, uid, uid); + if (ret == -1) + { + SysLog(NID_IO, "chown() failed (%s), path: %s, uid: %d", + strerror(errno), appSubDir[i].path, uid); + return false; + } + } + } + + ospShareAppIdPath.Append(pkgId); + unique_ptr pOspShareAppIdPath(_StringConverter::CopyToCharArrayN(ospShareAppIdPath)); + SysTryReturn(NID_IO, pOspShareAppIdPath != null, false, E_SYSTEM, "[E_SYSTEM] The memory is insufficient."); + ret = mkdir(pOspShareAppIdPath.get(), 0705); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o", + strerror(errno), pOspShareAppIdPath.get(), 0705); + return false; + } + ret = chown(pOspShareAppIdPath.get(), uid, uid); + if (ret == -1) + { + SysLog(NID_IO, "chown() failed (%s), path: %s, uid: %d", + strerror(errno), pOspShareAppIdPath.get(), uid); + return false; + } + + ospShare2AppIdPath.Append(pkgId); + unique_ptr pOspShare2AppIdPath(_StringConverter::CopyToCharArrayN(ospShare2AppIdPath)); + SysTryReturn(NID_IO, pOspShare2AppIdPath != null, false, E_SYSTEM, "[E_SYSTEM] The memory is insufficient."); + ret = mkdir(pOspShare2AppIdPath.get(), 0705); // TODO: change to 0770 + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o", + strerror(errno), pOspShare2AppIdPath.get(), 0705); + return false; + } + ret = chown(pOspShare2AppIdPath.get(), uid, uid); + if (ret == -1) + { + SysLog(NID_IO, "chown() failed (%s), path: %s, uid: %d", + strerror(errno), pOspShare2AppIdPath.get(), uid); + return false; + } + +#if 1 + for (i = 0; i < sizeof(mediaDir) / sizeof(struct _OspDir); ++i) + { + ret = mkdir(mediaDir[i].path, mediaDir[i].mode); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o", + strerror(errno), mediaDir[i].path, mediaDir[i].mode); + return false; + } + ret = chown(mediaDir[i].path, 5000, 5000); + SysTryReturn(NID_IO, ret == 0, false, E_SYSTEM, + "[E_SYSTEM] chown() failed (%d, %s), path: %s, uid: 5000, gid: 5000", + errno, strerror(errno), mediaDir[i].path); + } +#endif + + // XXX: shared directory is not supported for 2.0 applications +#if 0 + if (access("./shared/data", F_OK) == 0) + { + char copyCmd[256] = { 0, }; + sprintf(copyCmd, "cp -rf ./shared/data/* /opt/usr/share/.osp-compat/share/%ls/", pkgId.GetPointer()); + ret = system(copyCmd); + SysTryReturn(NID_IO, ret != -1, false, E_SYSTEM, "Failed to copy command (%s)", copyCmd); + + SysTryReturn(NID_IO, system("rm -rf ./shared/data") != -1, false, E_SYSTEM, + "[E_SYSTEM] rmdir() failed, path: ./shared/data"); + + char chownCmd[256] = { 0, }; + sprintf(chownCmd, "chown -R 5000:5000 /opt/usr/share/.osp-compat/share/%ls/", pkgId.GetPointer()); + SysTryReturn(NID_IO, system(chownCmd) != -1, false, E_SYSTEM, "[E_SYSTEM] chown() failed"); + + char symlinkCmd[256] = { 0, }; + sprintf(symlinkCmd, "ln -s %s ./shared/data", pOspShareAppIdPath.get()); + SysTryReturn(NID_IO, system(symlinkCmd) != -1, false, E_SYSTEM, "[E_SYSTEM] symlink() failed"); + } +#endif + char symlinkCmd[256] = { 0, }; + sprintf(symlinkCmd, "ln -s %s ./shared/data", pOspShareAppIdPath.get()); + SysTryReturn(NID_IO, system(symlinkCmd) != -1, false, E_SYSTEM, "[E_SYSTEM] symlink() failed"); + + return true; +} + +// TODO: Need to test this method. +bool +_FileImpl::CreateOspExternalDirectories(const String& pkgId) +{ + unsigned int i = 0; + int ret = 0; + int uid = -1; + struct _OspDir appSubDir[] = { // virtual path +// { "./data", 0700, true }, + { "./System", 0000, false }, // mount from /opt/apps/com.samsung.osp/system + { "./Storagecard", 0705, false }, + { "./Storagecard/Media", 0000, false } // mount from /opt/storage/sdcard + }; +#if 0 + struct _OspDir mediaDir[] = { // physical path + { "/opt/usr/media/Images", 0777, false }, + { "/opt/usr/media/Sounds", 0777, false }, + { "/opt/usr/media/Videos", 0777, false }, + //{ "/opt/usr/media/Themes", 0777, false }, + { "/opt/usr/media/Others", 0777, false } + }; +#endif + + for (i = 0; i < sizeof(appSubDir) / sizeof(struct _OspDir); i++) + { + ret = mkdir(appSubDir[i].path, appSubDir[i].mode); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o", + strerror(errno), appSubDir[i].path, appSubDir[i].mode); + return false; + } + if (appSubDir[i].appPrivilege) + { + ret = chown(appSubDir[i].path, uid, uid); + if (ret == -1) + { + SysLog(NID_IO, "chown() failed (%s), path: %s, uid: %d", + strerror(errno), appSubDir[i].path, uid); + return false; + } + } + } + +#if 0 + for (i = 0; i < sizeof(mediaDir) / sizeof(struct _OspDir); i++) + { + ret = mkdir(mediaDir[i].path, mediaDir[i].mode); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o", + strerror(errno), mediaDir[i].path, mediaDir[i].mode); + return false; + } + } +#endif + + return true; +} + +bool +_FileImpl::CreateSlpDirectories(void) +{ + unsigned int i = 0; + int ret = 0; + struct _OspDir slpDir[] = { // virtual path + //{ "./bin", 0000, false }, // mount from /bin + //{ "./boot", 0000, false }, + //{ "./cache", 0000, false }, + { "./csa", 0000, false }, + { "./dev", 0000, false }, + { "./etc", 0000, false }, + { "./lib", 0000, false }, + //{ "./lost+found", 0000, false }, + { "./media", 0000, false }, + { "./mnt", 0000, false }, + { "./opt", 0000, false }, + //{ "./packaging", 0000, false }, + { "./proc", 0000, false }, + { "./sbin", 0000, false }, + { "./srv", 0000, false }, + { "./sys", 0000, false }, + { "./tmp", 0000, false }, + { "./usr", 0000, false }, + { "./var", 0000, false } + }; + + for (i = 0; i < sizeof(slpDir) / sizeof(struct _OspDir); i++) + { + ret = mkdir(slpDir[i].path, slpDir[i].mode); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "mkdir() failed (%s), path: %s, mode: 0%o", + strerror(errno), slpDir[i].path, slpDir[i].mode); + return false; + } + } + + return true; +} + +bool +_FileImpl::CreateSymbolicLink(void) +{ + struct _LinkDir linkDirList[] = { + { "/opt/home", "./home" }, + { "/opt/home/root", "./root" }, + { "/mnt/mmc", "./sdcard" } + }; + + for (unsigned int i = 0; i < sizeof(linkDirList) / sizeof(struct _LinkDir); ++i) + { + int ret = symlink(linkDirList[i].srcPath, linkDirList[i].destPath); + if (ret == -1 && errno != 17) // EEXIST + { + SysLog(NID_IO, "Failed to create symbolic link, errno: %d (%s), src path: %s, dest path: %s", + strerror(errno), linkDirList[i].srcPath, linkDirList[i].destPath); + return false; + } + } + + return true; +} + +bool +_FileImpl::VerifyFilePathCompatibility(const String& filePath, bool ospCompat) +{ + if (ospCompat == true) + { + if (filePath[0] != L'/') + { + return false; + } + } + int length = filePath.GetLength(); + if (length > 0) + { + return true; + } + return false; +} + +_FileImpl* +_FileImpl::GetInstance(File& file) +{ + return file.__pFileImpl; +} + +const _FileImpl* +_FileImpl::GetInstance(const File& file) +{ + return file.__pFileImpl; +} + +result +_FileImpl::ConvertVirtualToPhysicalPath(const String& virtualPath, String& physicalPath) // for 2.0 app +{ + SysTryReturnResult(NID_IO, VerifyFilePathCompatibility(virtualPath, _AppInfo::IsOspCompat()) == true, + E_INVALID_ARG, "[E_INVALID_ARG] %ls is not compatible.", virtualPath.GetPointer()); + + const wchar_t* virtualPathPrefix[] = + { + L"/Home/Share2", + L"/Home/Share", + L"/Home", + L"/Res", + L"/Share2", + L"/Share/AppControl", + L"/Share", + //L"/HomeExt", + //L"/ShareExt", + //L"/Share2Ext", + //L"/NPKI", + L"/Media", + L"/Storagecard/Media", + //L"/Storagecard/NPKI", + }; + result r = E_SUCCESS; + int count = sizeof(virtualPathPrefix)/sizeof(wchar_t*); + int i = 0; + + for (i = 0; i < count; i++) + { + SysLog(NID_IO, "[V2P] i: %d, path: %ls", i, virtualPathPrefix[i]); + if (virtualPath.StartsWith(virtualPathPrefix[i], 0) == true) + { + break; + } + } + SysTryReturnResult(NID_IO, i != count, E_INVALID_ARG, "The path (%ls) is not matched.", + virtualPath.GetPointer()); + + int prefixLen = String(virtualPathPrefix[i]).GetLength(); + if (virtualPath.GetLength() > prefixLen) + { + wchar_t ch = '\0'; + + r = virtualPath.GetCharAt(prefixLen, ch); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] The path (%ls) is not matched.", + GetErrorMessage(r), virtualPath.GetPointer()); + + if (ch != L'/') + { + physicalPath.Clear(); + SysLog(NID_IO, "[E_INVALID_ARG] The path (%ls) is not matched.", + virtualPath.GetPointer()); + + return E_INVALID_ARG; + } + } + + String subPath; + virtualPath.SubString(wcslen(virtualPathPrefix[i]), subPath); + + Tizen::App::App* pApp = Tizen::App::App::GetInstance(); + SysTryReturnResult(NID_IO, pApp != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + String homePath = pApp->GetAppRootPath(); + String ospCompatSharedPath = _EnvironmentImpl::GetOspCompatSharedPath(); + + switch (i) + { + case 0: + physicalPath = homePath + L"data/Share2"; + break; + case 1: + physicalPath = homePath + L"data/Share"; + break; + case 2: + physicalPath = homePath + L"data"; + break; + case 3: + physicalPath = homePath + L"res"; + break; + case 4: + physicalPath = ospCompatSharedPath + L"share2"; + break; + case 5: + physicalPath = ospCompatSharedPath + L"share/AppControl"; + break; + case 6: + physicalPath = ospCompatSharedPath + L"share"; + break; + case 7: + physicalPath = Tizen::System::Environment::GetMediaPath(); + break; + case 8: + physicalPath = Tizen::System::Environment::GetExternalStoragePath() + L"Media"; + break; + default: + SysLog(NID_IO, "[E_INVALID_ARG] The path (%ls) is not matched.", + virtualPath.GetPointer()); + return E_INVALID_ARG; + } + + if (subPath.IsEmpty() == false) + { + physicalPath.Append(subPath); + } + + return r; +} + +result +_FileImpl::ConvertPhysicalToVirtualPath(const String& physicalPath, String& virtualPath) // for 2.0 app +{ + result r = E_SUCCESS; + const wchar_t* homeSubDir[] = { + L"/data/Share2", + L"/data/Share", + L"/data", + L"/res", + }; + const wchar_t* ospHomeSubDir[] = { + L"/share2", + L"/share/AppControl", + L"/share", + }; + String subPath; + int homeSubDirCount = sizeof(homeSubDir)/sizeof(wchar_t*); + int ospHomeSubDirCount = sizeof(ospHomeSubDir)/sizeof(wchar_t*); + int baseDirLen = 0; + int i = 0; + + SysLog(NID_IO, "[P2V] physicalPath: %ls", physicalPath.GetPointer()); + + Tizen::App::App* pApp = Tizen::App::App::GetInstance(); + SysTryReturnResult(NID_IO, pApp != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + String homePath = pApp->GetAppRootPath(); + homePath.SetLength(homePath.GetLength() - 1); + + String ospCompatSharedPath = _EnvironmentImpl::GetOspCompatSharedPath(); + ospCompatSharedPath.SetLength(ospCompatSharedPath.GetLength() - 1); + + String mediaPath = Tizen::System::Environment::GetMediaPath(); + mediaPath.SetLength(mediaPath.GetLength() - 1); + + String externalPath = Tizen::System::Environment::GetExternalStoragePath(); + externalPath.SetLength(externalPath.GetLength() - 1); + + if (physicalPath.StartsWith(homePath, 0) == true) + { + physicalPath.SubString(homePath.GetLength(), subPath); + + for (i = 0; i < homeSubDirCount; i++) + { + SysLog(NID_IO, "[P2V] i: %d, path: %ls", i, homeSubDir[i]); + if (subPath.StartsWith(homeSubDir[i], 0) == true) + { + break; + } + } + SysTryReturnResult(NID_IO, i != homeSubDirCount, E_INVALID_ARG, "The path (%ls) is not matched.", + physicalPath.GetPointer()); + + baseDirLen = homePath.GetLength() + String(homeSubDir[i]).GetLength(); + + switch (i) + { + case 0: + virtualPath = L"/Home/Share2"; + break; + case 1: + virtualPath = L"/Home/Share"; + break; + case 2: + virtualPath = L"/Home"; + break; + case 3: + virtualPath = L"/Res"; + break; + default: + break; + } + + } + else if (physicalPath.StartsWith(ospCompatSharedPath, 0) == true) + { + physicalPath.SubString(ospCompatSharedPath.GetLength(), subPath); + + for (i = 0; i < ospHomeSubDirCount; i++) + { + SysLog(NID_IO, "[P2V] i: %d, path: %ls", i, ospHomeSubDir[i]); + if (subPath.StartsWith(ospHomeSubDir[i], 0) == true) + { + break; + } + } + SysTryReturnResult(NID_IO, i != ospHomeSubDirCount, E_INVALID_ARG, "The path (%ls) is not matched.", + physicalPath.GetPointer()); + + baseDirLen = ospCompatSharedPath.GetLength() + String(ospHomeSubDir[i]).GetLength(); + + switch (i) + { + case 0: + virtualPath = L"/Share2"; + break; + case 1: + virtualPath = L"/Share/AppControl"; + break; + case 2: + virtualPath = L"/Share"; + break; + default: + break; + } + } + else if (physicalPath.StartsWith(mediaPath, 0) == true) + { + SysLog(NID_IO, "[P2V] media"); + virtualPath = L"/Media"; + baseDirLen = mediaPath.GetLength(); + } + else if (physicalPath.StartsWith(externalPath, 0) == true) + { + SysLog(NID_IO, "[P2V] external media"); + virtualPath = L"/Storagecard/Media"; + baseDirLen = externalPath.GetLength(); + } + else + { + SysLog(NID_IO, "[E_INVALID_ARG] The path (%ls) is not matched.", + physicalPath.GetPointer()); + + return E_INVALID_ARG; + } + + if (physicalPath.GetLength() > baseDirLen) + { + wchar_t ch = '\0'; + + r = physicalPath.GetCharAt(baseDirLen, ch); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] The path (%ls) is not matched.", + GetErrorMessage(r), physicalPath.GetPointer()); + + if (ch != L'/') + { + virtualPath.Clear(); + SysLog(NID_IO, "[E_INVALID_ARG] The path (%ls) is not matched.", + physicalPath.GetPointer()); + + return E_INVALID_ARG; + } + } + + subPath.Clear(); + physicalPath.SubString(baseDirLen, subPath); + + if (subPath.IsEmpty() == false) + { + virtualPath.Append(subPath); + } + + return r; +} + +}} // Tizen::Io diff --git a/src/io/FIo_FileUtil.cpp b/src/io/FIo_FileUtil.cpp new file mode 100644 index 0000000..7fc3c56 --- /dev/null +++ b/src/io/FIo_FileUtil.cpp @@ -0,0 +1,851 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_FileUtil.cpp + * @brief This is the implementation file for _FileUtil class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +static const int _BASE_YEAR = 1900; +static const int _MAX_COPY_BYTES = 4096; +static const int _MAX_OPENMODE_LENGTH = 3; + +//Holds app path prefixes +static const char* filePathAppPrefix[] = +{ + "/Home", + "/Res", + "/Share", + "/Share2", + "/HomeExt", + "/ShareExt", + "/Share2Ext", + "/Clipboard", + "/NPKI", + "/Storagecard/NPKI", + "/system/Document", + "/system/Data/FWeb", + "/Storagecard/DownloadedAppPackages", + "/system/Media", + "/system/Ringtones", + "/system/Wallpapers", + "/EmailBox", + "/MmsBox" +}; + +//Holds Media path prefixes +static const char* filePathMediaPrefix[] = +{ + "/Media", + "/Storagecard/Media" +}; + +//Holds system path prefixes +static const char* filePathSystemPrefix[] = +{ + "/system/configuration", + "/SystemRw" +}; + +result +_FileUtil::Remove(const String& filePath) +{ + result r = E_SUCCESS; + unique_ptr pFilePath(_StringConverter::CopyToCharArrayN(filePath)); + SysTryReturn(NID_IO, (pFilePath != null), GetLastResult(), GetLastResult(), ("[%s] Invalid file path."), + GetErrorMessage(GetLastResult())); + + if (_FileUtil::IsFileExist(pFilePath.get()) == false) + { + SysLog(NID_IO, "[E_FILE_NOT_FOUND] File(%s) does not exist.", pFilePath.get()); + return E_FILE_NOT_FOUND; + } + + char resolvedPath[PATH_MAX] = {0,}; + if (realpath(pFilePath.get(), resolvedPath) == null) + { + switch (errno) + { + case EACCES: + r = E_ILLEGAL_ACCESS; + break; + case EINVAL: + // fall through + case ELOOP: + // fall through + case ENAMETOOLONG: + // fall through + case ENOTDIR: + r = E_INVALID_ARG; + break; + case EIO: + r = E_IO; + break; + case ENOENT: + r = E_FILE_NOT_FOUND; + break; + default: + r = E_SYSTEM; + break; + } + + SysLog(NID_IO, "[%s] Failed to produce canonical absolute path (%ls). errno: %d (%s)", + GetErrorMessage(r), filePath.GetPointer(), errno, strerror(errno)); + + return r; + } + + int ret = unlink(resolvedPath); + if (ret != 0) + { + if (errno == EISDIR) + { + r = E_INVALID_ARG; + } + else + { + r = __ConvertNativeErrorToResult(errno); + SysLog(NID_IO, "[%s] Failed to unlink(), errno: %d (%s)", GetErrorMessage(r), errno, strerror(errno)); + } + } + + return r; +} + +result +_FileUtil::Move(const String& oldFilePath, const String& newFilePath) +{ + result r = E_SUCCESS; + struct stat statBuf; + + unique_ptr pOldPath(_StringConverter::CopyToCharArrayN(oldFilePath)); + SysTryReturn(NID_IO, pOldPath != null, GetLastResult(), GetLastResult(), + "[%s] Invalid old file path.", GetErrorMessage(GetLastResult())); + + unique_ptr pNewPath(_StringConverter::CopyToCharArrayN(newFilePath)); + SysTryReturn(NID_IO, pNewPath != null, GetLastResult(), GetLastResult(), + "[%s] Invalid new file path.", GetErrorMessage(GetLastResult())); + + SysTryReturnResult(NID_IO, _FileUtil::IsFileExist(newFilePath) == false, E_FILE_ALREADY_EXIST, + "New file already exists."); + + SysTryReturnResult(NID_IO, _FileUtil::IsFileExist(oldFilePath) == true, E_FILE_NOT_FOUND, + "Old filepath not found."); + + if (stat(pOldPath.get(), &statBuf) < 0) + { + r = __ConvertNativeErrorToResult(errno); + SysLogException(NID_IO, r, "[%s] stat() failed, path: %s, errno: %d (%s)", GetErrorMessage(r), pOldPath.get(), errno, strerror(errno)); + return r; + } + SysTryReturnResult(NID_IO, S_ISDIR(statBuf.st_mode) == false, E_INVALID_ARG, + "The old path is a directory."); + + // TODO: Use rename() for move operation in same mount point + // and need API versioning. +#if 0 + int ret = rename(pOldPath.get(), pNewPath.get()); + if (ret != 0) + { + r = __ConvertNativeErrorToResult(errno); + SysLog(NID_IO, "[%s] rename() failed, errno: %d, strerror: %s", errno, strerror(errno)); + return r; + } +#else + // To work across different mount points + r = File::Copy(oldFilePath, newFilePath, true); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = File::Remove(oldFilePath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); +#endif + + return E_SUCCESS; +} + +result +_FileUtil::Copy(const String& srcFilePath, const String& destFilePath, bool failIfExist) +{ + result r = E_SUCCESS; + int srcFd = -1; + int dstFd = -1; + int size = 0; + void* pSrcMap = MAP_FAILED; + void* pDstMap = MAP_FAILED; + unique_ptr pBuffer(null); + + unique_ptr pSrcpath(_StringConverter::CopyToCharArrayN(srcFilePath)); + SysTryReturn(NID_IO, pSrcpath != null, GetLastResult(), GetLastResult(), + "[%s] Invalid source file path.", GetErrorMessage(GetLastResult())); + + unique_ptr pDstpath(_StringConverter::CopyToCharArrayN(destFilePath)); + SysTryReturn(NID_IO, pDstpath != null, GetLastResult(), GetLastResult(), + "[%s] Invalid destination file path.", GetErrorMessage(GetLastResult())); + + SysTryReturnResult(NID_IO, _FileUtil::IsFileExist(srcFilePath) == true, E_FILE_NOT_FOUND, + "Source file(%s) does not exist.", pSrcpath.get()); + + if ((_FileUtil::IsFileExist(destFilePath) == true) && (failIfExist == true)) + { + r = E_FILE_ALREADY_EXIST; + SysLog(NID_IO, "[E_FILE_ALREADY_EXIST] Destination file already exists."); + return r; + } + + // try linux way to optimally use mmap. + srcFd = open(pSrcpath.get(), O_RDONLY); + r = __ConvertNativeErrorToResult(errno); + SysTryReturn(NID_IO, (srcFd != -1), r, r, "[%s] Failed to open file (%s).", __ConvertNativeErrorToMessage(errno), pSrcpath.get()); + + dstFd = open(pDstpath.get(), O_WRONLY | O_CREAT | O_TRUNC, 0644); + r = __ConvertNativeErrorToResult(errno); + SysTryCatch(NID_IO, (dstFd != -1), , r, "[%s] Failed to open file (%s), errno: %d (%s)", + __ConvertNativeErrorToMessage(errno), pDstpath.get(), errno, strerror(errno)); + + // First try the mmap method + size = lseek(srcFd, 0, SEEK_END); + r = __ConvertNativeErrorToResult(errno); + SysTryCatch(NID_IO, (size != -1), , r, "[%s] Failed to reach the end of file (%s).", __ConvertNativeErrorToMessage( + errno), pDstpath.get()); + + pSrcMap = mmap(0, size, PROT_READ, MAP_SHARED, srcFd, 0); + pDstMap = mmap(0, size, PROT_WRITE, MAP_SHARED, dstFd, 0); + + if ((pSrcMap != MAP_FAILED) && (pDstMap != MAP_FAILED)) + { + // do the copy and commit + memcpy(pDstMap, pSrcMap, size); + msync(pDstMap, size, MS_SYNC); + } + else // mmap method filed due to memory limitations.. try regular copy + { + off_t start = lseek(srcFd, 0, SEEK_SET); + r = __ConvertNativeErrorToResult(errno); + SysTryCatch(NID_IO, (start != -1), , r, "[%s] Failed to reach the end of file (%s).", __ConvertNativeErrorToMessage( + errno), pDstpath.get()); + + pBuffer = unique_ptr (new (std::nothrow) char[_MAX_COPY_BYTES]); + SysTryCatch(NID_IO, (pBuffer != null), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + ssize_t bytesRead = -1; + ssize_t bytesWritten = -1; + do + { + bytesRead = read(srcFd, pBuffer.get(), _MAX_COPY_BYTES); + r = __ConvertNativeErrorToResult(errno); + SysTryCatch(NID_IO, bytesRead != -1, , r, "[%s] Failed to read from file (%s), errno: %d", + __ConvertNativeErrorToMessage(errno), pSrcpath.get(), errno); + + bytesWritten = write(dstFd, pBuffer.get(), bytesRead); + r = __ConvertNativeErrorToResult(errno); + SysTryCatch(NID_IO, bytesWritten != -1, , r, "[%s] Failed to write to file (%s), errno: %d", + __ConvertNativeErrorToMessage( + errno), pDstpath.get(), errno); + } + while (bytesRead); + } + + r = E_SUCCESS; + + // fall thru +CATCH: + + if (srcFd != -1) + { + close(srcFd); + } + + if (dstFd != -1) + { + fsync(dstFd); + close(dstFd); + } + + if (pSrcMap != MAP_FAILED && size != -1) + { + munmap(pSrcMap, size); + } + + if (pDstMap != MAP_FAILED && size != -1) + { + munmap(pDstMap, size); + } + + return r; +} + +result +_FileUtil::GetAttributes(const String& filePath, FileAttributes& attribute) +{ + DateTime dateTime; + DateTime modifiedTime; + long long fileSize = 0; + unsigned long attr = 0; + result r = E_SUCCESS; + struct tm* pTm = null; + String fileName = L""; + bool hidden = false; + + unique_ptr pFilePath(_StringConverter::CopyToCharArrayN(filePath)); + SysTryReturn(NID_IO, (pFilePath != null), GetLastResult(), GetLastResult(), "[%s] Invalid source file path.", + GetErrorMessage(GetLastResult())); + + struct stat statbuf; + if (int ret = stat(pFilePath.get(), &statbuf) == -1) + { + r = __ConvertNativeErrorToResult(errno); + SysLogException(NID_IO, r, "[%s] Failed to get file (%s) status.", GetErrorMessage(r), pFilePath.get()); + return r; + } + + // size + fileSize = statbuf.st_size; + + // attributes + attr = statbuf.st_mode; + + // time of last status change + pTm = localtime(&statbuf.st_ctime); + SysTryReturnResult(NID_IO, pTm != null, E_SYSTEM, "Failed to call localtime() (%s).", strerror(errno)); + r = dateTime.SetValue(_BASE_YEAR + pTm->tm_year, 1 + pTm->tm_mon, pTm->tm_mday, pTm->tm_hour, pTm->tm_min, pTm->tm_sec); + SysTryReturn(NID_IO, (!IsFailed(r)), r, r, "[%s] Failed to set DateTime.", GetErrorMessage(r)); + + // time of last modification + pTm = localtime(&statbuf.st_mtime); + SysTryReturnResult(NID_IO, pTm != null, E_SYSTEM, "Failed to call localtime() (%s).", strerror(errno)); + r = modifiedTime.SetValue(_BASE_YEAR + pTm->tm_year, 1 + pTm->tm_mon, pTm->tm_mday, pTm->tm_hour, pTm->tm_min, pTm->tm_sec); + SysTryReturn(NID_IO, (!IsFailed(r)), r, r, "[%s] Failed to set DateTime.", GetErrorMessage(r)); + + fileName = _FileUtil::GetFileName(filePath); + if (fileName.StartsWith(L".", 0)) // including . and .. + { + hidden = true; + } + + _FileAttributesImpl::GetInstance(attribute)->Set(dateTime, modifiedTime, fileSize, attr, hidden); + + return E_SUCCESS; +} + +String +_FileUtil::GetFileName(const String& filePath) +{ + String fileName; + int pos = -1; + + result r = filePath.LastIndexOf(L'/', filePath.GetLength() - 1, pos); + SysTryReturn(NID_IO, !IsFailed(r), fileName, E_INVALID_ARG, "[E_INVALID_ARG] The file path is invalid."); + + r = filePath.SubString(pos + 1, fileName); + SysTryReturn(NID_IO, !IsFailed(r), fileName, E_INVALID_ARG, "[E_INVALID_ARG] The file path is invalid."); + SysTryReturn(NID_IO, fileName.GetLength() > 0 && fileName.GetLength() <= NAME_MAX, fileName, E_INVALID_ARG, + "[E_INVALID_ARG] The length of file name is zero or exceeds system limitations."); + + SetLastResult(E_SUCCESS); + return fileName; +} + +String +_FileUtil::GetFileExtension(const String& filePath) +{ + String extName; + int pos = -1; + + result r = filePath.LastIndexOf(L'/', filePath.GetLength() - 1, pos); + SysTryReturn(NID_IO, !IsFailed(r), extName, E_INVALID_ARG, "[E_INVALID_ARG] The file path is invalid."); + + String fileName; + r = filePath.SubString(pos + 1, fileName); + SysTryReturn(NID_IO, !IsFailed(r), extName, E_INVALID_ARG, "[E_INVALID_ARG] The file path is invalid."); + SysTryReturn(NID_IO, fileName.GetLength() > 0 && fileName.GetLength() <= NAME_MAX, extName, E_INVALID_ARG, + "[E_INVALID_ARG] The length of file name is zero or exceeds system limitations."); + + r = fileName.LastIndexOf(L'.', fileName.GetLength() - 1, pos); + SysTryReturn(NID_IO, !IsFailed(r), extName, E_INVALID_ARG, "[E_INVALID_ARG] The file path is invalid."); + + r = fileName.SubString(pos + 1, extName); + SysTryReturn(NID_IO, !IsFailed(r), extName, E_INVALID_ARG, "[E_INVALID_ARG] The file path is invalid."); + + SetLastResult(E_SUCCESS); + return extName; +} + +bool +_FileUtil::IsFileExist(const String& filePath) +{ + int ret = 0; + result r = E_SUCCESS; + + unique_ptr pFilePath(_StringConverter::CopyToCharArrayN(filePath)); + SysTryReturn(NID_IO, (pFilePath != null), false, GetLastResult(), ("[%s] Invalid file path."), + GetErrorMessage(GetLastResult())); + + ret = access(pFilePath.get(), F_OK); + if (ret != 0) + { + switch (errno) + { + case ENAMETOOLONG: + r = E_INVALID_ARG; + break; + case ENOENT: + r = E_SUCCESS; + break; + default: + r = __ConvertNativeErrorToResult(errno); + break; + } + } + + SetLastResult(r); + return (ret == 0) ? true : false; +} + +#if 0 +bool +_FileUtil::IsEncrypted(const String& filePath) +{ + result r = E_SUCCESS; + // TODO: int pathKind; + int readItems = 0; + int fileLength = 0; + bool encrypted = false; + // TODO: bool checkPrivilege = false; + byte secureHeader[SECURE_FILE_HEADER_SIZE_V1 + SECURE_IO_LOF_SIZE]; + byte reservedValue[SECURE_IO_STATIC_BIN_LEN] = {0xCA, 0xFE, 0xBE, 0xBE, 0xDA, 0xEF, 0xEB, 0xEB}; + char magicNum1[SECURE_IO_MAGIC_NUMBER_SIZE] = {0xCA, 0xFE, 0xBE, 0xBE}; + char magicNum2[SECURE_IO_MAGIC_NUMBER_SIZE] = {0xDA, 0xEF, 0xEF, 0xEB}; + FILE* pFile = null; + + unique_ptr pFilePath(_StringConverter::CopyToCharArrayN(filePath)); + SysTryReturn(NID_IO, pFilePath != null, false, E_INVALID_ARG, "[E_INVALID_ARG] CopyToCharArrayN failed!"); + + fileLength = strlen(pFilePath.get()); + SysTryReturn(NID_IO, fileLength > 0, false, E_INVALID_ARG, "[E_INVALID_ARG] CopyToCharArrayN failed!"); + + if (pFilePath[fileLength - 1] == ('/')) + { + pFilePath[fileLength - 1] = ('\0'); // remove last '/' character if exists. + } + +// // TODO: check accessibility to path +// r = CheckAccessibilityToPath(pFilePath, &pathKind, 0); +// if(IsFailed(r)) +// goto CATCH; +// +// if(pathKind == __PATH_KIND_AUTHORIZED_MMC) +// { +// __CheckPrivilege(PRV_INSTALLATION, checkPrivilege); +// if(!checkPrivilege) +// { +// r = E_ILLEGAL_ACCESS; +// goto CATCH; +// } +// } +// else if(pathKind == __PATH_KIND_AUTHORIZED_LINK || pathKind == __PATH_KIND_AUTHORIZED_NPKI || +// pathKind == __PATH_KIND_AUTHORIZED_PRELOADED_MEDIA) +// { +// __CheckPrivilege(PRV_PRIVILEGED_IO, checkPrivilege); +// if(!checkPrivilege) +// { +// r = E_ILLEGAL_ACCESS; +// goto CATCH; +// } +// } +// else if (pathKind == __PATH_KIND_APP_DENY) +// { +// r = E_ILLEGAL_ACCESS; +// goto CATCH; +// } + + pFile = fopen(pFilePath.get(), "r"); + if (pFile == null) + { + r = __ConvertNativeErrorToResult(errno); + SysLog(NID_IO, "[%s] Failed to open file (%s) in openMode (%s), (errno: %d).", GetErrorMessage(r), pFilePath.get(), "r", errno); + goto CATCH; + } + + readItems = fread(secureHeader, 1, SECURE_FILE_HEADER_SIZE_V1 + SECURE_IO_LOF_SIZE, pFile); + + if (readItems < (SECURE_FILE_HEADER_SIZE_V1 + SECURE_IO_LOF_SIZE)) + { + int eof = feof((FILE*)pFile); + if (eof) + { + //No error; + encrypted = false; + goto CATCH; + } + + r = __ConvertNativeErrorToResult(errno); + SysLog(NID_IO, "[%s] Failed to open file (%s) in openMode (%s), (errno: %d).", GetErrorMessage(r), pFilePath.get(), "r", errno); + goto CATCH; + } + + if (memcmp(secureHeader, SECURE_FILE_HEADER_STRING, SECURE_FILE_HEADER_STRING_SIZE) == 0 && \ + memcmp(secureHeader + SECURE_FILE_HEADER_STRING_SIZE, reservedValue, SECURE_IO_STATIC_BIN_LEN) == 0) + { + encrypted = true; + } + else if (memcmp(secureHeader, SECURE_REG_HEADER_STRING, SECURE_REG_HEADER_STRING_SIZE) == 0 && \ + memcmp(secureHeader + SECURE_REG_HEADER_STRING_SIZE, reservedValue, SECURE_IO_STATIC_BIN_LEN) == 0) + { + encrypted = true; + } + else if ((memcmp(secureHeader, magicNum1, SECURE_IO_MAGIC_NUMBER_SIZE) == 0) && + (memcmp(secureHeader + SECURE_IO_STATIC_BIN_LEN, magicNum2, SECURE_IO_MAGIC_NUMBER_SIZE) == 0)) + + { + encrypted = true; + } + else + { + encrypted = false; + } + + // fall thru +CATCH: + + if (pFile) + { + fclose(pFile); + } + + SetLastResult(r); + return encrypted; +} +#endif + +bool +_FileUtil::IsAppPath(const String& filePath) +{ + result r = E_SUCCESS; + + if (VerifyFilePath(filePath, FILEPATH_TYPE_APP)) + { + SetLastResult(E_SUCCESS); + return true; + } + r = GetLastResult(); + + SetLastResult(r); + return false; +} + +bool +_FileUtil::IsMediaPath(const String& filePath) +{ + result r = E_SUCCESS; + + if (VerifyFilePath(filePath, FILEPATH_TYPE_MEDIA)) + { + SetLastResult(E_SUCCESS); + return true; + } + r = GetLastResult(); + + SetLastResult(r); + return false; +} + +bool +_FileUtil::IsSystemPath(const String& filePath) +{ + result r = E_SUCCESS; + + if (VerifyFilePath(filePath, FILEPATH_TYPE_SYSTEM)) + { + SetLastResult(E_SUCCESS); + return true; + } + r = GetLastResult(); + + SetLastResult(r); + return false; +} + +bool +_FileUtil::VerifyFilePath(const String& filePath, _FilePathType pathType) +{ + result r = E_SUCCESS; + String tmpStr(""); + String absolutePath(""); + int i = 0; + int index = 0; + int pathCount = 0; + char** ppPathList = null; + bool candidateFound = false; + wchar_t ch = L'\0'; + + //TODO Apply realpath after data caging. + // + //char resolved_path[1024]; + //char* pFilePath = _StringConverter::CopyToCharArrayN(filePath); + // + //r = GetLastResult(); + // + //SysTryCatch(NID_IO, pFilePath != null, + // r, r, "[%s] Failed to get file path", GetErrorMessage(r)); + + + //SysLog(NID_IO, "convert: %s", pFilePath); + //if (realpath(pFilePath, resolved_path) !=0) + //{ + // r = __ConvertNativeErrorToResult(errno); + // SysLog(NID_IO, "convert Error!!! [%s] %s", resolved_path, GetErrorMessage(r)); + // delete[] pFilePath; + // return false; + // } + // + //SysLog(NID_IO, "convert result: %s", resolved_path); + //absolutePath.Append(resolved_path); + //delete[] pFilePath; + + absolutePath.Append(filePath); + // This code does not handle paths without prefix '/' ex: "Home/myfile" + // since it depends on cwd. + switch (pathType) + { + case FILEPATH_TYPE_APP: + pathCount = MAX_FILEPATH_APP; + ppPathList = const_cast (filePathAppPrefix); + break; + + case FILEPATH_TYPE_MEDIA: + pathCount = MAX_FILEPATH_MEDIA; + ppPathList = const_cast (filePathMediaPrefix); + break; + + case FILEPATH_TYPE_SYSTEM: + pathCount = MAX_FILEPATH_SYSTEM; + ppPathList = const_cast (filePathSystemPrefix); + break; + + default: + r = E_INVALID_ARG; + goto CATCH; + } + + absolutePath.GetCharAt(absolutePath.GetLength() - 1, ch); + if (ch != L'/') // if last char of absolutePath is not '/' then append it to make path parsing easier + { + absolutePath.Append(L'/'); + } + + for (i = 0; i < pathCount; i++) + { + tmpStr.Clear(); + tmpStr.Append(ppPathList[i]); + + if (absolutePath.IndexOf(tmpStr, 0, index) == E_SUCCESS) + { + if (index == 0) + { + ch = L'\0'; + if (absolutePath.GetCharAt(tmpStr.GetLength(), ch) == E_SUCCESS) + { + if (ch == L'/') // validate exact path. paths like /Home123/file.txt is not supported. + { + candidateFound = true; + break; + } + } + } + } + } + + if (candidateFound == true) + { + r = E_SUCCESS; + } + else + { + r = E_INVALID_ARG; + } + + // fall thru +CATCH: + SetLastResult(r); + + if (r == E_SUCCESS) + { + return true; + } + + return false; +} + +result +_FileUtil::ConvertToSecureFile(const String& plainFilePath, const String& secureFilePath, const ByteBuffer* pKey) +{ + SysTryReturnResult(NID_IO, plainFilePath.GetLength() > 0 && plainFilePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "Invalid argument was passed. Given file name length is not correct!"); + SysTryReturnResult(NID_IO, plainFilePath.EndsWith(L"/") == false, E_INVALID_ARG, + "Invalid argument was passed. Given file name is not correct! - ends with '/'"); + + SysTryReturnResult(NID_IO, secureFilePath.GetLength() > 0 && secureFilePath.GetLength() <= PATH_MAX, E_INVALID_ARG, + "Invalid argument was passed. Given file name length is not correct!"); + SysTryReturnResult(NID_IO, secureFilePath.EndsWith(L"/") == false, E_INVALID_ARG, + "Invalid argument was passed. Given file name is not correct! - ends with '/'"); + + int fileSize = 0; + int readSize = 0; + int lastBlockSize = 0; + int bufferSize = 0; + int blockCount = 0; + int count = 0; + unique_ptr pBuffer(null); + result r = E_SUCCESS; + + if (File::IsFileExist(secureFilePath)) + { + r = GetLastResult(); + if (!IsFailed(r)) + { + r = E_FILE_ALREADY_EXIST; + SysLog(NID_IO, "[E_FILE_ALREADY_EXIST] The secure file already exist."); + } + else + { + SysLog(NID_IO, "[%s] Propagated.", GetErrorMessage(r)); + } + return r; + } + + unique_ptr pFile(new (std::nothrow) File()); + SysTryReturnResult(NID_IO, pFile != null, E_OUT_OF_MEMORY, "Unable to create Io::File"); + + r = pFile->Construct(plainFilePath, L"r", false); + if (IsFailed(r)) + { + if (r == E_MAX_EXCEEDED) + { + r = E_IO; + } + SysLog(NID_IO, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + + r = pFile->Seek(FILESEEKPOSITION_END, 0); + SysTryReturn(NID_IO, r == E_SUCCESS , r, r, "[%s] Propagated", GetErrorMessage(r)); + + fileSize = pFile->Tell(); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryReturn(NID_IO, r == E_SUCCESS , r, r, "[%s] Propagated", GetErrorMessage(r)); + + unique_ptr pSecureFile(new (std::nothrow) File()); + SysTryReturnResult(NID_IO, pSecureFile != null, E_OUT_OF_MEMORY, + "Unable to create Io::File"); + + r = pSecureFile->Construct(secureFilePath, "w", *pKey); + SysTryReturn(NID_IO, r == E_SUCCESS , r, r, "[%s] Propagated", GetErrorMessage(r)); + + if (fileSize == 0) + { + return r; + } + + lastBlockSize = fileSize % CIPHER_BLOCK_SIZE; + if (lastBlockSize == 0) + { + blockCount = fileSize / CIPHER_BLOCK_SIZE; + lastBlockSize = CIPHER_BLOCK_SIZE; + } + else + { + blockCount = fileSize / CIPHER_BLOCK_SIZE + 1; + } + + for(count = 0; count < blockCount; count++) + { + if (pBuffer != null) + { + memset(pBuffer.get(), 0, CIPHER_BLOCK_SIZE); + } + + if ((count + 1) == blockCount && pBuffer == null) + { + pBuffer.reset(new (std::nothrow) byte[lastBlockSize]); + SysTryReturnResult(NID_IO, pBuffer != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + memset(pBuffer.get(), 0, lastBlockSize); + bufferSize = lastBlockSize; + } + + else if ((count + 1) != blockCount && pBuffer == null) + { + pBuffer.reset(new (std::nothrow) byte[CIPHER_BLOCK_SIZE]); + SysTryReturnResult(NID_IO, pBuffer != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + memset(pBuffer.get(), 0, CIPHER_BLOCK_SIZE); + bufferSize = CIPHER_BLOCK_SIZE; + } + + readSize = pFile->Read(pBuffer.get(), bufferSize); + r = GetLastResult(); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; + } + SysLog(NID_IO, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + + r = pSecureFile->Write(pBuffer.get(), readSize); + SysTryReturn(NID_IO, r == E_SUCCESS , r, r, "[%s] Propagated", GetErrorMessage(r)); + } + + return E_SUCCESS; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_IIpcClientEventListener.cpp b/src/io/FIo_IIpcClientEventListener.cpp new file mode 100644 index 0000000..4b99dca --- /dev/null +++ b/src/io/FIo_IIpcClientEventListener.cpp @@ -0,0 +1,36 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IIpcClientEventListener.cpp + * @brief This is the implementation file for the _IIpcClientEventListener class. + * + */ + + +#include "FIo_IIpcClientEventListener.h" + +namespace Tizen { namespace Io +{ + + +_IIpcClientEventListener::~_IIpcClientEventListener(void) +{ + +} + +} } // Tizen::Io diff --git a/src/io/FIo_IIpcServerEventListener.cpp b/src/io/FIo_IIpcServerEventListener.cpp new file mode 100644 index 0000000..36598b6 --- /dev/null +++ b/src/io/FIo_IIpcServerEventListener.cpp @@ -0,0 +1,34 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IIpcServerEventListener.cpp + * @brief This is the implementation file for the _IIpcServerEventListener class. + * + */ + +#include "FIo_IIpcServerEventListener.h" + +namespace Tizen { namespace Io +{ + +_IIpcServerEventListener::~_IIpcServerEventListener(void) +{ + +} + +} } // Tizen::Io diff --git a/src/io/FIo_IpcClient.cpp b/src/io/FIo_IpcClient.cpp new file mode 100644 index 0000000..1b788bc --- /dev/null +++ b/src/io/FIo_IpcClient.cpp @@ -0,0 +1,594 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IpcClient.cpp + * @brief This is the implementation file for the _IpcClient class. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include "FIo_IpcClient.h" +#include "FIo_IIpcClientEventListener.h" + +using namespace IPC; +using namespace std; +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Io +{ + +_IpcClient::_IpcClient(void) + : __pReverseSource(null) + , __fdCount(0) + , __pFdLock(null) + , __name("") + , __pListener(null) +{ + __messageBuffer[0] = '\0'; +} + +_IpcClient::~_IpcClient(void) +{ + int fd = 0; + + if (__pReverseSource != null) + { + g_source_destroy(__pReverseSource); + g_source_unref(__pReverseSource); + __pReverseSource = null; + } + + while (__fds.size() > 0) + { + fd = __fds.back(); + __fds.pop_back(); + + close(fd); + } + + delete __pFdLock; +} + +result +_IpcClient::Construct(const String& name, const _IIpcClientEventListener* pListener) +{ + SysAssertf(__pFdLock == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + result r = E_SUCCESS; + Mutex* pMutex = null; + + __name = name; + __pListener = const_cast <_IIpcClientEventListener*>(pListener); + + pMutex = new (std::nothrow) Mutex(); + SysTryReturnResult(NID_IO, pMutex != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pMutex->Create(); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to create SourceLock.", GetErrorMessage(r)); + + __pFdLock = pMutex; + + r = MakeConnection(); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to connect to server.", GetErrorMessage(r)); + + if (__pListener) + { + r = MakeConnection(true); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to connect to server.", GetErrorMessage(r)); + } + + return E_SUCCESS; + +CATCH: + __name = ""; + __pListener = null; + __pFdLock = null; + + delete pMutex; + + return r; +} + +struct HelloMessage +{ + int pid; + bool reverse; + char appId[256]; + char appExecutableName[256]; +}; + +result +_IpcClient::MakeConnection(bool forReverse) +{ + result r = E_SUCCESS; + + struct sockaddr_un server; + socklen_t serverLen = 0; + int client = -1; + int ret = 0; + HelloMessage helloMessage = {0, false}; + std::string socketName; + char* pSocketName = null; + size_t socketNameLength = 0; + int flags = 0; + + helloMessage.pid = getpid(); + helloMessage.reverse = forReverse; + + pSocketName = _StringConverter::CopyToCharArrayN(__name); + SysTryReturnResult(NID_IO, pSocketName != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + socketName.append("/tmp/"); + socketName.append(pSocketName); + + delete[] pSocketName; + + socketNameLength = socketName.size() + 1; + SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long."); + + if (__fdCount == 0) + { + // Set an appId + String appId = _AppInfo::GetAppId(); + int length = (appId.GetLength() + 1) * sizeof(wchar_t); + if (length > 255) + { + length = 255; + } + + SysTryReturnResult(NID_IO, appId.GetLength() > 0, E_SYSTEM, "AppId dose not exist."); + + memcpy(helloMessage.appId, appId.GetPointer(), length); + + // Set an executableName + //String appExecutableName = _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(appId); + String appExecutableName = _AppInfo::GetAppExecutableName(); + length = (appExecutableName.GetLength() + 1) * sizeof(wchar_t); + if (length > 255) + { + length = 255; + } + + //SysTryReturnResult(NID_IO, appExecutableName.GetLength() > 0, E_SYSTEM, "App Executable name of AppId(%ls) dose not exist.", appId.GetPointer()); + if (appExecutableName.GetLength() != 0) + { + memcpy(helloMessage.appExecutableName, appExecutableName.GetPointer(), length); + } + } + + client = socket(AF_UNIX, SOCK_STREAM, 0); + SysTryCatch(NID_IO, client != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to create a socket : %s.", strerror(errno)); + + flags = fcntl(client, F_GETFL, 0); + ret = fcntl(client, F_SETFL, flags | O_NONBLOCK); + SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).", + errno, strerror(errno)); + + bzero(&server, sizeof(server)); + server.sun_family = AF_UNIX; + strncpy(server.sun_path, socketName.c_str(), socketNameLength); + serverLen = sizeof(server); + + ret = connect(client, (struct sockaddr*) &server, serverLen); + if (ret != 0) + { + SysTryCatch(NID_IO, errno == EINPROGRESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s", + socketName.c_str(), strerror(errno)); + + fd_set rset; + fd_set wset; + struct timeval timeout; + int length = 0; + int error = 0; + socklen_t socketLength = 0; + + FD_ZERO(&rset); + FD_SET(client, &rset); + wset = rset; + timeout.tv_sec = 10; // FIXME: replace 10 with const int + timeout.tv_usec = 0; + + // FIXME: + // replace select with poll + while (true) + { + ret = select(client+1, &rset, &wset, NULL, &timeout); + if (ret < 0) + { + SysTryCatch(NID_IO, errno == EINTR , r = E_SYSTEM, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error."); + + continue; + } + else if (ret == 0) + { + r = E_TIMEOUT; + SysLogException(NID_IO, E_TIMEOUT, "[E_TIMEOUT] Failed to connect due to timeout."); + goto CATCH; + } + else + { + break; + } + } + + if (FD_ISSET(client, &rset) || FD_ISSET(client, &wset)) + { + length = sizeof(error); + ret = getsockopt(client, SOL_SOCKET, SO_ERROR, &error, &socketLength); + SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to connect to server(%s) : %s", + socketName.c_str(), strerror(errno)); + } + else + { + r = E_SYSTEM; + SysLogException(NID_IO, E_SYSTEM, "[E_TIMEOUT] Failed to connect due to system error."); + goto CATCH; + } + } + + ret = fcntl(client, F_SETFL, flags); + SysTryCatch(NID_IO, ret >= 0 , r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set file status flags (%d, %s).", + errno, strerror(errno)); + + write(client, &helloMessage, sizeof(helloMessage)); + + if (forReverse) + { + GError* pGError = null; + GSource* pGSource = null; + ; + GIOChannel* pChannel = g_io_channel_unix_new(client); + GMainContext* pGMainContext = g_main_context_default(); + + g_io_channel_set_encoding(pChannel, null, &pGError); + g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError); + g_io_channel_set_close_on_unref(pChannel, TRUE); + + pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP)); + g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, this, null); + g_source_attach(pGSource, pGMainContext); + + g_io_channel_unref(pChannel); + __pReverseSource = pGSource; + } + else + { + ++__fdCount; + + ReleaseFd(client); + } + + return r; + +CATCH: + if (client != -1) + { + close(client); + } + + return r; +} + +gboolean +_IpcClient::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data) +{ + + _IpcClient* pIpcClient = (_IpcClient*) data; + + return pIpcClient->HandleReceivedMessage(source, condition); +} + +gboolean +_IpcClient::HandleReceivedMessage(GIOChannel* source, GIOCondition condition) +{ + GError* pGError = null; + GIOStatus status; + IPC::Message* pMessage = null; + + if (condition & G_IO_HUP) + { + g_source_destroy(__pReverseSource); + g_source_unref(__pReverseSource); + __pReverseSource = null; + + return FALSE; + } + else if (condition & G_IO_IN) + { + gsize readSize = 0; + const char* pStart = null; + const char* pEnd = null; + const char* pEndOfMessage = null; + + while (true) + { + pGError = null; + status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError); + if (status == G_IO_STATUS_EOF) + { + pGError = null; + + g_io_channel_shutdown(source, FALSE, &pGError); + + g_source_destroy(__pReverseSource); + g_source_unref(__pReverseSource); + __pReverseSource = null; + + return FALSE; + } + + if (readSize == 0) + { + break; + } + + if (__pending.empty()) + { + pStart = __messageBuffer; + pEnd = pStart + readSize; + } + else + { + __pending.append(__messageBuffer, readSize); + pStart = __pending.data(); + pEnd = pStart + __pending.size(); + } + + while (true) + { + pEndOfMessage = IPC::Message::FindNext(pStart, pEnd); + if (pEndOfMessage == null) + { + __pending.assign(pStart, pEnd - pStart); + break; + } + + pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart); + SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + if (__pListener) + { + __pListener->OnIpcResponseReceived(*this, *pMessage); + } + + delete pMessage; + + pStart = pEndOfMessage; + } + } + } + else + { + // empty statement. + } + + return TRUE; +} + +int +_IpcClient::AcquireFd(void) +{ + result r = E_SUCCESS; + int fd = -1; + + while (fd == -1) + { + __pFdLock->Acquire(); + if (__fds.size() == 0) + { + __pFdLock->Release(); + r = MakeConnection(false); + SysTryReturn(NID_IO, !IsFailed(r), -1, r, "[%s] Failed to connect to the server.", GetErrorMessage(r)); + + continue; + } + + fd = __fds.back(); + __fds.pop_back(); + + __pFdLock->Release(); + } + + return fd; +} + +void +_IpcClient::ReleaseFd(int fd) +{ + __pFdLock->Acquire(); + + __fds.push_back(fd); + + __pFdLock->Release(); +} + +result +_IpcClient::SendAsync(IPC::Message* pMessage) +{ + result r = E_SUCCESS; + + int fd = -1; + char* pData = null; + int remain = 0; + int written = 0; + + pData = (char*) pMessage->data(); + remain = pMessage->size(); + + fd = AcquireFd(); + SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd."); + + while (remain > 0) + { + written = write(fd, (char*) pData, remain); + remain -= written; + pData += written; + } + + ReleaseFd(fd); + + return r; +} + +result +_IpcClient::SendSync(IPC::Message* pMessage) +{ + result r = E_SUCCESS; + + int messageId = 0; + int fd = -1; + + char* pData = null; + int remain = 0; + int written = 0; + int readSize = 0; + char buffer[1024]; + char* pEndOfMessage = null; + + std::string message; + + struct pollfd pfd; + + IPC::Message* pReply = null; + MessageReplyDeserializer* pReplyDeserializer = null; + IPC::SyncMessage* pSyncMessage = dynamic_cast (pMessage); + SysTryReturnResult(NID_IO, pSyncMessage != null, E_INVALID_ARG, "pMessage is not a sync message."); + + messageId = SyncMessage::GetMessageId(*pSyncMessage); + + fd = AcquireFd(); + SysTryReturnResult(NID_IO, fd != -1, E_SYSTEM, "Failed to get fd."); + + pData = (char*) pSyncMessage->data(); + remain = pSyncMessage->size(); + + while (remain > 0) + { + written = write(fd, (char*) pData, remain); + remain -= written; + pData += written; + } + + // Wait reply + pfd.fd = fd; + pfd.events = POLLIN | POLLRDHUP; + pfd.revents = 0; + + while (true) + { + poll(&pfd, 1, -1); + + if (pfd.revents & POLLRDHUP) + { + return E_SYSTEM; + } + + if (pfd.revents & POLLIN) + { + readSize = read(fd, buffer, 1024); + } + + message.append(buffer, readSize); + + pEndOfMessage = (char*) IPC::Message::FindNext(message.data(), message.data() + message.size()); + if (pEndOfMessage) + { + pReply = new (std::nothrow) IPC::Message(message.data(), pEndOfMessage - message.data()); + SysTryReturnResult(NID_IO, pReply != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + break; + } + } + + pReplyDeserializer = pSyncMessage->GetReplyDeserializer(); + pReplyDeserializer->SerializeOutputParameters(*pReply); + + delete pReply; + delete pReplyDeserializer; + + ReleaseFd(fd); + + return r; +} + +result +_IpcClient::Send(IPC::Message* pMessage) +{ + result r = E_SUCCESS; + + SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n"); + + if (pMessage->is_sync()) + { + r = SendSync(pMessage); + } + else + { + r = SendAsync(pMessage); + } + + return r; +} + +result +_IpcClient::SendRequest(IPC::Message* pMessage) +{ + return Send(pMessage); +} + +result +_IpcClient::SendRequest(const IPC::Message& message) +{ + result r = E_SUCCESS; + + SysAssertf(__pFdLock != null, "Not yet constructed. Construct() should be called before use.\n"); + + if (message.is_sync()) + { + r = SendSync(const_cast(&message)); + } + else + { + r = SendAsync(const_cast(&message)); + } + + return r; +} + +} } //Tizen::Io diff --git a/src/io/FIo_IpcServer.cpp b/src/io/FIo_IpcServer.cpp new file mode 100644 index 0000000..f1a9ebc --- /dev/null +++ b/src/io/FIo_IpcServer.cpp @@ -0,0 +1,788 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IpcServer.cpp + * @brief This is the implementation file for the _IpcServer class. + * + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "FIo_IIpcServerEventListener.h" +#include "FIo_IpcServer.h" + +using namespace std; +using namespace IPC; +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +_IpcServer::_ChannelInfo::_ChannelInfo(void) + : pClientInfo(null) + , pGIOChannel(null) + , pGSource(null) + , destroySource(true) +{ + +} + +_IpcServer::_ChannelInfo::~_ChannelInfo(void) +{ + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (pGSource != null) + { + if (destroySource) + { + g_source_destroy(pGSource); + } + + g_source_unref(pGSource); + } +} + +_IpcServer::_ClientInfo::_ClientInfo(void) + : clientId(-1) + , pIpcServer(null) + , pReverseChannel(null) + , appId("") +{ + +} + +_IpcServer::_ClientInfo::~_ClientInfo(void) +{ + if (pReverseChannel != null) + { + g_io_channel_unref(pReverseChannel); + } + + channels.clear(); +} + +_IpcServer::_IpcServer(void) + : __name("") + , __runOnCallerThread(false) + , __pEventDispatcher(null) + , __pListener(null) + , __handlerThread(0) + , __pHandlerGMainContext(null) + , __pHandlerGMainLoop(null) + , __pConnectGSource(null) + , __pCurrentChannel(null) + , __pCurrentClientInfo(null) +{ + __messageBuffer[0] = '\0'; +} + + +_IpcServer::~_IpcServer(void) +{ + if (__pConnectGSource != null) + { + g_source_destroy(__pConnectGSource); + g_source_unref(__pConnectGSource); + __pConnectGSource = null; + } + + if (!__runOnCallerThread) + { + if (__pEventDispatcher) + { + delete __pEventDispatcher; + __pEventDispatcher = null; + } + + if (__pHandlerGMainLoop) + { + g_main_loop_unref(__pHandlerGMainLoop); + __pHandlerGMainLoop = null; + } + + if (__pHandlerGMainContext) + { + g_main_context_unref(__pHandlerGMainContext); + __pHandlerGMainContext = null; + } + } + + // clean-up clients + __clients.clear(); +} + +result +_IpcServer::Construct(const String& name, const _IIpcServerEventListener& listener, bool runOnCallerThread) +{ + result r = E_SUCCESS; + + GIOChannel* pGIOChannel = null; + GSource* pGSource = null; + + struct sockaddr_un serverAddress; + int serverSocket = -1; + int serverLen = 0; + int ret = 0; + std::string socketName; + char* pName = null; + size_t socketNameLength = 0; + + __name = name; + __pListener = const_cast <_IIpcServerEventListener*>(&listener); + __runOnCallerThread = runOnCallerThread; + + pName = _StringConverter::CopyToCharArrayN(name); + SysTryReturnResult(NID_IO, pName != null, E_OUT_OF_MEMORY, "Not enough memory"); + + socketName.append("/tmp/"); + socketName.append(pName); + + delete[] pName; + + socketNameLength = socketName.size() + 1; + SysTryReturnResult(NID_IO, socketNameLength < 108, E_INVALID_ARG, "Server name is too long"); + + if (!__runOnCallerThread) + { + __pHandlerGMainContext = g_main_context_new(); + __pHandlerGMainLoop = g_main_loop_new(__pHandlerGMainContext, FALSE); + + } + else + { + __pHandlerGMainContext = g_main_context_get_thread_default(); + if (__pHandlerGMainContext == null) // is global? + { + __pHandlerGMainContext = g_main_context_default(); + if (__pHandlerGMainContext == null) + { + return E_SYSTEM; + } + } + } + + ret = unlink(socketName.c_str()); + SysTryLog(NID_IO, ret == 0, "Unlink a socket has failed.. but it is not a problem."); + + serverSocket = socket(AF_UNIX, SOCK_STREAM, 0); + SysTryReturnResult(NID_IO, serverSocket != -1, E_SYSTEM, "Failed to create a socket."); + + bzero(&serverAddress, sizeof(serverAddress)); + serverAddress.sun_family = AF_UNIX; + strncpy(serverAddress.sun_path, socketName.c_str(), socketNameLength); + serverLen = sizeof(serverAddress); + + ret = bind(serverSocket, (const struct sockaddr*) &serverAddress, serverLen); + SysTryCatch(NID_IO, ret != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to bind a socket(%d, %s): %s", serverSocket, + socketName.c_str(), strerror(errno)); + + ret = chmod(socketName.c_str(), 0666); + SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to change permission of a socket(%d, %s): %s", serverSocket, + socketName.c_str(), strerror(errno)); + + listen(serverSocket, 5); + + pGIOChannel = g_io_channel_unix_new(serverSocket); + SysTryCatch(NID_IO, pGIOChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + // socket will be closed when pGIOChannel is deleted. + g_io_channel_set_close_on_unref(pGIOChannel, TRUE); + serverSocket = -1; + + pGSource = g_io_create_watch(pGIOChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP)); + SysTryCatch(NID_IO, pGSource != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] Failed to create watch for socket."); + + // channel will be delete when pGSource is deleted. + g_io_channel_unref(pGIOChannel); + pGIOChannel = null; + + g_source_set_callback(pGSource, (GSourceFunc) OnConnectionRequest, this, NULL); + g_source_attach(pGSource, __pHandlerGMainContext); + + if (__runOnCallerThread) + { + __pListener->OnIpcServerStarted(*this); + } + else + { + ret = pthread_create(&__handlerThread, null, &ThreadProc, (void*) this); + SysTryCatch(NID_IO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to an IPC thread"); + } + + __pConnectGSource = pGSource; + + return E_SUCCESS; + +CATCH: + if (pGIOChannel != null) + { + g_io_channel_unref(pGIOChannel); + } + + if (serverSocket != -1) + { + close(serverSocket); + } + + if (runOnCallerThread && __pHandlerGMainContext) + { + g_main_context_unref(__pHandlerGMainContext); + __pHandlerGMainContext = null; + } + + return r; +} + +struct HelloMessage +{ + int pid; + bool reverse; // true if the connection is for reverse message + char appId[256]; + char appExecutableName[256]; +}; + +gboolean +_IpcServer::OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data) +{ + _IpcServer* pIpcServer = (_IpcServer*) data; + GError* pGError = null; + HelloMessage helloMessage; + _ClientInfo* pClientInfo = null; + _ChannelInfo* pChannelInfo = null; + GSource* pGSource = null; + GIOChannel* pChannel = null; + + int server = -1; + int client = -1; + struct sockaddr_un clientAddress; + socklen_t clientLen = sizeof(clientAddress); + + SysAssertf(pIpcServer != null, "Not yet constructed. Construct() should be called before use.\n"); + SysAssertf(pIpcServer->__pListener != null, "Listener is null.\n"); + + server = g_io_channel_unix_get_fd(source); + + client = accept(server, (struct sockaddr*) &clientAddress, &clientLen); + SysTryCatch(NID_IO, client != -1, , E_SYSTEM, "[E_SYSTEM] Accept failed."); + + read(client, &helloMessage, sizeof(helloMessage)); + helloMessage.appId[255] = '\0'; + helloMessage.appExecutableName[255] = '\0'; + + pChannel = g_io_channel_unix_new(client); + SysTryCatch(NID_IO, pChannel != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + g_io_channel_set_encoding(pChannel, NULL, &pGError); + g_io_channel_set_flags(pChannel, G_IO_FLAG_NONBLOCK, &pGError); + + g_io_channel_set_close_on_unref(pChannel, TRUE); + client = -1; + + pClientInfo = pIpcServer->__clients[helloMessage.pid]; + if (pClientInfo == null) // first connection request from this client + { + pClientInfo = new (std::nothrow) _ClientInfo; + SysTryCatch(NID_IO, pClientInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + pClientInfo->pIpcServer = pIpcServer; + pClientInfo->clientId = helloMessage.pid; + pClientInfo->appId.Append((wchar_t*) helloMessage.appId); + pClientInfo->appExecutableName.Append((wchar_t*) helloMessage.appExecutableName); + pClientInfo->pReverseChannel = null; + + pIpcServer->__clients[helloMessage.pid] = pClientInfo; + pIpcServer->__pListener->OnIpcClientConnected(*pIpcServer, helloMessage.pid); + } + + if (helloMessage.reverse) + { + pClientInfo->pReverseChannel = pChannel; + } + else + { + pChannelInfo = new (std::nothrow) _ChannelInfo; + SysTryCatch(NID_IO, pChannelInfo != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Not enough memory."); + + pGSource = g_io_create_watch(pChannel, (GIOCondition) (G_IO_IN | G_IO_ERR | G_IO_NVAL | G_IO_HUP)); + g_source_set_callback(pGSource, (GSourceFunc) OnReadMessage, pChannelInfo, NULL); + g_source_attach(pGSource, pIpcServer->__pHandlerGMainContext); + + pChannelInfo->pClientInfo = pClientInfo; + pChannelInfo->pGIOChannel = pChannel; + pChannelInfo->pGSource = pGSource; + + pClientInfo->channels.push_back(pChannelInfo); + } + + return true; + +CATCH: + if (pChannel != null) + { + g_io_channel_unref(pChannel); + } + + if (client != -1) + { + close(client); + } + + return true; +} + +int +_IpcServer::GetClientId(void) const +{ + if (__pCurrentClientInfo) + { + return __pCurrentClientInfo->clientId; + } + + return -1; +} + +int +_IpcServer::GetClientProcessId(void) const +{ + if (__pCurrentClientInfo) + { + return __pCurrentClientInfo->clientId; + } + + return -1; +} + +AppId +_IpcServer::GetClientAppId(void) const +{ + static String nullString; + + if (__pCurrentClientInfo) + { + return __pCurrentClientInfo->appId; + } + + return nullString; +} + +String +_IpcServer::GetClientAppExecutableName(void) const +{ + static String nullString; + + if (__pCurrentClientInfo) + { + return __pCurrentClientInfo->appExecutableName; + } + + return nullString; +} + +gboolean +_IpcServer::HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data) +{ + GError* pGError = NULL; + GIOStatus status; + IPC::Message* pMessage = NULL; + _ChannelInfo* pChannelInfo = (_ChannelInfo*) data; + _ClientInfo* pClientInfo = pChannelInfo->pClientInfo; + + if (condition & G_IO_HUP) + { + SysLog(NID_IO, "Connection closed"); + int clientId = pClientInfo->clientId; + + g_io_channel_shutdown(source, FALSE, &pGError); + + for (unsigned int i = 0; i < pClientInfo->channels.size(); i++) + { + if (pChannelInfo == pClientInfo->channels[i]) + { + pClientInfo->channels.erase(pClientInfo->channels.begin() + i); + + // Do not destroy a source in a dispatch callback + // because main loop will do it if the callback return FALSE. + pChannelInfo->destroySource = false; + delete pChannelInfo; + + break; + } + } + + if (pClientInfo->channels.size() == 0) + { + SysLog(NID_IO, "All connections of client(%d) are closed. delete client info", clientId); + + __pListener->OnIpcClientDisconnected(*this, clientId); + + __clients[clientId] = null; + + delete pClientInfo; + } + + return FALSE; + } + else if (condition & G_IO_IN) + { + gsize readSize = 0; + const char* pStart = NULL; + const char* pEnd = NULL; + const char* pEndOfMessage = NULL; + + while (true) + { + pGError = null; + status = g_io_channel_read_chars(source, (char*) __messageBuffer, __MAX_MESSAGE_BUFFER_SIZE, &readSize, &pGError); + if (status != G_IO_STATUS_NORMAL) + { + if (status == G_IO_STATUS_EOF || status == G_IO_STATUS_ERROR) + { + if (status == G_IO_STATUS_EOF) + { + SysLog(NID_IO, "G_IO_STATUS_EOF, the connection is closed."); + } + else + { + SysLog(NID_IO, "G_IO_STATUS_ERROR, the connection is closed. "); + } + + pGError = null; + g_io_channel_shutdown(source, FALSE, &pGError); + + int clientId = pClientInfo->clientId; + + for (unsigned int i = 0; i < pClientInfo->channels.size(); i++) + { + if (pChannelInfo == pClientInfo->channels[i]) + { + pClientInfo->channels.erase(pClientInfo->channels.begin() + i); + + pChannelInfo->destroySource = false; + delete pChannelInfo; + break; + } + } + + if (pClientInfo->channels.size() == 0) + { + SysLog(NID_IO, "All connections of client(%d) are closed normally by the client.", clientId); + + if (__pListener) + { + __pListener->OnIpcClientDisconnected(*this, clientId); + } + + __clients[clientId] = null; + + delete pClientInfo; + } + + return FALSE; + } + } + + if (readSize == 0) + { + break; + } + + if (__pending.empty()) + { + pStart = __messageBuffer; + pEnd = pStart + readSize; + } + else + { + __pending.append(__messageBuffer, readSize); + pStart = __pending.data(); + pEnd = pStart + __pending.size(); + } + + while (true) + { + pEndOfMessage = IPC::Message::FindNext(pStart, pEnd); + if (pEndOfMessage == NULL) + { + __pending.assign(pStart, pEnd - pStart); + break; + } + + pMessage = new (std::nothrow) IPC::Message(pStart, pEndOfMessage - pStart); + SysTryReturn(NID_IO, pMessage != null, FALSE, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + __pCurrentChannel = source; + + if (__pListener) + { + __pListener->OnIpcRequestReceived(*this, *pMessage); + } + + delete pMessage; + + __pCurrentChannel = NULL; + + pStart = pEndOfMessage; + } + } + } + else + { + // empty statement + } + + return TRUE; +} + +gboolean +_IpcServer::OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data) +{ + gboolean ret = FALSE; + _ChannelInfo* pChannelInfo = (_ChannelInfo*) data; + _ClientInfo* pClientInfo = pChannelInfo->pClientInfo; + _IpcServer* pIpcServer = (_IpcServer*) pClientInfo->pIpcServer; + + pIpcServer->__pCurrentClientInfo = pClientInfo; + ret = pIpcServer->HandleReceivedMessage(source, condition, data); + pIpcServer->__pCurrentClientInfo = null; + + return ret; +} + +void* +_IpcServer::ThreadProc(void* pParam) +{ + _IpcServer* pIpcServer = (_IpcServer*) pParam; + if (pIpcServer != NULL) + { + pIpcServer->Run(NULL); + } + + return NULL; +} + +void +_IpcServer::Run(void* pParam) +{ + result r = E_SUCCESS; + + if (__pListener == null) + { + return; + } + + __pEventDispatcher = new (std::nothrow) _EventDispatcher; + SysTryReturnVoidResult(NID_IO, __pEventDispatcher != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = __pEventDispatcher->Construct(__pHandlerGMainContext); + if (IsFailed(r)) + { + delete __pEventDispatcher; + __pEventDispatcher = null; + } + + __pListener->OnIpcServerStarted(*this); + + g_main_loop_run(__pHandlerGMainLoop); + + __pListener->OnIpcServerStopped(*this); +} + +result +_IpcServer::Start(void) +{ + return E_SUCCESS; +} + +String +_IpcServer::GetName(void) const +{ + return __name; +} + +result +_IpcServer::Stop(void) +{ + result r = E_SUCCESS; + int ret = 0; + + SysTryReturnResult(NID_IO, __pListener != null, E_SYSTEM, "Listener is null."); + + if (!__runOnCallerThread) + { + pthread_t self = pthread_self(); + + if (__pHandlerGMainLoop) + { + g_main_loop_quit(__pHandlerGMainLoop); + } + + if (__handlerThread != self) + { + ret = pthread_join(__handlerThread, null); + SysTryLog(NID_IO, ret == 0, "Join an IPC thread returns an error"); + } + } + else + { + __pListener->OnIpcServerStopped(*this); + } + + return r; +} + +bool +_IpcServer::Send(IPC::Message* msg) +{ + gsize remain = 0; + gsize written = 0; + char* pData = NULL; + GError* pGError = NULL; + + + pData = (char*) msg->data(); + remain = msg->size(); + + if (msg->is_reply()) + { + while (remain > 0) + { + pGError = NULL; + g_io_channel_write_chars(__pCurrentChannel, (char*) pData, remain, &written, &pGError); + + remain -= written; + pData += written; + } + + g_io_channel_flush(__pCurrentChannel, &pGError); + } + else + { + // empty statement; + } + + return true; +} + +result +_IpcServer::SendResponse(int client, IPC::Message* pMessage) +{ + result r = E_SUCCESS; + gsize remain = 0; + gsize written = 0; + char* pData = null; + GError* pGError = null; + _ClientInfo* pClientInfo = null; + + SysTryReturn(NID_IO, client >= 0 && pMessage != null, false, E_INVALID_ARG, + "[E_INVALID_ARG] pMessage(0x%x) is null or clinet(%d) < 0", pMessage, + client); + SysTryCatch(NID_IO, !pMessage->is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee."); + + pClientInfo = __clients[client]; + SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] client(%d) has not been registered.", + client); + + pData = (char*) pMessage->data(); + remain = pMessage->size(); + + while (remain > 0) + { + pGError = NULL; + g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError); + SysTryCatch(NID_IO, pGError == null, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket."); + + remain -= written; + pData += written; + } + + g_io_channel_flush(pClientInfo->pReverseChannel, &pGError); + + delete pMessage; + + return E_SUCCESS; + +CATCH: + delete pMessage; + return r; +} + +result +_IpcServer::SendResponse(int client, const IPC::Message& message) +{ + result r = E_SUCCESS; + gsize remain = 0; + gsize written = 0; + char* pData = null; + GError* pGError = null; + _ClientInfo* pClientInfo = null; + + SysTryReturn(NID_IO, client >= 0, false, E_INVALID_ARG, "[E_INVALID_ARG] clinet(%d) < 0", client); + SysTryCatch(NID_IO, !message.is_sync(), r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Can't send sync. messagee."); + + pClientInfo = __clients[client]; + SysTryCatch(NID_IO, pClientInfo != null, r = E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] client(%d) has not been registered.", + client); + + pData = (char*) message.data(); + remain = message.size(); + + while (remain > 0) + { + pGError = NULL; + g_io_channel_write_chars(pClientInfo->pReverseChannel, (char*) pData, remain, &written, &pGError); + SysTryCatch(NID_IO, pGError == null, , E_SYSTEM, "[E_SYSTEM] Error occurred during writing message to socket."); + + remain -= written; + pData += written; + } + + g_io_channel_flush(pClientInfo->pReverseChannel, &pGError); + + return E_SUCCESS; + +CATCH: + return r; +} + +} } // Tizen::Io diff --git a/src/io/FIo_LocalMessagePortImpl.cpp b/src/io/FIo_LocalMessagePortImpl.cpp new file mode 100644 index 0000000..d25f73d --- /dev/null +++ b/src/io/FIo_LocalMessagePortImpl.cpp @@ -0,0 +1,192 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_LocalMessagePortImpl.cpp + * @brief This is the implementation file for the _LocalMessagePortImpl class. + * + */ + +#include + +#include +#include +#include +#include +#include + +#include "FIo_LocalMessagePortImpl.h" +#include "FIo_RemoteMessagePortImpl.h" +#include "FIo_MessagePortManagerImpl.h" +#include "FIo_MessagePortProxy.h" + +using namespace std; + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Collection; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +class _MessagePortEventArg + : public IEventArg +{ +public: + _MessagePortEventArg() + : __pRemotePort(null) + , __pMap(null) + { + } + RemoteMessagePort* __pRemotePort; + IMap* __pMap; +}; + +class _MessagePortEvent + : public Event +{ +protected: + virtual void FireImpl(IEventListener& listener, const IEventArg& arg) + { + IMessagePortListener* pListener = dynamic_cast (&listener); + if (pListener != null) + { + const _MessagePortEventArg* pArg = dynamic_cast(&arg); + if (pArg != null) + { + if (pArg->__pRemotePort == null) + { + pListener->OnMessageReceivedN(pArg->__pMap); + } + else + { + pListener->OnMessageReceivedN(pArg->__pRemotePort, pArg->__pMap); + } + } + } + } +}; + +_LocalMessagePortImpl::_LocalMessagePortImpl(void) + : __isTrusted(false) + , __pEvent(null) +{ + +} + +_LocalMessagePortImpl::~_LocalMessagePortImpl(void) +{ + delete __pEvent; +} + +result +_LocalMessagePortImpl::Construct(const Tizen::Base::String& port, bool isTrusted) +{ + result r = _MessagePortProxy::GetProxy()->RegisterMessagePort(port, isTrusted, *this); + SysTryReturnResult(NID_IO, r == E_SUCCESS, r, "Failed to initialize a message port."); + + _MessagePortEvent* pEvent = new (std::nothrow) _MessagePortEvent(); + SysTryReturnResult(NID_IO, pEvent != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + __pEvent = pEvent; + __port = port; + __isTrusted = isTrusted; + + return E_SUCCESS; +} + +result +_LocalMessagePortImpl::AddMessagePortListener(IMessagePortListener& listener) +{ + return __pEvent->AddListener(listener); +} + +result +_LocalMessagePortImpl::RemoveMessagePortListener(IMessagePortListener& listener) +{ + return __pEvent->RemoveListener(listener); +} + +String +_LocalMessagePortImpl::GetName(void) const +{ + return __port; +} + +bool +_LocalMessagePortImpl::IsTrusted(void) const +{ + return __isTrusted; +} + +void +_LocalMessagePortImpl::OnMessageReceivedN(IMap* pMap) +{ + _MessagePortEventArg* pEventArg= new (std::nothrow) _MessagePortEventArg(); + if(pEventArg != null) + { + pEventArg->__pMap = pMap; + __pEvent->Fire(*pEventArg); + } +} + +void +_LocalMessagePortImpl::OnMessageReceivedN(const AppId& remoteAppId, const String& remotePort, bool isTrusted, IMap* pMap) +{ + SysLog(NID_IO, "A message is received from remote port [%ls:%ls].", remoteAppId.GetPointer(), remotePort.GetPointer()); + + _MessagePortManagerImpl* pManager = _MessagePortManagerImpl::GetInstance(); + SysTryReturnVoidResult(NID_IO, pManager != null, GetLastResult(), "Propagating."); + + RemoteMessagePort* pRemotePort = pManager->GetRemoteMessagePort(remoteAppId, remotePort, isTrusted); + + _MessagePortEventArg* pEventArg = new (std::nothrow) _MessagePortEventArg(); + if(pEventArg != null) + { + pEventArg->__pRemotePort = pRemotePort; + pEventArg->__pMap = pMap; + __pEvent->Fire(*pEventArg); + } +} + +LocalMessagePort* +_LocalMessagePortImpl::GetMessagePort(const String& port, bool isTrusted) +{ + result r = E_SUCCESS; + + LocalMessagePort* pLocalMessagePort = new (std::nothrow) LocalMessagePort; + SysTryReturn(NID_IO, pLocalMessagePort != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + unique_ptr<_LocalMessagePortImpl> pImpl(new (std::nothrow) _LocalMessagePortImpl); + SysTryCatch(NID_IO, pImpl != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pImpl->Construct(port, isTrusted); + SysTryCatch(NID_IO, r == E_SUCCESS, , E_SYSTEM, "[E_SYSTEM] Failed to initialize a message port."); + + pLocalMessagePort->__pLocalMessagePortImpl = pImpl.release(); + + SetLastResult(r); + return pLocalMessagePort; + +CATCH: + delete pLocalMessagePort; + + return null; +} + +} } // Tizen::Io diff --git a/src/io/FIo_MemoryMappedFileImpl.cpp b/src/io/FIo_MemoryMappedFileImpl.cpp new file mode 100644 index 0000000..27f9ebc --- /dev/null +++ b/src/io/FIo_MemoryMappedFileImpl.cpp @@ -0,0 +1,207 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MemoryMappedFileImpl.cpp + * @brief This is the implementation file for _MemoryMappedFileImpl class. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "FIo_MemoryMappedFileImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Io +{ + +_MemoryMappedFileImpl::_MemoryMappedFileImpl(void) + : __fd(-1) +{ +} + +_MemoryMappedFileImpl::~_MemoryMappedFileImpl(void) +{ +} + +result +_MemoryMappedFileImpl::Construct(const File& file) +{ + result r = E_SUCCESS; + + const _FileImpl* pFileImpl = _FileImpl::GetInstance(file); + + __fd = fileno(pFileImpl->GetFilePointer()); + + SysTryReturnResult(NID_IO, pFileImpl->IsReadable() == true, E_INVALID_ARG, + "The specified file parameter is not opened for reading."); + + return r; +} + +void* +_MemoryMappedFileImpl::Map(void* address, long long length, unsigned long protection, unsigned long flag, long long offset) +{ + int prot = PROT_NONE; + int flags = 0x0; + result r = E_SUCCESS; + + if (protection & MEMORY_PROTECTION_MODE_READ) + { + prot |= PROT_READ; + } + if (protection & MEMORY_PROTECTION_MODE_WRITE) + { + prot |= PROT_WRITE; + } + if (protection & MEMORY_PROTECTION_MODE_EXEC) + { + prot |= PROT_EXEC; + } + + if (flag & MEMORY_MAPPED_FILE_FLAG_SHARED) + { + flags |= MAP_SHARED; + } + if (flag & MEMORY_MAPPED_FILE_FLAG_PRIVATE) + { + flags |= MAP_PRIVATE; + } + if (flag & MEMORY_MAPPED_FILE_FLAG_FIXED) + { + flags |= MAP_FIXED; + } + + void* pRetAddr = mmap(address, length, protection, flags, __fd, offset); + if (pRetAddr == MAP_FAILED) + { + switch (errno) + { + case EACCES: + r = E_ILLEGAL_ACCESS; + break; + case EAGAIN: + r = E_OBJECT_LOCKED; + break; + case EINVAL: + r = E_INVALID_ARG; + break; + case ENFILE: + r = E_MAX_EXCEEDED; + break; + case ENOMEM: + r = E_OUT_OF_MEMORY; + break; + default: + r = E_IO; + break; + } + SysLog(NID_IO, "[%s] Map() fails. errno: %d (%s)", GetErrorMessage(r), errno, strerror(errno)); + goto CATCH; + } + + SetLastResult(E_SUCCESS); + return pRetAddr; + +CATCH: + SetLastResult(r); + return null; +} + +result +_MemoryMappedFileImpl::Unmap(void* address, long long length) +{ + result r = E_SUCCESS; + + if (munmap(address, length) < 0) + { + switch (errno) + { + case EINVAL: + r = E_INVALID_ARG; + break; + default: + r = E_IO; + break; + } + SysLog(NID_IO, "[%s] Unmap() fails. errno: %d (%s)", GetErrorMessage(r), errno, strerror(errno)); + goto CATCH; + } + + return E_SUCCESS; + +CATCH: + return r; +} + +result +_MemoryMappedFileImpl::Sync(void* address, long long length, MemoryMappedFileSyncFlag syncFlag) +{ + int flags = 0x0; + result r = E_SUCCESS; + + if (syncFlag == MEMORY_MAPPED_FILE_SYNC_FLAG_ASYNC) + { + flags |= MS_ASYNC; + } + else if (syncFlag == MEMORY_MAPPED_FILE_SYNC_FLAG_SYNC) + { + flags |= MS_SYNC; + } + + if (msync(address, length, flags) < 0) + { + switch (errno) + { + case EINVAL: + // fall through + case ENOMEM: + r = E_INVALID_ARG; + break; + default: + r = E_IO; + break; + } + goto CATCH; + } + + return E_SUCCESS; + +CATCH: + SysLog(NID_IO, "[%s] Sync() fails. errno: %d (%s)", GetErrorMessage(r), errno, strerror(errno)); + return r; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_MemoryMappedFileImpl.h b/src/io/FIo_MemoryMappedFileImpl.h new file mode 100644 index 0000000..96fa036 --- /dev/null +++ b/src/io/FIo_MemoryMappedFileImpl.h @@ -0,0 +1,72 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MemoryMappedFileImpl.h + * @brief This is the header file for the %_MemoryMappedFileImpl class. + * + * This header file contains the declarations of the %_MemoryMappedFileImpl class. + */ + +#ifndef _FIO_INTERNAL_MEMORY_MAPPED_FILE_IMPL_H_ +#define _FIO_INTERNAL_MEMORY_MAPPED_FILE_IMPL_H_ + +#include + +namespace Tizen { namespace Io +{ + +class _MemoryMappedFileImpl + : public Tizen::Base::Object +{ + +public: + _MemoryMappedFileImpl(void); + + ~_MemoryMappedFileImpl(void); + + result Construct(const File& file); + + void* Map(void* address, long long length, unsigned long protection, unsigned long flag, long long offset); + + result Unmap(void* address, long long length); + + result Sync(void* address, long long length, MemoryMappedFileSyncFlag syncFlag); + +private: + /** + * This is the default copy constructor for this class. + * + * @since 2.1 + */ + _MemoryMappedFileImpl(const _MemoryMappedFileImpl& rhs); + + /** + * This is the assignment operator for this class. + * + * @since 2.1 + */ + _MemoryMappedFileImpl& operator =(const _MemoryMappedFileImpl& rhs); + + int __fd; + +}; // _MemoryMappedFileImpl + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_MEMORY_MAPPED_FILE_IMPL_H_ + diff --git a/src/io/FIo_MessagePortManagerImpl.cpp b/src/io/FIo_MessagePortManagerImpl.cpp new file mode 100644 index 0000000..ec061d5 --- /dev/null +++ b/src/io/FIo_MessagePortManagerImpl.cpp @@ -0,0 +1,229 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MessagePortManagerImpl.cpp + * @brief This is the implementation file for the _MessagePortManagerImpl class. + * + */ + +#include +#include +#include + +#include +#include +#include +#include "FIo_MessagePortManagerImpl.h" +#include "FIo_LocalMessagePortImpl.h" +#include "FIo_RemoteMessagePortImpl.h" + +using namespace std; + +using namespace Tizen::Base; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +_MessagePortManagerImpl* _MessagePortManagerImpl::__pMessagePortMgrImplInst = null; + +_MessagePortManagerImpl::_MessagePortManagerImpl(void) +{ +} + +_MessagePortManagerImpl::~_MessagePortManagerImpl(void) +{ +} + +result +_MessagePortManagerImpl::Construct(void) +{ + result r = E_SUCCESS; + + static _StringHashProvider hashProvider; + static _StringComparer stringComparer; + + r = __localPorts.Construct(0, 0, hashProvider, stringComparer); + r = __remotePorts.Construct(0, 0, hashProvider, stringComparer); + r = __trustLocalPorts.Construct(0, 0, hashProvider, stringComparer); + r = __trustRemotePorts.Construct(0, 0, hashProvider, stringComparer); + + return E_SUCCESS; +} + +void +_MessagePortManagerImpl::InitSingleton(void) +{ + unique_ptr<_MessagePortManagerImpl> pInst(new (std::nothrow) _MessagePortManagerImpl); + SysTryReturnVoidResult(NID_IO, pInst != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + result r = pInst->Construct(); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), r, "[%s] Propagating.", GetErrorMessage(r)); + + __pMessagePortMgrImplInst = pInst.release(); + + std::atexit(DestroySingleton); + return; +} + +void +_MessagePortManagerImpl::DestroySingleton(void) +{ + delete __pMessagePortMgrImplInst; +} + +_MessagePortManagerImpl* +_MessagePortManagerImpl::GetInstance(void) +{ + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + if (__pMessagePortMgrImplInst == null) + { + ClearLastResult(); + + pthread_once(&onceBlock, InitSingleton); + result r = GetLastResult(); + if (IsFailed(r)) + { + onceBlock = PTHREAD_ONCE_INIT; + SysPropagate(NID_IO, r); + } + } + + return __pMessagePortMgrImplInst; +} + +LocalMessagePort* +_MessagePortManagerImpl::RequestLocalMessagePort(const String& localPort) +{ + SysTryReturn(NID_IO, !localPort.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] The port name is empty."); + + LocalMessagePort* pMessagePort = null; + + __localPorts.GetValue(localPort, pMessagePort); + if (pMessagePort == null) + { + pMessagePort = _LocalMessagePortImpl::GetMessagePort(localPort); + SysTryReturn(NID_IO, pMessagePort != null, null, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + __localPorts.Add(localPort, pMessagePort); + } + + SetLastResult(E_SUCCESS); + return pMessagePort; +} + +RemoteMessagePort* +_MessagePortManagerImpl::RequestRemoteMessagePort(const AppId& remoteAppId, const String& remotePort) +{ + SysTryReturn(NID_IO, !remoteAppId.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] The application id is empty."); + SysTryReturn(NID_IO, !remotePort.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] The port name is empty."); + + RemoteMessagePort* pMessagePort = null; + String remoteKey(remoteAppId + remotePort); + + __remotePorts.GetValue(remoteKey, pMessagePort); + if (pMessagePort == null) + { + pMessagePort = _RemoteMessagePortImpl::GetMessagePort(remoteAppId, remotePort); + SysTryReturn(NID_IO, pMessagePort != null, null, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + __remotePorts.Add(remoteKey, pMessagePort); + } + + SetLastResult(E_SUCCESS); + return pMessagePort; +} + +LocalMessagePort* +_MessagePortManagerImpl::RequestTrustedLocalMessagePort(const String& localPort) +{ + SysTryReturn(NID_IO, !localPort.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] The port name is empty."); + + LocalMessagePort* pMessagePort = null; + + __trustLocalPorts.GetValue(localPort, pMessagePort); + if (pMessagePort == null) + { + pMessagePort = _LocalMessagePortImpl::GetMessagePort(localPort, true); + SysTryReturn(NID_IO, pMessagePort != null, null, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + __trustLocalPorts.Add(localPort, pMessagePort); + } + + SetLastResult(E_SUCCESS); + return pMessagePort; +} + +RemoteMessagePort* +_MessagePortManagerImpl::RequestTrustedRemoteMessagePort(const AppId& remoteAppId, const String& remotePort) +{ + SysTryReturn(NID_IO, !remoteAppId.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] The application id is empty."); + SysTryReturn(NID_IO, !remotePort.IsEmpty(), null, E_INVALID_ARG, "[E_INVALID_ARG] The port name is empty."); + + RemoteMessagePort* pMessagePort = null; + String remoteKey(remoteAppId + remotePort); + + __trustRemotePorts.GetValue(remoteKey, pMessagePort); + if (pMessagePort == null) + { + pMessagePort = _RemoteMessagePortImpl::GetMessagePort(remoteAppId, remotePort, true); + SysTryReturn(NID_IO, pMessagePort != null, null, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + __trustRemotePorts.Add(remoteKey, pMessagePort); + } + + SetLastResult(E_SUCCESS); + return pMessagePort; +} + +RemoteMessagePort* + _MessagePortManagerImpl::GetRemoteMessagePort(const AppId& remoteAppId, const String& remotePort, bool isTrusted) +{ + RemoteMessagePort* pMessagePort = null; + String remoteKey(remoteAppId + remotePort); + + if (!isTrusted) + { + __remotePorts.GetValue(remoteKey, pMessagePort); + } + else + { + __trustRemotePorts.GetValue(remoteKey, pMessagePort); + } + + if (pMessagePort == null) + { + pMessagePort = _RemoteMessagePortImpl::GetMessagePortOnly(remoteAppId, remotePort, isTrusted); + SysTryReturn(NID_IO, pMessagePort != null, null, GetLastResult(), "[%s] Propagating.", GetErrorMessage(GetLastResult())); + + if (!isTrusted) + { + __remotePorts.Add(remoteKey, pMessagePort); + } + else + { + __trustRemotePorts.Add(remoteKey, pMessagePort); + } + } + + SetLastResult(E_SUCCESS); + return pMessagePort; +} + +} } // Tizen::Io diff --git a/src/io/FIo_MessagePortMessages.cpp b/src/io/FIo_MessagePortMessages.cpp new file mode 100644 index 0000000..0fa5421 --- /dev/null +++ b/src/io/FIo_MessagePortMessages.cpp @@ -0,0 +1,26 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MessagePortMessages.cpp + * @brief This is the implementation file for the MessagePortMessages class. + * + */ + + +#define IPC_MESSAGE_IMPL +#include "FIo_MessagePortMessages.h" diff --git a/src/io/FIo_MessagePortProxy.cpp b/src/io/FIo_MessagePortProxy.cpp new file mode 100644 index 0000000..4f4ebb3 --- /dev/null +++ b/src/io/FIo_MessagePortProxy.cpp @@ -0,0 +1,342 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MessagePortProxy.cpp + * @brief This is the implementation file for the _MessagePortProxy class. + * + */ + +#include +#include + +#include + +#include +#include +#include +#include "FIo_IpcClient.h" +#include "FIo_MessagePortProxy.h" +#include "FIo_MessagePortMessages.h" + +using namespace std; + +using namespace Tizen::App; +using namespace Tizen::Io; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Io +{ + +_MessagePortProxy::_MessagePortProxy(void) + : __pIpcClient(null) +{ +} + +_MessagePortProxy::~_MessagePortProxy(void) +{ +} + +result +_MessagePortProxy::Construct(void) +{ + SysAssertf(__pIpcClient == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + result r = E_SUCCESS; + + static _StringHashProvider hashProvider; + static _StringComparer stringComparer; + + __listeners.Construct(0, 0, hashProvider, stringComparer); + __trustedListeners.Construct(0, 0, hashProvider, stringComparer); + + unique_ptr<_IpcClient> pIpcClient(new (std::nothrow) _IpcClient); + SysTryReturnResult(NID_IO, pIpcClient != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pIpcClient->Construct("osp.io.ipcserver.messageportmanager", this); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to connect to IPC server.", GetErrorMessage(r)); + + __pIpcClient = pIpcClient.release(); + + const String& appId = _AppInfo::GetAppId(); + const String& appExecutableName = _AppInfo::GetAppExecutableName(); + + __appId.Append(appId); + __appId.Append(L'.'); + __appId.Append(appExecutableName); + + return E_SUCCESS; +} + + +void +_MessagePortProxy::OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message) +{ + IPC_BEGIN_MESSAGE_MAP(_MessagePortProxy, message) + IPC_MESSAGE_HANDLER_EX(MessagePortService_sendMessageAsync, &client, OnSendMessage) + IPC_MESSAGE_HANDLER_EX(MessagePortService_sendBidirMessageAsync, &client, OnSendBidirMessage) + IPC_END_MESSAGE_MAP_EX() +} + +result +_MessagePortProxy::RegisterMessagePort(const String& localPort, bool isTrusted, + const _IMessagePortListener& listener) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "Register a message port : [%ls:%ls]", __appId.GetPointer(), localPort.GetPointer()); + + result r = E_SUCCESS; + int ret = 0; + bool contain = false; + String key = localPort; + + if (!isTrusted) + { + __listeners.ContainsKey(key, contain); + + if (!contain) + { + __listeners.Add(key, const_cast<_IMessagePortListener*>(&listener)); + + } + else + { + __listeners.SetValue(key, const_cast<_IMessagePortListener*>(&listener)); + } + } + else + { + __trustedListeners.ContainsKey(key, contain); + + if (!contain) + { + __trustedListeners.Add(key, const_cast<_IMessagePortListener*>(&listener)); + + } + else + { + __trustedListeners.SetValue(key, const_cast<_IMessagePortListener*>(&listener)); + } + + } + + unique_ptr pMsg(new (std::nothrow) MessagePortService_register(__appId, localPort, isTrusted, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + SysTryReturnResult(NID_IO, r == E_SUCCESS, r, "Failed to register a message port.", GetErrorMessage(r)); + SysTryReturnResult(NID_IO, ret == E_SUCCESS, ret, "Failed to register a message port.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +result +_MessagePortProxy::RequestRemotePort(const AppId& remoteAppId, + const String& remotePort, + bool isTrusted) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "Request a remote message port [%ls:%ls]", remoteAppId.GetPointer(), remotePort.GetPointer()); + + result r = E_SUCCESS; + int ret = 0; + + if (isTrusted) + { + package_manager_compare_result_type_e res; + + unique_ptr pLocal(_StringConverter::CopyToCharArrayN(__appId)); + unique_ptr pRemote(_StringConverter::CopyToCharArrayN(remoteAppId)); + + if (package_manager_compare_app_cert_info(pLocal.get(), pRemote.get(), &res) == 0) + { + if (res != PACAKGE_MANAGER_COMPARE_MATCH) + { + SysLogException(NID_IO, E_CERTIFICATE_VERIFICATION_FAILED, "[E_CERTIFICATE_VERIFICATION_FAILED] The target application is not signed with the same certificate."); + return E_CERTIFICATE_VERIFICATION_FAILED; + } + } + else + { + SysLogException(NID_IO, E_SYSTEM, "[E_SYSTEM] Failed to compare the cerificate infomation."); + return E_SYSTEM; + } + } + + unique_ptr pMsg(new (std::nothrow) MessagePortService_requestRemotePort(remoteAppId, remotePort, isTrusted, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + SysTryReturnResult(NID_IO, r == E_SUCCESS, r, "Failed to request a message port.", GetErrorMessage(r)); + SysTryReturnResult(NID_IO, ret == E_SUCCESS, ret, "Failed to request a message port.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +result +_MessagePortProxy::SendMessage(const AppId& remoteAppId, const String& remotePort, bool isTrusted, const HashMap* pMap) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysLog(NID_IO, "Send a unidirectional message to remote port [%ls:%ls]", remoteAppId.GetPointer(), remotePort.GetPointer()); + + result r = E_SUCCESS; + int ret = 0; + + if (pMap != null) + { + unique_ptr pMsg(new (std::nothrow) MessagePortService_sendMessage(remoteAppId, remotePort, isTrusted, *pMap, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + r = __pIpcClient->SendRequest(pMsg.get() ); + } + + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to send a message.", GetErrorMessage(r)); + SysTryReturn(NID_IO, ret == E_SUCCESS, ret, ret, "[%s] Failed to send a message.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +result +_MessagePortProxy::SendMessage(const String& localPort, bool isTrustedLocal, const AppId& remoteAppId, const String& remotePort, bool isTrustedRemote, const HashMap* pMap) +{ + SysAssertf(__pIpcClient != null, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + int ret = 0; + + SysLog(NID_IO, "Send a bidirectional message from [%ls:%ls] to [%ls:%ls]", __appId.GetPointer(), localPort.GetPointer(), remoteAppId.GetPointer(), remotePort.GetPointer()); + + if (pMap != null) + { + if (!isTrustedRemote) + { + unique_ptr pMsg(new (std::nothrow) MessagePortService_sendBidirMessage(__appId, localPort, isTrustedLocal, remoteAppId, remotePort, *pMap, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + r = __pIpcClient->SendRequest(pMsg.get()); + } + else + { + unique_ptr pMsg(new (std::nothrow) MessagePortService_sendTrustedBidirMessage(__appId, localPort, isTrustedLocal, remoteAppId, remotePort, *pMap, &ret)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + r = __pIpcClient->SendRequest(pMsg.get()); + } + } + + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Failed to send a message.", GetErrorMessage(r)); + SysTryReturn(NID_IO, ret == E_SUCCESS, ret, ret, "[%s] Failed to send a message.", GetErrorMessage(ret)); + + return E_SUCCESS; +} + +bool +_MessagePortProxy::OnSendMessage(const String& localPort, bool isTrusted, const HashMap& map) +{ + SysLog(NID_IO, "A message is received to local port [%ls:%ls].", __appId.GetPointer(), localPort.GetPointer()); + + _IMessagePortListener* pListener = null; + + String key = localPort; + + if (!isTrusted) + { + __listeners.GetValue(key, pListener); + } + else + { + __trustedListeners.GetValue(key, pListener); + } + + HashMap* pMap = new (std::nothrow) HashMap(SingleObjectDeleter); + SysTryReturn(NID_IO, pMap != null, false, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pMap->Construct(map); + + if (pListener) + { + pListener->OnMessageReceivedN(pMap); + + return true; + } + else + { + delete pMap; + } + + return false; +} + +bool +_MessagePortProxy::OnSendBidirMessage(const String& localPort, bool isTrustedLocal, const AppId& remoteAppId, const String& remotePort, bool isTrustedRemote, const HashMap& map) +{ + SysLog(NID_IO, "A message is received to local port [%ls:%ls], from remote port [%ls:%ls].", __appId.GetPointer(), localPort.GetPointer(), remoteAppId.GetPointer(), remotePort.GetPointer()); + + _IMessagePortListener* pListener = null; + + String key = localPort; + + if (!isTrustedLocal) + { + __listeners.GetValue(key, pListener); + } + else + { + __trustedListeners.GetValue(key, pListener); + } + + HashMap* pMap = new (std::nothrow) HashMap(SingleObjectDeleter); + SysTryReturn(NID_IO, pMap != null, false, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pMap->Construct(map); + + if (pListener) + { + pListener->OnMessageReceivedN(remoteAppId, remotePort, isTrustedRemote, pMap); + return true; + } + else + { + delete pMap; + } + + return false; +} + +_MessagePortProxy* +_MessagePortProxy::GetProxy(void) +{ + static _MessagePortProxy* pProxy = null; + + if (pProxy == null) + { + unique_ptr<_MessagePortProxy> p(new (std::nothrow) _MessagePortProxy); + SysTryReturn(NID_IO, p != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + result r = p->Construct(); + SysTryReturn(NID_IO, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] Failed to initialize a message port proxy."); + + pProxy = p.release(); + } + + SetLastResult(E_SUCCESS); + return pProxy; +} + +}} diff --git a/src/io/FIo_MmcStorageManagerImpl.cpp b/src/io/FIo_MmcStorageManagerImpl.cpp new file mode 100644 index 0000000..a2e761a --- /dev/null +++ b/src/io/FIo_MmcStorageManagerImpl.cpp @@ -0,0 +1,206 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MmcStorageManagerImpl.cpp + * @brief This is the implementation file for _MmcStorageManagerImpl class. + */ + +#include +#include +#include + +#include +#include +#include + +#include "FIo_MmcStorageManagerProxy.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +_MmcStorageManagerImpl::_MmcStorageManagerImpl(void) + : __pMmcStorageManagerProxy(null) +{ +} + +_MmcStorageManagerImpl::~_MmcStorageManagerImpl(void) +{ +} + +result +_MmcStorageManagerImpl::Construct(void) +{ + result r = E_SUCCESS; + + std::unique_ptr<_MmcStorageManagerProxy> pMmcStorageManagerProxy(new (std::nothrow) _MmcStorageManagerProxy); + SysTryReturnResult(NID_IO, pMmcStorageManagerProxy != null, E_OUT_OF_MEMORY, "The memory is insufficient"); + + r = pMmcStorageManagerProxy->Construct(this); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] __pMmcStorageManagerProxy->Construct() failed.", GetErrorMessage(r)); + + __pMmcStorageManagerProxy = pMmcStorageManagerProxy.release(); + + return E_SUCCESS; +} + +_MmcStorageManagerImpl* +_MmcStorageManagerImpl::GetInstance(void) +{ + static _MmcStorageManagerImpl* pImpl = null; + if (pImpl == null) + { + std::unique_ptr<_MmcStorageManagerImpl> p(new (std::nothrow) _MmcStorageManagerImpl); + SysTryReturn(NID_IO, p != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + result r = p->Construct(); + SysTryReturn(NID_IO, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] Failed to initialize channel."); + + pImpl = p.release(); + } + + return pImpl; + +} + +result +_MmcStorageManagerImpl::Mount(void) +{ + return __pMmcStorageManagerProxy->Mount(); +} + +result +_MmcStorageManagerImpl::Unmount(void) +{ + return __pMmcStorageManagerProxy->Unmount(); +} + +result +_MmcStorageManagerImpl::Format(void) +{ + return __pMmcStorageManagerProxy->Format(); +} + +result +_MmcStorageManagerImpl::AddMmcStorageMountListener(IMmcStorageMountListener& listener) +{ + result r = __pMmcMountListener.Add(&listener); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_MmcStorageManagerImpl::RemoveMmcStorageMountListener(IMmcStorageMountListener& listener) +{ + result r = __pMmcMountListener.Remove(&listener); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_MmcStorageManagerImpl::AddMmcStorageFormatListener(IMmcStorageFormatListener& listener) +{ + result r = __pMmcFormatListener.Add(&listener); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_MmcStorageManagerImpl::RemoveMmcStorageFormatListener(IMmcStorageFormatListener& listener) +{ + result r = E_SUCCESS; + + r = __pMmcFormatListener.Remove(&listener); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagating.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_MmcStorageManagerImpl::OnMmcMountResponseReceived(result r) +{ + std::unique_ptr< IEnumeratorT< IMmcStorageMountListener* > > + pEnum(__pMmcMountListener.GetEnumeratorN()); + if (pEnum.get()) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + IMmcStorageMountListener* pListener = null; + pEnum->GetCurrent(pListener); + if (pListener != null) + { + SysLog(NID_IO, "Final Mount() response sent to Application : [%s]", GetErrorMessage(r)); + pListener->OnMmcStorageMounted(r); + } + } + } + + return E_SUCCESS; +} + +result +_MmcStorageManagerImpl::OnMmcUnmountResponseReceived(result r) +{ + std::unique_ptr< IEnumeratorT< IMmcStorageMountListener* > > + pEnum(__pMmcMountListener.GetEnumeratorN()); + if (pEnum.get()) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + IMmcStorageMountListener* pListener = null; + pEnum->GetCurrent(pListener); + if (pListener != null) + { + SysLog(NID_IO, "Final Unmount() response sent to Application : [%s]", GetErrorMessage(r)); + pListener->OnMmcStorageUnmounted(r); + } + } + } + + return E_SUCCESS; +} + +result +_MmcStorageManagerImpl::OnMmcFormatResponseReceived(result r) +{ + std::unique_ptr > + pEnum(__pMmcFormatListener.GetEnumeratorN()); + if (pEnum.get()) + { + while (pEnum->MoveNext() == E_SUCCESS) + { + IMmcStorageFormatListener* pListener = null; + pEnum->GetCurrent(pListener); + if (pListener != null) + { + SysLog(NID_IO, "Final Format() response sent to Application : [%s]", GetErrorMessage(r)); + pListener->OnMmcStorageFormatted(r); + } + } + } + + return E_SUCCESS; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_MmcStorageManagerIpcMessages.cpp b/src/io/FIo_MmcStorageManagerIpcMessages.cpp new file mode 100644 index 0000000..ebc60aa --- /dev/null +++ b/src/io/FIo_MmcStorageManagerIpcMessages.cpp @@ -0,0 +1,46 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MmcStorageManagerIpcMessages.cpp + * @brief This file contains IPC message class generated by macros. + */ + +#define IPC_MESSAGE_IMPL +#include "FIo_MmcStorageManagerIpcMessages.h" + +// Generate constructors. +#include "ipc/struct_constructor_macros.h" +#include "FIo_MmcStorageManagerIpcMessages.h" +// Generate destructors. + +#include "ipc/struct_destructor_macros.h" +#include "FIo_MmcStorageManagerIpcMessages.h" + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC +{ +#include "FIo_MmcStorageManagerIpcMessages.h" +} // namespace IPC + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC +{ +#include "FIo_MmcStorageManagerIpcMessages.h" +} // namespace IPC diff --git a/src/io/FIo_MmcStorageManagerProxy.cpp b/src/io/FIo_MmcStorageManagerProxy.cpp new file mode 100644 index 0000000..b1d9f73 --- /dev/null +++ b/src/io/FIo_MmcStorageManagerProxy.cpp @@ -0,0 +1,141 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MmcStorageManagerProxy.cpp + * @brief This is the implementation for the _MmcStorageManagerProxy class. + */ + +#include +#include + +#include +#include +#include + +#include "FIo_IMmcStorageServiceEventListener.h" +#include "FIo_MmcStorageManagerProxy.h" +#include "FIo_MmcStorageManagerIpcMessages.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +_IMmcStorageServiceEventListener* _MmcStorageManagerProxy::__pImpl = null; + +_MmcStorageManagerProxy::_MmcStorageManagerProxy(void) + : __pIpcClient(null) +{ +} + +_MmcStorageManagerProxy::~_MmcStorageManagerProxy(void) +{ + delete __pIpcClient; +} + +result +_MmcStorageManagerProxy::Construct(_IMmcStorageServiceEventListener* pImpl) +{ + __pIpcClient = new (std::nothrow) _IpcClient(); + SysTryReturnResult(NID_IO, __pIpcClient != null, E_OUT_OF_MEMORY, "_IpcClient creation failed."); + + result r = __pIpcClient->Construct("osp.io.ipcserver.mmcstoragemanager", this); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] _IpcClient::Construct failed.", GetErrorMessage(r)); + + __pImpl = pImpl; + + return E_SUCCESS; +} + +result +_MmcStorageManagerProxy::Mount(void) +{ + SysTryReturnResult(NID_IO, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) MmcStorageManager_Mount(&response)); + result r = __pIpcClient->SendRequest(pMsg.get()); + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] SendRequest is failed.", GetErrorMessage(r)); + + SysLog(NID_IO, "Received sync mount response msg from server is: [%s]\n", GetErrorMessage(response)); + return response; +} + +result +_MmcStorageManagerProxy::Unmount(void) +{ + SysTryReturnResult(NID_IO, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) MmcStorageManager_Unmount(&response)); + result r = __pIpcClient->SendRequest(pMsg.get()); + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] SendRequest is failed.", GetErrorMessage(r)); + + SysLog(NID_IO, "Received sync unmount response msg from server is: [%s]\n", GetErrorMessage(response)); + return response; +} + +result +_MmcStorageManagerProxy::Format(void) +{ + SysTryReturnResult(NID_IO, __pIpcClient != null, E_INVALID_STATE, "__pIpcClient instance must not be null."); + + result response = E_SUCCESS; + std::auto_ptr pMsg (new (std::nothrow) MmcStorageManager_Format(&response)); + result r = __pIpcClient->SendRequest(pMsg.get()); + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] SendRequest is failed.", GetErrorMessage(r)); + + SysLog(NID_IO, "Received sync format response msg from server is: [%s]\n", GetErrorMessage(response)); + return response; +} + +void +_MmcStorageManagerProxy::OnIpcResponseReceived(Tizen::Io::_IpcClient& client, const IPC::Message& message) +{ + IPC_BEGIN_MESSAGE_MAP(_MmcStorageManagerProxy, message) + IPC_MESSAGE_HANDLER_EX(MmcStorageManager_MountReceived, &client, MountResponseReceived) + IPC_MESSAGE_HANDLER_EX(MmcStorageManager_UnmountReceived, &client, UnmountResponseReceived) + IPC_MESSAGE_HANDLER_EX(MmcStorageManager_FormatReceived, &client, FormatResponseReceived) + IPC_END_MESSAGE_MAP() +} + +void +_MmcStorageManagerProxy::MountResponseReceived(result r) +{ + SysLog(NID_IO, "Received Async mount response msg from server is : [%s]\n", GetErrorMessage(r)); + __pImpl->OnMmcMountResponseReceived(r); +} + +void +_MmcStorageManagerProxy::UnmountResponseReceived(result r) +{ + SysLog(NID_IO, "Received Async unmount response msg from server is : [%s]\n", GetErrorMessage(r)); + __pImpl->OnMmcUnmountResponseReceived(r); +} + +void +_MmcStorageManagerProxy::FormatResponseReceived(result r) +{ + SysLog(NID_IO, "Received Async format response msg from server is : [%s]\n", GetErrorMessage(r)); + __pImpl->OnMmcFormatResponseReceived(r); +} + +} } // Tizen::Io diff --git a/src/io/FIo_NormalFile.cpp b/src/io/FIo_NormalFile.cpp new file mode 100644 index 0000000..5216c64 --- /dev/null +++ b/src/io/FIo_NormalFile.cpp @@ -0,0 +1,412 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_NormalFile.cpp + * @brief This is the implementation file for _NormalFile class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +static const int _MAX_LINE_LENGTH = 4096; + +#define _MAX_OPENMODE_LENGTH 3 + +_NormalFile::_NormalFile(void) + : __pFile(NULL) +{ +} + +_NormalFile::~_NormalFile(void) +{ + result r = E_SUCCESS; + + if (__pFile) + { + if (fclose(__pFile) != 0) + { + r = __ConvertNativeErrorToResult(errno); + SysLog(NID_IO, "[%s] Failed to close the file.", GetErrorMessage(r)); + } + __pFile = NULL; + } +} + +result +_NormalFile::Construct(const String& filePath, const char* pOpenMode) +{ + SysAssertf(__pFile == NULL, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + int fd = -1; + result r = E_SUCCESS; + + unique_ptr pFilePath(_StringConverter::CopyToCharArrayN(filePath)); + SysTryReturn(NID_IO, (pFilePath != null), GetLastResult(), GetLastResult(), ("[%s] Invalid file path."), + GetErrorMessage(GetLastResult())); + + FILE* pFile = fopen(pFilePath.get(), pOpenMode); + if (pFile == null) + { + r = __ConvertNativeErrorToResult(errno); + SysLogException(NID_IO, r, "[%s] Failed to open file (%s) in openMode (%s), errno: %d (%s).", + GetErrorMessage(r), pFilePath.get(), pOpenMode, errno, strerror(errno)); + return r; + } + + fd = fileno(pFile); + + __pFile = pFile; + __filePath = filePath; + + return E_SUCCESS; +} + +result +_NormalFile::ReadN(char** buffer, int& length) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + int fileSize = 0; + int ret = 0; + + ret = fseek(__pFile, 0, SEEK_END); + SysTryReturnResult(NID_IO, ret >= 0, E_SYSTEM, "The system I/O error occurred."); + + fileSize = ftell(__pFile); + SysTryReturnResult(NID_IO, fileSize >= 0, E_SYSTEM, "The system I/O error occurred."); + + SysLog(NID_IO, "The length of registry file (%ls) is %d.", __filePath.GetPointer(), fileSize); + if (fileSize == 0) + { + return E_SUCCESS; + } + + ret = fseek(__pFile, 0, SEEK_SET); // moves file offset to zero because of a+ open mode. + SysTryReturnResult(NID_IO, ret >= 0, E_SYSTEM, "The system I/O error occurred."); + + unique_ptr pBuffer(new (std::nothrow) char[fileSize + 1]); + SysTryReturnResult(NID_IO, pBuffer != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + memset(pBuffer.get(), 0x00, fileSize + 1); + + int readBytes = fread((void*)pBuffer.get(), 1, fileSize, __pFile); + SysTryCatch(NID_IO, readBytes > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to read registry file (%d, %s).", + errno, strerror(errno)); + + length = readBytes + 1; + *buffer = pBuffer.release(); + + // fall through +CATCH: + if (IsFailed(r)) + { + *buffer = null; + length = 0; + } + + return r; +} + +result +_NormalFile::Read(ByteBuffer& buffer) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + + int length = buffer.GetRemaining(); + if (length == 0) + { + return E_INVALID_ARG; + } + + int curPos = buffer.GetPosition(); + int bytesRead = fread((void*) (buffer.GetPointer() + curPos), 1, length, __pFile); + if (bytesRead < length) + { + SysTryReturnResult(NID_IO, !(bytesRead == 0 && feof(__pFile)), E_END_OF_FILE, "end of file"); + + if (ferror(__pFile)) + { + r = __ConvertNativeErrorToResult(errno); + SysTryReturnResult(NID_IO, !(r == E_INVALID_OPERATION), E_ILLEGAL_ACCESS, "File was not opened for reading!"); + SysLogException(NID_IO, r, "[%s] Failed to read data from file, (errno: %d)", GetErrorMessage(r), errno); + return r; + } + } + + buffer.SetPosition(curPos + bytesRead); + + return E_SUCCESS; +} + +int +_NormalFile::Read(void* buffer, int length) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + + int readBytes = fread(buffer, 1, length, __pFile); + if (readBytes < length) + { + //SysTryReturn(NID_IO, !(readBytes == 0 && feof(__pFile)), 0, E_END_OF_FILE, "[E_END_OF_FILE] end of file"); + if (readBytes == 0 && feof(__pFile)) + { + SysLog(NID_IO, "[E_END_OF_FILE] end of file"); + SetLastResult(E_END_OF_FILE); + return 0; + } + + if (ferror(__pFile)) + { + r = __ConvertNativeErrorToResult(errno); + SysTryReturn(NID_IO, !(r == E_INVALID_OPERATION), 0, E_ILLEGAL_ACCESS, + "[E_ILLEGAL_ACCESS] File was not opened for reading!"); + SysLogException(NID_IO, r, "[%s] Failed to read data from file", GetErrorMessage(r)); + return 0; + } + } + + SetLastResult(E_SUCCESS); + return readBytes; +} + +result +_NormalFile::Read(String& buffer) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + + char line[_MAX_LINE_LENGTH] = {0, }; + result r = E_SUCCESS; + + buffer.Clear(); + if (fgets(line, _MAX_LINE_LENGTH - 1, __pFile) == null) + { + SysTryReturnResult(NID_IO, !feof(__pFile), E_END_OF_FILE, "end of file"); + + if (ferror(__pFile)) + { + r = __ConvertNativeErrorToResult(errno); + SysTryReturnResult(NID_IO, !(r == E_INVALID_OPERATION), E_ILLEGAL_ACCESS, " File was not opened for reading!"); + SysLogException(NID_IO, r, "[%s] Failed to read data from file", GetErrorMessage(r)); + } + } + else + { + buffer = String(line); + } + + return r; +} + +result +_NormalFile::Write(const ByteBuffer& buffer) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + + int length = buffer.GetLimit(); + if (length == 0) + { + return E_INVALID_ARG; + } + + int bytesWritten = fwrite(buffer.GetPointer(), 1, length, __pFile); + if (bytesWritten < length) + { + if (ferror(__pFile)) + { + r = __ConvertNativeErrorToResult(errno); + SysTryReturnResult(NID_IO, !(r == E_INVALID_OPERATION), E_ILLEGAL_ACCESS, "File was not opened for writing!"); + SysLogException(NID_IO, r, "[%s] Failed to write data to file, (errno: %d).", GetErrorMessage(r), errno); + } + } + + return r; +} + +result +_NormalFile::Write(const void* buffer, int length) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, length > 0, E_INVALID_ARG, "length cannot be 0!"); + + result r = E_SUCCESS; + + if ((size_t) length > fwrite(buffer, 1, length, __pFile)) + { + if (ferror(__pFile)) + { + r = __ConvertNativeErrorToResult(errno); + SysTryReturnResult(NID_IO, !(r == E_INVALID_OPERATION), E_ILLEGAL_ACCESS, "File was not opened for writing!"); + SysLogException(NID_IO, r, "[%s] Failed to write data to file, (errno: %d).", GetErrorMessage(r), errno); + } + } + + return r; +} + +result +_NormalFile::Write(const String& buffer) +{ + result r = E_SUCCESS; + + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, buffer.GetLength() > 0, E_INVALID_ARG, "Buffer length cannot be 0!"); + + unique_ptr pData(_StringConverter::CopyToCharArrayN(buffer)); + SysTryReturn(NID_IO, (pData != null), GetLastResult(), GetLastResult(), ("[%s] Invalid file path."), + GetErrorMessage(GetLastResult())); + + if (fputs(pData.get(), __pFile) <= 0) + { + if (ferror(__pFile)) + { + r = __ConvertNativeErrorToResult(errno); + SysTryReturnResult(NID_IO, !(r == E_INVALID_OPERATION), E_ILLEGAL_ACCESS, "File was not opened for writing!"); + SysLogException(NID_IO, r, "[%s] Failed to write data to file, (errno: %d).", GetErrorMessage(r), errno); + } + } + + return r; +} + +result +_NormalFile::Flush(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + + // fflush() returns '0' even if file was opened in read only mode! + if (fflush(__pFile) != 0) + { + r = __ConvertNativeErrorToResult(errno); + SysLogException(NID_IO, r, "[%s] Failed to flush data to file. errno(%d)", GetErrorMessage(r), errno); + } + + return r; +} + +int +_NormalFile::Tell(void) const +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + result r = E_SUCCESS; + + int ret = ftell(__pFile); + if (ret == -1) + { + r = __ConvertNativeErrorToResult(errno); + SysLogException(NID_IO, r, "[%s] Failed to flush data to file", GetErrorMessage(r)); + } + + SetLastResult(r); + return ret; +} + +result +_NormalFile::Seek(FileSeekPosition position, long offset) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + + int whence = FILESEEKPOSITION_CURRENT; + switch (position) + { + case FILESEEKPOSITION_BEGIN: + whence = SEEK_SET; + break; + + case FILESEEKPOSITION_CURRENT: + whence = SEEK_CUR; + break; + + case FILESEEKPOSITION_END: + whence = SEEK_END; + break; + default: + SysTryReturnResult(NID_IO, false, E_INVALID_ARG, "Seek position is invalid."); + } + + int ret = fseek(__pFile, offset, whence); + if (ret != 0) + { + r = __ConvertNativeErrorToResult(errno); + SysLogException(NID_IO, r, "[%s] Failed to seek in file", GetErrorMessage(r)); + } + + return r; +} + +result +_NormalFile::Truncate(int length) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + result r = E_SUCCESS; + + int ret = ftruncate(fileno(__pFile), (off_t) length); + if (ret != 0) + { + r = __ConvertNativeErrorToResult(errno); + SysLogException(NID_IO, r, "[%s] Failed to truncate file. errno(%d)", GetErrorMessage(r), errno); + } + + return r; +} + +String +_NormalFile::GetName(void) +{ + SysAssertf(__pFile != NULL, "Not yet constructed. Construct() should be called before use.\n"); + + SetLastResult(E_SUCCESS); // for OSP 2.0 compatibility + return __filePath; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_NormalRegistry.cpp b/src/io/FIo_NormalRegistry.cpp new file mode 100644 index 0000000..d86808f --- /dev/null +++ b/src/io/FIo_NormalRegistry.cpp @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_NormalRegistry.cpp + * @brief This is the implementation file for _NormalRegistry class. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +_NormalRegistry::_NormalRegistry(void) +{ +} + +_NormalRegistry::~_NormalRegistry(void) +{ + if (_write == true && _FileImpl::IsFileExist(_regPath) == true) + { + this->Flush(); + } + + _sectionList.RemoveAll(true); + + delete[] _pBuffer; //clear existing buffer + _pBuffer = null; + _length = 0; +} + +result +_NormalRegistry::Construct(const String& regPath, const char* pOpenMode) +{ + SysAssertf(_constructed == false, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + bool isValidOpenMode = this->VerifyRegistryOpenMode(pOpenMode); + SysTryReturnResult(NID_IO, isValidOpenMode == true, E_INVALID_ARG, "The specified openMode is invalid. (%s)", pOpenMode); + + result r = this->Load(regPath, pOpenMode); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to load the registry file (%ls).", + GetErrorMessage(r), regPath.GetPointer()); + + if (_pBuffer && _length >= SECURE_REG_HEADER_SIZE_V1) + { + r = _SecureIoUtil::CheckSecureRegistryHeader(&_pBuffer, &_length, regPath, false); + SysTryReturnResult(NID_IO, !IsFailed(r), E_INVALID_ARG, "Can not open the secure file in normal mode."); + } + + r = this->Parse(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to parse the registry file (%ls).", + GetErrorMessage(r), regPath.GetPointer()); + + _constructed = true; + _regPath.Clear(); + _regPath.Append(regPath); + + return r; +} + +result +_NormalRegistry::Flush(void) +{ + result r = this->PrepareToWrite(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to prepare to write.", GetErrorMessage(r)); + + r = this->Write(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write registry file.", GetErrorMessage(r)); + + return r; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_RegistryCore.cpp b/src/io/FIo_RegistryCore.cpp new file mode 100644 index 0000000..28b443a --- /dev/null +++ b/src/io/FIo_RegistryCore.cpp @@ -0,0 +1,1794 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_RegistryCore.cpp + * @brief This is the implementation file for _RegistryCore class. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "FIo_FileImpl.h" +#include "FIo_NormalRegistry.h" +#include "FIo_SecureRegistry.h" +#include "FIo_RegistryCore.h" +#include "FIo_SecureIoUtil.h" + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +static const size_t _MAX_REG_OPENMODE_LENGTH = 2; + +#define _REGISTRY_SECTION_MARKER_CHAR L'#' +#define _REGISTRY_SECTION_VALUE_ASSIGNMENT_MARKER_CHAR L'=' + +class _RegistrySection + : public Object +{ +public: + ~_RegistrySection(void); +private: + String __sectionName; + LinkedList __entryList; + friend class _RegistryCore; +}; + +_RegistrySection::~_RegistrySection(void) +{ + __entryList.RemoveAll(true); +} + +class _RegistryEntry + : public Object +{ +public: + String entryName; + String entryValue; +}; + +_RegistryCore::_RegistryCore(void) + : _constructed(false) + , _read(false) + , _write(false) + , _truncate(false) + , _append(false) + , _pBuffer(null) + , _length(0) +{ +} + +_RegistryCore::~_RegistryCore(void) +{ +} + +bool +_RegistryCore::VerifyRegistryOpenMode(const char* pOpenMode) +{ + if (pOpenMode == null) + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode is null."); + return false; + } + + if (strlen(pOpenMode) > _MAX_REG_OPENMODE_LENGTH) + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + + switch (pOpenMode[0]) + { + case 'r': + _read = true; + break; + case 'w': + _write = true; + _truncate = true; + break; + case 'a': + _write = true; + _append = true; + break; + default: + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + + switch (pOpenMode[1]) + { + case '\0': + break; + case '+': + if (pOpenMode[2] == '\0') + { + _read = true; + _write = true; + break; + } + else + { + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + default: + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode (%s) is invalid.", pOpenMode); + return false; + } + + return true; +} + +result +_RegistryCore::Parse(void) +{ + result r = E_SUCCESS; + wchar_t ch = '\0'; + bool sectionFound = false; + String sectionName; + int length = 0; + unique_ptr pEntryName(null); + unique_ptr pEntryValue(null); + int firstTokenPos = 0; + String line; + + if (_pBuffer == null) + { + SysLog(NID_IO, "The buffer is empty."); + return E_SUCCESS; + } + + String inputStr = String((char*)_pBuffer); + StringTokenizer lineTok(inputStr, L"\n"); + + r = lineTok.GetNextToken(line); + + while (r == E_SUCCESS) + { + // skip empty lines + if (line.GetLength() == 0) + { + r = lineTok.GetNextToken(line); + continue; + } + + // find registry section marker + line.GetCharAt(0, ch); + if (ch == _REGISTRY_SECTION_MARKER_CHAR) + { + sectionFound = true; + + // skip '#' and "\n' at the end + r = line.SubString(1, line.GetLength() - 1, sectionName); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + + // if End of the document follows section name without newline character. + sectionName.GetCharAt(sectionName.GetLength() - 1, ch); + if (ch == L'\n') + { + sectionName.SetLength(sectionName.GetLength() - 1); //Remove '\n' + } + + // for compatibility check if line contains '\r' at the end + sectionName.GetCharAt(sectionName.GetLength() - 1, ch); + if (ch == L'\r') + { + sectionName.SetLength(sectionName.GetLength() - 1); //Remove '\r' + } + + //TODO: check if remaining data in sectionName is valid or not + //after removing '#', '\n', and '\r', sectionName should contain at least 1 valid character + SysTryCatch(NID_IO, + sectionName.GetLength() > 0, r = E_PARSING_FAILED, E_PARSING_FAILED, + "[E_PARSING_FAILED] Section length cannot be <2."); + + unique_ptr pSectionName(_StringConverter::CopyToCharArrayN(sectionName)); + SysTryCatch(NID_IO, pSectionName != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + if (!_RegistryCore::CheckSectionName(pSectionName.get())) + { + SysTryCatch(NID_IO, false, r = E_PARSING_FAILED, E_PARSING_FAILED, + "[E_PARSING_FAILED] Section name could not be parsed."); + } + + r = _RegistryCore::AddSection(_sectionList, sectionName); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + } + else // not a section.. but may belongs to a section (entry) + { + // ignores blank lines + line.GetCharAt(0, ch); + if ((ch == L'\n') || (ch == L'\r')) + { + r = lineTok.GetNextToken(line); + continue; + } + + //TODO + // Need to check for tabs, spaces in the beginning of each line + + // if no section found till now.. ignore + if (sectionFound == false) + { + r = lineTok.GetNextToken(line); + continue; + } + + // if End of the document follows entry value without newline character. + line.GetCharAt(line.GetLength() - 1, ch); + if (ch == L'\n') + { + line.SetLength(line.GetLength() - 1); //Remove '\n' + } + + line.GetCharAt(line.GetLength() - 1, ch); + if (ch == L'\r') + { + line.SetLength(line.GetLength() - 1); //Remove '\r' + } + + String entryName(""); + String entryVal(""); + + // we will have sectionitem=value (or) sectionitem= (or) sectionitem + // as our string. Break this into entry and value + StringTokenizer strTok(line, L"="); + + // extract entry name + if (strTok.HasMoreTokens()) + { + line.IndexOf(L'=', 0, firstTokenPos); // position of first occurance of '=' in a line + if (firstTokenPos == 0) + { + // entryName should not be empty. i.e., "=value" or just '=' is invalid case + SysTryCatch(NID_IO, false, r = E_PARSING_FAILED, E_PARSING_FAILED, + "[E_PARSING_FAILED] Entry name cannot be empty."); + } + else + { + strTok.GetNextToken(entryName); + } + } + else // missing '=' in entry line or entry line does not seem to contain "xxx=xxx" format + { + SysTryCatch(NID_IO, false, r = E_PARSING_FAILED, E_PARSING_FAILED, "[E_PARSING_FAILED] invalid entry Line found."); + } + + // check if entry name contains invalid chars + pEntryName.reset(_StringConverter::CopyToCharArrayN(entryName)); + SysTryCatch(NID_IO, pEntryName, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + if (!_RegistryCore::CheckEntryName(pEntryName.get())) + { + SysTryCatch(NID_IO, false, r = E_PARSING_FAILED, E_PARSING_FAILED, + "[E_PARSING_FAILED] Entry name could not be parsed."); + } + + line.SubString(firstTokenPos + 1, entryVal); // extract entry value + + // check if entry value contains invalid chars + pEntryValue.reset(_StringConverter::CopyToCharArrayN(entryVal)); + SysTryCatch(NID_IO, pEntryValue, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + length = strlen(pEntryValue.get()); + if (length > 0) + { + if (!_RegistryCore::CheckEntryValue(pEntryValue.get())) + { + SysTryCatch(NID_IO, false, r = E_PARSING_FAILED, E_PARSING_FAILED, + "[E_PARSING_FAILED] Entry value could not be parsed."); + } + } + + // add the entry and value + r = _RegistryCore::AddValue(_sectionList, sectionName, entryName, entryVal); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + } + r = lineTok.GetNextToken(line); + } // while() + + if (r == E_OUT_OF_RANGE) + { + r = E_SUCCESS; + } + + // fall through +CATCH: + + if (r == E_PARSING_FAILED && Tizen::App::_AppInfo::IsOspCompat() == false) + { + r = E_INVALID_FORMAT; + } + + SysLog(NID_IO, "[%s] exception occurred.", GetErrorMessage(r)); + return r; +} + +result +_RegistryCore::Load(const String& regPath, const char* pOpenMode) +{ + result r = E_SUCCESS; + delete[] _pBuffer; //clear existing buffer + _pBuffer = null; + _length = 0; + + // open registry file + unique_ptr<_FileImpl> pFileImpl(new (std::nothrow) _FileImpl()); + SysTryReturnResult(NID_IO, pFileImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pFileImpl->Construct(regPath, pOpenMode, null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Constructing the file has failed.", GetErrorMessage(r)); + + // reset the section list to be sure that its empty + _sectionList.RemoveAll(true); + + if (_truncate == false) + { + // load the registry file + r = pFileImpl->ReadN((char**)&_pBuffer, _length); + if (_length > 0) + { + _length--; + } + } + + return r; +} + +result +_RegistryCore::AddSection(const String& sectionName) +{ + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + bool sectionFound = false; + + // Get section information + unique_ptr pEnum(_sectionList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + _RegistrySection* pRegSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == true) + { + return E_SECTION_ALREADY_EXIST; + } + + // create a key with section name + unique_ptr<_RegistrySection> pRegSection(new (std::nothrow) _RegistrySection()); + SysTryReturnResult(NID_IO, pRegSection != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + pRegSection->__sectionName = sectionName; + + // add new section and section-entry map + r = _sectionList.Add(*(pRegSection.release())); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_RegistryCore::RemoveSection(const String& sectionName) +{ + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + _RegistrySection* pRegSection = null; + bool sectionFound = false; + + if (_sectionList.GetCount() == 0) + { + return E_SECTION_NOT_FOUND; + } + + // Get section information + unique_ptr pEnum(_sectionList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegSection = dynamic_cast< _RegistrySection* >(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagating.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == false) + { + return E_SECTION_NOT_FOUND; + } + + r = _sectionList.Remove(*pRegSection, true); + SysTryReturnResult(NID_IO, !IsFailed(r), E_IO, "system error"); + + return E_SUCCESS; +} + +result +_RegistryCore::GetSectionListN(IList** pRetList) +{ + result r = E_SUCCESS; + unique_ptr pEnum(null); + _RegistrySection* pSection = null; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, pRetList != null, E_INVALID_ARG, "pList cannot be null."); + + // construct an array list to be returned + unique_ptr pSectionList(new (std::nothrow) ArrayList()); + SysTryReturnResult(NID_IO, pSectionList != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + r = pSectionList->Construct(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + // if no sectons, return empty list + if (_sectionList.GetCount() == 0) + { + *pRetList = pSectionList.release(); + return E_SUCCESS; + } + + // copy from class section list to the new list and return + pEnum.reset(_sectionList.GetEnumeratorN()); + SysTryReturn(NID_IO, pEnum != null, GetLastResult(), GetLastResult(), "[%s] Section list is empty.", GetErrorMessage(GetLastResult())); + + while (pEnum->MoveNext() == E_SUCCESS) + { + pSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + unique_ptr pSectionName(new (std::nothrow) String(pSection->__sectionName)); + SysTryReturnResult(NID_IO, pSectionName != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pSectionList->Add(*(pSectionName.release())); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + *pRetList = pSectionList.release(); + + return E_SUCCESS; +} + +result +_RegistryCore::GetEntryList(const String& sectionName, Collection::HashMap& retMap) +{ + result r = E_SUCCESS; + unique_ptr pEnum(null); + unique_ptr pKeyEntryStr(null); + unique_ptr pKeyValStr(null); + bool sectionFound = false; + _RegistrySection* pRegSection = null; + _RegistryEntry* pRegEntry = null; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + if (_sectionList.GetCount() == 0) + { + return E_SECTION_NOT_FOUND; + } + + // Get section information + pEnum.reset(_sectionList.GetEnumeratorN()); + SysTryReturnResult(NID_IO, pEnum != null, E_SYSTEM, "Section list is empty."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == false) + { + return E_SECTION_NOT_FOUND; + } + + // copy from item list to the new list and return + pEnum.reset((pRegSection->__entryList).GetEnumeratorN()); + SysTryReturn(NID_IO, pEnum != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegEntry = dynamic_cast <_RegistryEntry*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + pKeyEntryStr.reset(new (std::nothrow) String((pRegEntry->entryName))); + SysTryCatch(NID_IO, pKeyEntryStr != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + pKeyValStr.reset(new (std::nothrow) String((pRegEntry->entryValue))); + SysTryCatch(NID_IO, pKeyValStr != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = retMap.Add(*(pKeyEntryStr.release()), *(pKeyValStr.release())); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + } + + return E_SUCCESS; + +CATCH: + retMap.RemoveAll(true); + + return r; +} + +result +_RegistryCore::GetEntryListN(const String& sectionName, HashMap** pRetList) +{ + result r = E_SUCCESS; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, pRetList != null, E_INVALID_ARG, "pRetList cannot be null."); + + // construct an array list to be returned + unique_ptr pEntryList(new (std::nothrow) HashMap()); + SysTryReturnResult(NID_IO, pEntryList != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + r = pEntryList->Construct(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + r = GetEntryList(sectionName, *(pEntryList.get())); + *pRetList = pEntryList.release(); + + return r; +} + +IMap* +_RegistryCore::GetAllEntriesN(const String& sectionName) +{ + result r = E_SUCCESS; + HashMap* pMap = null; + + r = GetEntryListN(sectionName, &pMap); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return pMap; + +CATCH: + SetLastResult(r); + return null; +} + +IList* +_RegistryCore::GetAllEntryNamesN(const String& sectionName) +{ + result r = E_SUCCESS; + + unique_ptr pEntryList(new (std::nothrow) ArrayList()); + SysTryReturn(NID_IO, pEntryList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pEntryList->Construct(); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + unique_ptr pMap(this->GetAllEntriesN(sectionName)); + SysTryReturn(NID_IO, pMap != null, null, GetLastResult(), "[%s] Getting all entries was failed.", + GetErrorMessage(GetLastResult())); + + unique_ptr pMapEnum(pMap->GetMapEnumeratorN()); + SysTryReturn(NID_IO, pMapEnum, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + while (pMapEnum->MoveNext() == E_SUCCESS) + { + String* pKey = dynamic_cast< String* >(pMapEnum->GetKey()); + SysTryReturn(NID_IO, pKey != null, null, E_IO, "[E_OUT_OF_MEMORY] The system error occurred."); + + String* pEntryName = new (std::nothrow) String(*pKey); + SysTryReturn(NID_IO, pEntryName != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pEntryList->Add(*pEntryName); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + SetLastResult(E_SUCCESS); + return pEntryList.release(); +} + +result +_RegistryCore::GetValue(const String& sectionName, const String& entryName, String& valStr) +{ + bool sectionFound = false; + bool entryFound = false; + _RegistrySection* pRegSection = null; + _RegistryEntry* pRegEntry = null; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + if (_sectionList.GetCount() == 0) + { + return E_SECTION_NOT_FOUND; + } + + // Get section information + unique_ptr pEnum(_sectionList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == false) + { + return E_SECTION_NOT_FOUND; + } + + pEnum.reset(pRegSection->__entryList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegEntry = dynamic_cast <_RegistryEntry*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegEntry->entryName == entryName) + { + valStr = pRegEntry->entryValue; + entryFound = true; + break; + } + } + + SysTryLog(NID_IO, entryFound, "Entry not found"); + + return((entryFound == true) ? E_SUCCESS : E_KEY_NOT_FOUND); +} + +result +_RegistryCore::AddValue(const String& sectionName, const String& entryName, const String& valStr) +{ + result r = E_SUCCESS; + bool sectionFound = false; + bool entryFound = false; + _RegistrySection* pRegSection = null; + int length = 0; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + // Get section information + unique_ptr pEnum(_sectionList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == false) + { + return E_SECTION_NOT_FOUND; + } + + pEnum.reset(pRegSection->__entryList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + _RegistryEntry* pRegEntry = dynamic_cast <_RegistryEntry*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegEntry->entryName == entryName) + { + entryFound = true; + break; + } + } + + if (entryFound == true) + { + return E_KEY_ALREADY_EXIST; + } + + unique_ptr<_RegistryEntry> pRegEntry(new (std::nothrow) _RegistryEntry()); + SysTryReturnResult(NID_IO, pRegEntry != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + unique_ptr pEntryName(_StringConverter::CopyToCharArrayN(entryName)); + SysTryReturnResult(NID_IO, pEntryName != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + length = strlen(pEntryName.get()); + if (!_RegistryCore::CheckEntryName(pEntryName.get())) + { + SysTryReturnResult(NID_IO, false, E_PARSING_FAILED, "Entry name could not be parsed."); + } + + unique_ptr pEntryValue(_StringConverter::CopyToCharArrayN(valStr)); + SysTryReturnResult(NID_IO, pEntryValue != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + length = strlen(pEntryValue.get()); + if (length > 0 && !_RegistryCore::CheckEntryValue(pEntryValue.get())) + { + SysTryReturnResult(NID_IO, false, E_PARSING_FAILED, "Entry value could not be parsed."); + } + + pRegEntry->entryName = entryName; + pRegEntry->entryValue = valStr; + + r = pRegSection->__entryList.Add(*(pRegEntry.release())); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_RegistryCore::SetValue(const String& sectionName, const String& entryName, const String& valStr) +{ + result r = E_SUCCESS; + bool sectionFound = false; + bool entryFound = false; + _RegistryEntry* pRegEntry = null; + _RegistrySection* pRegSection = null; + int length = 0; + int entryIndex = 0; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + if (_sectionList.GetCount() == 0) + { + return E_SECTION_NOT_FOUND; + } + + // Get section information + unique_ptr pEnum(_sectionList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegSection = dynamic_cast< _RegistrySection* >(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == false) + { + return E_SECTION_NOT_FOUND; + } + + pEnum.reset(pRegSection->__entryList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegEntry = dynamic_cast< _RegistryEntry* >(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegEntry->entryName == entryName) + { + entryFound = true; + break; + } + entryIndex++; + } + + if (entryFound == false) + { + return E_KEY_NOT_FOUND; + } + + if (valStr.GetLength() > 0) + { + unique_ptr pEntryValue(_StringConverter::CopyToCharArrayN(valStr)); + SysTryReturnResult(NID_IO, pEntryValue != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + length = strlen(pEntryValue.get()); + if (!_RegistryCore::CheckEntryValue(pEntryValue.get())) + { + return E_PARSING_FAILED; + } + } + + pRegEntry->entryValue = valStr; + r = pRegSection->__entryList.SetAt(*pRegEntry, entryIndex); + SysTryReturnResult(NID_IO, !IsFailed(r), E_IO, "system error"); + + return E_SUCCESS; +} + +result +_RegistryCore::RemoveValue(const String& sectionName, const String& entryName) +{ + result r = E_SUCCESS; + bool sectionFound = false; + bool entryFound = false; + _RegistryEntry* pRegEntry = null; + _RegistrySection* pRegSection = null; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + if (_sectionList.GetCount() <= 0) + { + return E_SECTION_NOT_FOUND; + } + + // Get section information + unique_ptr pEnum(_sectionList.GetEnumeratorN()); + if (pEnum == null) + { + return E_SECTION_NOT_FOUND; + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == false) + { + return E_SECTION_NOT_FOUND; + } + + pEnum.reset(pRegSection->__entryList.GetEnumeratorN()); + if (pEnum == null) + { + return E_SECTION_NOT_FOUND; + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegEntry = dynamic_cast <_RegistryEntry*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegEntry->entryName == entryName) + { + entryFound = true; + break; + } + } + + if (entryFound == false) + { + return E_KEY_NOT_FOUND; + } + + r = pRegSection->__entryList.Remove(*pRegEntry, true); + SysTryReturnResult(NID_IO, !IsFailed(r), E_IO, "system error"); + + return E_SUCCESS; +} + +result +_RegistryCore::Flush(void) +{ + return E_SUCCESS; +} + +result +_RegistryCore::Write(void) +{ + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + if (_pBuffer == null) + { + SysLog(NID_IO, "The buffer is empty."); + return E_SUCCESS; + } + + result r = E_SUCCESS; + + String openMode(L"w+"); + unique_ptr<_FileImpl> pFileImpl(new (std::nothrow) _FileImpl); + SysTryReturnResult(NID_IO, pFileImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + //TODO: Secure mode is to be handled + r = pFileImpl->Construct(_regPath, "w+", null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = pFileImpl->Write(_pBuffer, _length); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = pFileImpl->Flush(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + return r; +} + +result +_RegistryCore::PrepareToWrite(void) +{ + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + result r = E_SUCCESS; + _RegistryEntry* pRegEntry = null; + _RegistrySection* pRegSection = null; + String inputBuffer; + + delete[] _pBuffer; //clear existing buffer + _pBuffer = null; + _length = 0; + + if (_write == false) + { + SysLog(NID_IO, "[E_ILLEGAL_ACCESS] Registry cannot be flushed as it was opened in read only mode."); + return E_ILLEGAL_ACCESS; + } + + // if no sections, do nothing + if (_sectionList.GetCount() == 0) + { + unique_ptr pFilePath(_StringConverter::CopyToCharArrayN(_regPath)); + truncate(pFilePath.get(), 0); + + return E_SUCCESS; + } + + // write the registry map to a file + // Get section information + unique_ptr pSectionEnum(_sectionList.GetEnumeratorN()); + SysTryReturn(NID_IO, pSectionEnum != null, GetLastResult(), GetLastResult(), "[%s] Section list is empty.", + GetErrorMessage(GetLastResult())); + + while (pSectionEnum->MoveNext() == E_SUCCESS) + { + // get section name + pRegSection = dynamic_cast <_RegistrySection*>(pSectionEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + // write section name to file + r = inputBuffer.Append(String(L"#" + pRegSection->__sectionName + String(L'\n'))); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + // read the entries for this section + unique_ptr pEntryEnum(pRegSection->__entryList.GetEnumeratorN()); + SysTryReturn(NID_IO, pSectionEnum != null, GetLastResult(), GetLastResult(), "[%s] Entry list is empty.", + GetErrorMessage(GetLastResult())); + + while (pEntryEnum->MoveNext() == E_SUCCESS) + { + pRegEntry = dynamic_cast <_RegistryEntry*>(pEntryEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + // write entry name to file + r = inputBuffer.Append(pRegEntry->entryName + String(L"=" + pRegEntry->entryValue + String(L'\n'))); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + } + + _pBuffer = (byte*)_StringConverter::CopyToCharArrayN(inputBuffer); + SysTryReturn(NID_IO, _pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + _length = strlen((char*)_pBuffer); + + return r; +} + +int +_RegistryCore::GetSectionIndex(const String& sectionName) +{ + bool sectionFound = false; + _RegistrySection* pRegSection = null; + int index = 0; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, sectionName.GetLength() > 0, -1, E_INVALID_ARG, + "[E_INVALID_ARG] sectionName.GetLength() <= 0"); + + SysTryReturn(NID_IO, _sectionList.GetCount() > 0, -1, E_SECTION_NOT_FOUND, "[E_SECTION_NOT_FOUND] Section not found."); + + // Get section information + unique_ptr pEnum(_sectionList.GetEnumeratorN()); + SysTryReturn(NID_IO, pEnum != null, GetLastResult(), GetLastResult(), "[%s] Section list is empty.", + GetErrorMessage(GetLastResult())); + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, -1, GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + index++; + } + + if (sectionFound == false) + { + return E_SECTION_NOT_FOUND; + } + + SetLastResult(E_SUCCESS); + return index; +} + +void +_RegistryCore::Removekey(const String& sectionName, const String& keyName) +{ + result r = E_SUCCESS; + int sectionIndex = -1; + int entryIndex = -1; + + sectionIndex = GetSectionIndex(sectionName); + r = GetLastResult(); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), r, "[%s] Propagated.", GetErrorMessage(r)); + + entryIndex = GetEntryIndex(sectionIndex, keyName); + r = GetLastResult(); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), r, "[%s] Propagated.", GetErrorMessage(r)); + + RemoveEntry(sectionIndex, entryIndex); + r = GetLastResult(); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), r, "[%s] Propagated.", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return; +} + +int +_RegistryCore::GetAllSectionCount(void) +{ + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + + SetLastResult(E_SUCCESS); + return _sectionList.GetCount(); +} + +int +_RegistryCore::GetAllEntryCount(int sectionIndex) +{ + _RegistrySection* pRegSection = null; + int listSize = 0; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, sectionIndex >= 0, 0, E_INVALID_ARG, "[E_INVALID_ARG] sectionIndex < 0."); + listSize = _sectionList.GetCount(); + SysTryReturn(NID_IO, listSize > 0, 0, E_SECTION_NOT_FOUND, "[E_INVALID_ARG] section listSize <= 0."); + SysTryReturn(NID_IO, sectionIndex >= listSize, 0, E_SECTION_NOT_FOUND, + "[E_INVALID_ARG] sectionIndex > listSize."); + + pRegSection = (_RegistrySection*) GetSectionByIndex(sectionIndex); + SysTryReturn(NID_IO, pRegSection != null, 0, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] section was not found."); + + SetLastResult(E_SUCCESS); + return pRegSection->__entryList.GetCount(); +} + +void +_RegistryCore::RemoveEntry(int sectionIndex, int entryIndex) +{ + result r = E_SUCCESS; + int listSize = 0; + int entryListSize = 0; + _RegistrySection* pRegSection = null; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnVoidResult(NID_IO, sectionIndex >= 0, E_INVALID_ARG, "[E_INVALID_ARG] sectionIndex < 0."); + SysTryReturnVoidResult(NID_IO, entryIndex >= 0, E_INVALID_ARG, "[E_INVALID_ARG] entryIndex < 0."); + + listSize = _sectionList.GetCount(); + SysTryReturnVoidResult(NID_IO, listSize > 0, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] section listSize <= 0."); + SysTryReturnVoidResult(NID_IO, sectionIndex < listSize, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] sectionIndex >= listSize."); + + pRegSection = (_RegistrySection*) GetSectionByIndex(sectionIndex); + SysTryReturnVoidResult(NID_IO, pRegSection != null, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] Section at index (%d) not found.", sectionIndex); + + r = GetLastResult(); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), r,"[%s] Propagated.", GetErrorMessage(r)); + + entryListSize = pRegSection->__entryList.GetCount(); + SysTryReturnVoidResult(NID_IO, (entryListSize > 0 || entryIndex < entryListSize), E_KEY_NOT_FOUND, + "[E_KEY_NOT_FOUND] entryListSize is 0 or entryIndex >= entryListSize."); + + r = pRegSection->__entryList.RemoveAt(entryIndex, true); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), r, "[%s] Propagated.", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); +} + +void +_RegistryCore::ModifyEntryValue(int sectionIndex, int entryIndex, _RegValueType type, const void* pValue, int size) +{ + SetLastResult(E_UNSUPPORTED_OPERATION); +} + +int +_RegistryCore::GetEntryIndex(int sectionIndex, const String& entryName) +{ + _RegistrySection* pRegSection = null; + _RegistryEntry* pRegEntry = null; + int listSize = 0; + bool entryFound = false; + int entryIndex = -1; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, sectionIndex >= 0, -1, E_INVALID_ARG, "[E_INVALID_ARG]sectionIndex < 0."); + SysTryReturn(NID_IO, entryName.GetLength() > 0, -1, E_INVALID_ARG, "[E_INVALID_ARG]entryName length < 0."); + + listSize = _sectionList.GetCount(); + SysTryReturn(NID_IO, listSize > 0, -1, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND]Registry section list is empty."); + SysTryReturn(NID_IO, sectionIndex < listSize, -1, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND]sectionIndex >= listSize."); + + pRegSection = (_RegistrySection*) GetSectionByIndex(sectionIndex); + SysTryReturn(NID_IO, pRegSection != null, -1, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] Section at index (%d) not found.", sectionIndex); + + // read the entries for this section + unique_ptr pEntryEnum(pRegSection->__entryList.GetEnumeratorN()); + SysTryReturn(NID_IO, pEntryEnum != null, -1, GetLastResult(), "[%s] Entry list is empty.", + GetErrorMessage(GetLastResult())); + + entryIndex = 0; + while (pEntryEnum->MoveNext() == E_SUCCESS) + { + pRegEntry = dynamic_cast <_RegistryEntry*>(pEntryEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, -1, GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (entryName == pRegEntry->entryName) + { + entryFound = true; + break; + } + entryIndex++; + } + + SysTryReturn(NID_IO, entryFound != false, -1, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] entry was not found."); + + SetLastResult(E_SUCCESS); + return entryIndex; +} + +String +_RegistryCore::GetEntryName(int sectionIndex, int entryIndex) +{ + _RegistrySection* pRegSection = null; + _RegistryEntry* pRegEntry = null; + int listSize = 0; + int tmpIndex = -1; + String empty; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, sectionIndex >= 0, empty, E_INVALID_ARG, "[E_INVALID_ARG]sectionIndex < 0."); + SysTryReturn(NID_IO, entryIndex >= 0, empty, E_INVALID_ARG, "[E_INVALID_ARG]entryIndex < 0."); + + listSize = _sectionList.GetCount(); + SysTryReturn(NID_IO, listSize > 0, empty, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND]Registry section list is empty."); + SysTryReturn(NID_IO, sectionIndex < listSize, empty, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND]sectionIndex >= listSize."); + + pRegSection = (_RegistrySection*) GetSectionByIndex(sectionIndex); + SysTryReturn(NID_IO, pRegSection != null, empty, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] Section at index (%d) not found.", sectionIndex); + + // read the entries for this section + unique_ptr pEntryEnum(pRegSection->__entryList.GetEnumeratorN()); + SysTryReturn(NID_IO, pEntryEnum != null, empty, GetLastResult(), "[%s] Entry list is empty.", + GetErrorMessage(GetLastResult())); + + tmpIndex = entryIndex; + while (pEntryEnum->MoveNext() == E_SUCCESS) + { + if (tmpIndex == 0) + { + pRegEntry = dynamic_cast <_RegistryEntry*>(pEntryEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, empty, GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + break; + } + tmpIndex--; + } + + SysTryReturn(NID_IO, pRegEntry != null, empty, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] entry was not found."); + + SetLastResult(E_SUCCESS); + return pRegEntry->entryName; +} + +void +_RegistryCore::GetEntryValue(int sectionIndex, int entryIndex, _RegValueType type, void* pValue, int* pSize) +{ + _RegistrySection* pRegSection = null; + _RegistryEntry* pRegEntry = null; + IEnumerator* pEntryEnum = null; + result r = E_SUCCESS; + int listSize = 0; + int tmpEntryIndex = -1; + int entryListSize = 0; + String strValueEncoded; + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnVoidResult(NID_IO, sectionIndex >= 0, E_INVALID_ARG, "[E_INVALID_ARG]sectionIndex < 0."); + SysTryReturnVoidResult(NID_IO, type >= 0 && type <= REG_VALUE_TYPE_MAX, E_INVALID_ARG, + "[E_INVALID_ARG] invalid registry type."); + SysTryReturnVoidResult(NID_IO, pValue != null, E_INVALID_ARG, "[E_INVALID_ARG]pValue is null."); + SysTryReturnVoidResult(NID_IO, pSize != null, E_INVALID_ARG, "[E_INVALID_ARG]pSize is null."); + SysTryReturnVoidResult(NID_IO, *pSize > 0, E_INVALID_ARG, "[E_INVALID_ARG] *pSize < 0."); + + listSize = _sectionList.GetCount(); + SysTryReturnVoidResult(NID_IO, listSize > 0, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND]Registry section list is empty."); + SysTryReturnVoidResult(NID_IO, sectionIndex < listSize, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND]sectionIndex >= listSize."); + + pRegSection = (_RegistrySection*) GetSectionByIndex(sectionIndex); + SysTryReturnVoidResult(NID_IO, pRegSection != null, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] section at index (%d) is not available.", sectionIndex); + + entryListSize = pRegSection->__entryList.GetCount(); + SysTryReturnVoidResult(NID_IO, entryListSize > 0, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND]Entry list is empty."); + SysTryReturnVoidResult(NID_IO, entryIndex < entryListSize, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND]Entry not found."); + + // read the entries for this section + pEntryEnum = pRegSection->__entryList.GetEnumeratorN(); + SysTryReturnVoidResult(NID_IO, pEntryEnum != null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND]Entry list is empty."); + + tmpEntryIndex = entryIndex; + while (pEntryEnum->MoveNext() == E_SUCCESS) + { + if (entryIndex == 0) + { + pRegEntry = dynamic_cast <_RegistryEntry*>(pEntryEnum->GetCurrent()); + SysTryReturnVoidResult(NID_IO, pRegEntry != null, GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + break; + } + entryIndex--; + + } + + SysTryReturnVoidResult(NID_IO, pRegEntry != null, E_KEY_NOT_FOUND, + "[E_KEY_NOT_FOUND] Entry was not found."); + + strValueEncoded = pRegEntry->entryValue; + + DecodeData(strValueEncoded, type, pValue, pSize); + r = GetLastResult(); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), E_PARSING_FAILED, "[%s] Propagated.", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return; +} + +String +_RegistryCore::GetSectionName(int sectionIndex) +{ + _RegistrySection* pRegSection = null; + result r = E_SUCCESS; + int listSize = 0; + String sectionName(""); + + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, sectionIndex >= 0, sectionName, E_INVALID_ARG, "[E_INVALID_ARG]sectionIndex < 0."); + + listSize = _sectionList.GetCount(); + SysTryReturn(NID_IO, listSize > 0, sectionName, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND]Registry section list is empty."); + SysTryReturn(NID_IO, sectionIndex < listSize, sectionName, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND]sectionIndex >= listSize."); + + pRegSection = (_RegistrySection*) GetSectionByIndex(sectionIndex); + SysTryReturn(NID_IO, pRegSection != null, sectionName, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] sectionIndex is not available."); + + r = GetLastResult(); + SysTryReturn(NID_IO, !IsFailed(r), sectionName, r, "[%s] Propagated.", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return pRegSection->__sectionName; +} + +void* +_RegistryCore::GetSectionByIndex(int sectionIndex) +{ + _RegistrySection* pRegSection = null; + int index = sectionIndex; + + // Get section information + unique_ptr pEnum(_sectionList.GetEnumeratorN()); + SysTryReturn(NID_IO, pEnum != null, null, GetLastResult(), + "[%s] section list is empty.", GetErrorMessage(GetLastResult())); + + while (pEnum->MoveNext() == E_SUCCESS) + { + if (index == 0) + { + pRegSection = dynamic_cast< _RegistrySection* >(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, null, GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + break; + } + index--; + + } + + SysTryReturn(NID_IO, pRegSection != null, null, E_SECTION_NOT_FOUND, + "[E_SECTION_NOT_FOUND] Section was not found."); + + SetLastResult(E_SUCCESS); + + return pRegSection; +} + +void +_RegistryCore::DecodeData(const String& strValueEncoded, _RegValueType type, void* pValue, int* pSize) +{ + SysAssert(strValueEncoded.GetLength() > 0); + SysAssert(pValue); + SysAssert(pSize); + SysAssert(pSize && *pSize > 0); + + SysTryReturnVoidResult(NID_IO, pValue != null, E_INVALID_ARG, "[E_INVALID_ARG] Invalid argument."); + SysTryReturnVoidResult(NID_IO, pSize != null, E_INVALID_ARG, "[E_INVALID_ARG] Invalid argument."); + + switch (type) + { + case REG_VALUE_TYPE_INT: // (-2147483647 - 1) ~ 2147483647 + { + int retIntVal = 0; + result r = E_SUCCESS; + + if (*pSize != sizeof(int)) + { + SetLastResult(E_INVALID_ARG); + return; + } + + r = Integer::Parse(strValueEncoded, retIntVal); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), E_PARSING_FAILED, "[%s] Propagated.", GetErrorMessage(r)); + + *(int*) pValue = retIntVal; + break; + } + + case REG_VALUE_TYPE_REAL: // Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers + // ranging in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 + // for negative values and from 4.94065645841246544E-324 through 1.79769313486231570E+308 + // for positive values. + { + double retDoubleVal = 0; + result r = E_SUCCESS; + + if (*pSize != sizeof(double)) + { + SetLastResult(E_INVALID_ARG); + return; + } + + r = Double::Parse(strValueEncoded, retDoubleVal); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), E_PARSING_FAILED, "[%s] Propagated.", GetErrorMessage(r)); + + *(double*) pValue = retDoubleVal; + break; + } + + case REG_VALUE_TYPE_STRING: + { +// if(*pSize != sizeof(String)) +// { +// SetLastResult(E_INVALID_ARG); +// return; +// } + *(String*) pValue = strValueEncoded; + break; + } + + case REG_VALUE_TYPE_BINARY: + { + SetLastResult(E_PARSING_FAILED); + return; + } + + case REG_VALUE_TYPE_UUID: + { + UuId retUuIdVal; + result r = E_SUCCESS; + + r = UuId::Parse(strValueEncoded, retUuIdVal); + SysTryReturnVoidResult(NID_IO, !IsFailed(r), E_PARSING_FAILED, "[%s] Propagated.", GetErrorMessage(r)); + + *(UuId*) pValue = retUuIdVal; + break; + } + + case REG_VALUE_TYPE_UUIDSET: + { + SetLastResult(E_PARSING_FAILED); + return; + } + + default: + SysAssert(0); // should not happen! + return; + } + + SetLastResult(E_SUCCESS); + return; +} + +result +_RegistryCore::AddSection(LinkedList& sectionList, const String& sectionName) +{ + result r = E_SUCCESS; + bool sectionFound = false; + + // Get section information + unique_ptr pEnum(sectionList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + _RegistrySection* pRegSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == true) + { + return E_SECTION_ALREADY_EXIST; + } + + // create a key with section name + unique_ptr<_RegistrySection> pRegSection(new (std::nothrow) _RegistrySection()); + + SysTryReturnResult(NID_IO, pRegSection != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + pRegSection->__sectionName = sectionName; + + // add new section and section-entry map + r = sectionList.Add(*(pRegSection.release())); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_RegistryCore::AddValue(LinkedList& sectionList, const String& sectionName, const String& entryName, const String& valStr) +{ + result r = E_SUCCESS; + bool sectionFound = false; + bool entryFound = false; + _RegistrySection* pRegSection = null; + + // Get section information + unique_ptr pEnum(sectionList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + pRegSection = dynamic_cast <_RegistrySection*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegSection != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegSection->__sectionName == sectionName) + { + sectionFound = true; + break; + } + } + + if (sectionFound == false) + { + return E_SECTION_NOT_FOUND; + } + + pEnum.reset(pRegSection->__entryList.GetEnumeratorN()); + if (pEnum == null) + { + return GetLastResult(); + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + _RegistryEntry* pRegEntry = dynamic_cast <_RegistryEntry*>(pEnum->GetCurrent()); + SysTryReturn(NID_IO, pRegEntry != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", + GetErrorMessage(GetLastResult())); + + if (pRegEntry->entryName == entryName) + { + entryFound = true; + break; + } + } + + if (entryFound == true) + { + return E_KEY_ALREADY_EXIST; + } + + unique_ptr<_RegistryEntry> pRegEntry(new (std::nothrow) _RegistryEntry()); + SysTryReturnResult(NID_IO, pRegEntry != null, E_OUT_OF_MEMORY, + "The memory is insufficient."); + + pRegEntry->entryName = entryName; + pRegEntry->entryValue = valStr; + + r = pRegSection->__entryList.Add(*(pRegEntry.release())); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +bool +_RegistryCore::CheckSectionName(char* pSectionName) +{ + char* pTemp = null; + int length = 0; + char* pFrom = null; + char* pTo = null; + + if (pSectionName == null) + { + return false; + } + + pFrom = pSectionName; + length = strlen(pSectionName); + pTo = pSectionName + (length - 1); + + if (!pFrom || !pTo || pFrom > pTo) + { + return false; + } + + for (pTemp = pFrom; pTemp <= pTo; pTemp++) + { + if (*pTemp == '\0' || *pTemp == '\n' || *pTemp == '#' || *pTemp == '=') + { + return false; + } + } + + return true; +} + +bool +_RegistryCore::CheckEntryName(char* pEntryName) +{ + char* pTemp = null; + int length = 0; + char* pFrom = null; + char* pTo = null; + + if (pEntryName == null) + { + return false; + } + + pFrom = pEntryName; + length = strlen(pEntryName); + pTo = pEntryName + (length - 1); + + if (!pFrom || !pTo || pFrom > pTo) + { + return false; + } + + for (pTemp = pFrom; pTemp <= pTo; pTemp++) + { + if (*pTemp == '\0' || *pTemp == '\n' || *pTemp == '#' || *pTemp == '=') + { + return false; + } + } + + return true; +} + +bool +_RegistryCore::CheckEntryValue(char* pEntryVal) +{ + char* pTemp = null; + int length = 0; + char* pFrom = null; + char* pTo = null; + + if (pEntryVal == null) + { + return false; + } + + pFrom = pEntryVal; + length = strlen(pEntryVal); + pTo = pEntryVal + (length - 1); + + if (!pFrom || !pTo || pFrom > pTo) + { + return false; + } + + for (pTemp = pFrom; pTemp <= pTo; pTemp++) + { + if (*pTemp == '\0' || *pTemp == '\n') + { + return false; + } + } + + return true; +} + +result +_RegistryCore::ConvertToSecureRegistry(const String& plainRegPath, const String& secureRegPath, const ByteBuffer* pKey) +{ + result r = E_SUCCESS; + + if (File::IsFileExist(secureRegPath)) + { + r = GetLastResult(); + if (r == E_SUCCESS) + { + r = E_FILE_ALREADY_EXIST; + SysLog(NID_IO, "[E_FILE_ALREADY_EXIST] The secure registry already exists."); + } + else + { + SysLog(NID_IO, "[%s]Propagated.", GetErrorMessage(r)); + } + return r; + } + + unique_ptr<_NormalRegistry> pNormalReg(new (std::nothrow) _NormalRegistry()); + SysTryReturnResult(NID_IO, pNormalReg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pNormalReg->Load(plainRegPath, "r"); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + unique_ptr<_SecureRegistry> pSecureReg(new (std::nothrow) _SecureRegistry()); + SysTryReturnResult(NID_IO, pSecureReg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pSecureReg->Construct(secureRegPath, "w+", pKey); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + if (pNormalReg->_pBuffer != null && pNormalReg->_length > 0) + { + pSecureReg->_pBuffer = pNormalReg->_pBuffer; + pSecureReg->_length = pNormalReg->_length; + + pNormalReg->_pBuffer = null; + pNormalReg->_length = 0; + + r = pSecureReg->Parse(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + return E_SUCCESS; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_RegistryImpl.cpp b/src/io/FIo_RegistryImpl.cpp new file mode 100644 index 0000000..be71c3f --- /dev/null +++ b/src/io/FIo_RegistryImpl.cpp @@ -0,0 +1,328 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_RegistryImpl.cpp + * @brief This is the implementation file for _RegistryImpl class. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +static const int _MAX_REG_OPENMODE_LENGTH = 2; + +_RegistryImpl::_RegistryImpl(void) + : __pRegistryCore(null) +{ +} + +_RegistryImpl::~_RegistryImpl(void) +{ + delete __pRegistryCore; +} + +bool +_RegistryImpl::ConvertRegistryOpenMode(long legacyMode, char* pOpenMode) +{ + switch (legacyMode) + { + case REG_OPEN_READ_ONLY: + strcpy(pOpenMode, "r\0"); + break; + case REG_OPEN_READ_WRITE: + strcpy(pOpenMode, "r+\0"); + break; + case (REG_OPEN_READ_WRITE | REG_OPEN_CREATE): + strcpy(pOpenMode, "a+\0"); + break; + default: + SysLog(NID_IO, "[E_INVALID_ARG] The specified openMode is invalid."); + return false; + } + return true; +} + +// This method will be removed in a future release. +result +_RegistryImpl::Construct(const String& regPath, long legacyMode, const ByteBuffer* pSecretKey) +{ + SysAssertf(__pRegistryCore == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + unique_ptr pOpenMode(new char[_MAX_REG_OPENMODE_LENGTH + 1]); + SysTryReturnResult(NID_IO, pOpenMode != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + bool isValid = _RegistryImpl::ConvertRegistryOpenMode(legacyMode, pOpenMode.get()); + SysTryReturnResult(NID_IO, isValid == true, E_INVALID_ARG, "The specified openMode is invalid."); + + return Construct(regPath, pOpenMode.get(), pSecretKey); +} + +result +_RegistryImpl::Construct(const String& regPath, const char* pOpenMode, const ByteBuffer* pSecretKey) +{ + SysAssertf(__pRegistryCore == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + result r = E_SUCCESS; + if (!pSecretKey) + { + unique_ptr<_NormalRegistry> pNormalRegistry(new (std::nothrow) _NormalRegistry()); + SysTryReturnResult(NID_IO, pNormalRegistry != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pNormalRegistry->Construct(regPath, pOpenMode); + if (IsFailed(r)) + { + SysLogException(NID_IO, r, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + __pRegistryCore = pNormalRegistry.release(); + } + else + { + unique_ptr<_SecureRegistry> pSecureRegistry(new (std::nothrow) _SecureRegistry()); + SysTryReturnResult(NID_IO, pSecureRegistry != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pSecureRegistry->Construct(regPath, pOpenMode, pSecretKey); + if (IsFailed(r)) + { + SysLogException(NID_IO, r, "[%s] Propagated.", GetErrorMessage(r)); + return r; + } + __pRegistryCore = pSecureRegistry.release(); + } + + return r; +} + +result +_RegistryImpl::Remove(const String& regPath) +{ + return _FileImpl::Remove(regPath); +} + +result +_RegistryImpl::AddSection(const String& sectionName) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->AddSection(sectionName); +} + +result +_RegistryImpl::RemoveSection(const String& sectionName) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->RemoveSection(sectionName); +} + +result +_RegistryImpl::GetSectionListN(IList** pRetList) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetSectionListN(pRetList); +} + + +result +_RegistryImpl::GetEntryList(const String& sectionName, Collection::HashMap& retMap) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetEntryList(sectionName, retMap); +} + + +result +_RegistryImpl::GetEntryListN(const String& sectionName, HashMap** pRetList) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetEntryListN(sectionName, pRetList); +} + +IMap* +_RegistryImpl::GetAllEntriesN(const String& sectionName) const +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetAllEntriesN(sectionName); +} + +IList* +_RegistryImpl::GetAllEntryNamesN(const String& sectionName) const +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetAllEntryNamesN(sectionName); +} + +result +_RegistryImpl::GetValue(const String& sectionName, const String& entryName, String& valStr) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetValue(sectionName, entryName, valStr); +} + +result +_RegistryImpl::AddValue(const String& sectionName, const String& entryName, const String& valStr) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->AddValue(sectionName, entryName, valStr); +} + +result +_RegistryImpl::SetValue(const String& sectionName, const String& entryName, const String& valStr) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->SetValue(sectionName, entryName, valStr); +} + +result +_RegistryImpl::RemoveValue(const String& sectionName, const String& entryName) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->RemoveValue(sectionName, entryName); +} + +result +_RegistryImpl::Flush(void) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->Flush(); +} + +result +_RegistryImpl::ConvertToSecureRegistry(const String& plainRegPath, const String& secureRegPath, const ByteBuffer* pKey) +{ + return _SecureRegistry::ConvertToSecureRegistry(plainRegPath, secureRegPath, pKey); +} + +int +_RegistryImpl::GetSectionIndex(const String& sectionName) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetSectionIndex(sectionName); +} + +void +_RegistryImpl::Removekey(const String& sectionName, const String& keyName) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + __pRegistryCore->Removekey(sectionName, keyName); +} + +int +_RegistryImpl::GetAllSectionCount(void) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetAllSectionCount(); +} + + +int +_RegistryImpl::GetAllEntryCount(int sectionIndex) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetAllEntryCount(sectionIndex); +} + +void +_RegistryImpl::RemoveEntry(int sectionIndex, int entryIndex) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + __pRegistryCore->RemoveEntry(sectionIndex, entryIndex); +} + +void +_RegistryImpl::ModifyEntryValue(int sectionIndex, int entryIndex, _RegValueType type, const void* pValue, int size) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + __pRegistryCore->ModifyEntryValue(sectionIndex, entryIndex, type, pValue, size); +} + +int +_RegistryImpl::GetEntryIndex(int sectionIndex, const String& entryName) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetEntryIndex(sectionIndex, entryName); +} + +String +_RegistryImpl::GetEntryName(int sectionIndex, int entryIndex) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetEntryName(sectionIndex, entryIndex); +} + +void +_RegistryImpl::GetEntryValue(int sectionIndex, int entryIndex, _RegValueType type, void* pValue, int* pSize) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + __pRegistryCore->GetEntryValue(sectionIndex, entryIndex, type, pValue, pSize); +} + +String +_RegistryImpl::GetSectionName(int sectionIndex) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetSectionName(sectionIndex); +} + +void* +_RegistryImpl::GetSectionByIndex(int sectionIndex) +{ + SysAssertf(__pRegistryCore != null, "Not yet constructed. Construct() should be called before use.\n"); + return __pRegistryCore->GetSectionByIndex(sectionIndex); +} + +_RegistryImpl* +_RegistryImpl::GetInstance(Registry& registry) +{ + return registry.__pRegistryImpl; +} + +const _RegistryImpl* +_RegistryImpl::GetInstance(const Registry& registry) +{ + return registry.__pRegistryImpl; +} + +}} // Tizen::Io + diff --git a/src/io/FIo_RemoteMessagePortImpl.cpp b/src/io/FIo_RemoteMessagePortImpl.cpp new file mode 100644 index 0000000..92d19ca --- /dev/null +++ b/src/io/FIo_RemoteMessagePortImpl.cpp @@ -0,0 +1,184 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_RemoteMessagePortImpl.cpp + * @brief This is the implementation file for the _RemoteMessagePortImpl class. + * + */ + +#include +#include + +#include +#include +#include +#include +#include + +#include "FIo_RemoteMessagePortImpl.h" +#include "FIo_MessagePortProxy.h" + +using namespace std; + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +_RemoteMessagePortImpl::_RemoteMessagePortImpl(void) + : __isTrusted(false) +{ + +} + +_RemoteMessagePortImpl::~_RemoteMessagePortImpl(void) +{ + +} + +result +_RemoteMessagePortImpl::Construct(const AppId& remoteAppId, const String& remotePort, bool isTrusted) +{ + result r = _MessagePortProxy::GetProxy()->RequestRemotePort(remoteAppId, remotePort, isTrusted); + SysTryReturnResult(NID_IO, r == E_SUCCESS, r, "Propagating."); + + __remoteAppId = remoteAppId; + __remotePort = remotePort; + __isTrusted = isTrusted; + + return E_SUCCESS; +} + +AppId +_RemoteMessagePortImpl::GetAppId(void) const +{ + return __remoteAppId; +} + +String +_RemoteMessagePortImpl::GetName(void) const +{ + return __remotePort; +} + +bool +_RemoteMessagePortImpl::IsTrusted(void) const +{ + return __isTrusted; +} + +result +_RemoteMessagePortImpl::SendMessage(const IMap* pMessage) +{ + SysTryReturnResult(NID_IO, pMessage != null, E_INVALID_ARG, "The argument is null."); + SysTryReturnResult(NID_IO, CheckMessageType(pMessage), E_INVALID_ARG, "The argument is invalid."); + + return _MessagePortProxy::GetProxy()->SendMessage(__remoteAppId, __remotePort, __isTrusted, (HashMap*)pMessage); +} + +result +_RemoteMessagePortImpl::SendMessage(const LocalMessagePort* pLocalMessagePort, const IMap* pMessage) +{ + SysTryReturnResult(NID_IO, pLocalMessagePort != null, E_INVALID_ARG, "The argument is null."); + SysTryReturnResult(NID_IO, pMessage != null, E_INVALID_ARG, "The argument is null."); + SysTryReturnResult(NID_IO, CheckMessageType(pMessage), E_INVALID_ARG, "The argument is invalid."); + + return _MessagePortProxy::GetProxy()->SendMessage(pLocalMessagePort->GetName(), pLocalMessagePort->IsTrusted(), __remoteAppId, __remotePort, __isTrusted, (HashMap*)pMessage); +} + +bool +_RemoteMessagePortImpl::CheckMessageType(const IMap* pMessage) +{ + std::unique_ptr pEnum (pMessage->GetMapEnumeratorN()); + while(pEnum->MoveNext() == E_SUCCESS) + { + const String* pKey = dynamic_cast(pEnum->GetKey()); + const Object* pValue = pEnum->GetValue(); + + if (pKey && pValue) + { + if (typeid(*pValue) != typeid(const String)) + { + if (typeid(*pValue) != typeid(const ByteBuffer)) + { + return false; + } + } + } + else + { + return false; + } + } + + return true; +} + +RemoteMessagePort* +_RemoteMessagePortImpl::GetMessagePort(const AppId& remoteAppId, const String& remotePort, bool isTrusted) +{ + result r = E_SUCCESS; + + RemoteMessagePort* pRemoteMessagePort = new (std::nothrow) RemoteMessagePort; + SysTryReturn(NID_IO, pRemoteMessagePort != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + unique_ptr<_RemoteMessagePortImpl> pImpl(new (std::nothrow) _RemoteMessagePortImpl); + SysTryCatch(NID_IO, pImpl != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pImpl->Construct(remoteAppId, remotePort, isTrusted); + SysTryCatch(NID_IO, r != E_OBJ_NOT_FOUND, , E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] The remote message port is not found."); + SysTryCatch(NID_IO, r == E_SUCCESS, , r, "[%s] Propagating.", GetErrorMessage(r)); + + pRemoteMessagePort->__pRemoteMessagePortImpl = pImpl.release(); + + SetLastResult(r); + return pRemoteMessagePort; + +CATCH: + delete pRemoteMessagePort; + + return null; +} + +RemoteMessagePort* +_RemoteMessagePortImpl::GetMessagePortOnly(const AppId& remoteAppId, const String& remotePort, bool isTrusted) +{ + RemoteMessagePort* pRemoteMessagePort = new (std::nothrow) RemoteMessagePort; + SysTryReturn(NID_IO, pRemoteMessagePort != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + unique_ptr<_RemoteMessagePortImpl> pImpl(new (std::nothrow) _RemoteMessagePortImpl); + SysTryCatch(NID_IO, pImpl != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pImpl->__remoteAppId = remoteAppId; + pImpl->__remotePort = remotePort; + pImpl->__isTrusted = isTrusted; + + pRemoteMessagePort->__pRemoteMessagePortImpl = pImpl.release(); + + SetLastResult(E_SUCCESS); + return pRemoteMessagePort; + +CATCH: + delete pRemoteMessagePort; + + return null; +} + +} } // Tizen::Io diff --git a/src/io/FIo_SecureFile.cpp b/src/io/FIo_SecureFile.cpp new file mode 100644 index 0000000..8b3020b --- /dev/null +++ b/src/io/FIo_SecureFile.cpp @@ -0,0 +1,703 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_SecureFile.cpp + * @brief This is the implementation file for _SecureFile class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; + +namespace Tizen { namespace Io +{ + +_SecureFile::_SecureFile(void) + : __pNormalFile(null) + , __virtualFilePointer(0) + , __pKey(null) +{ +} + +_SecureFile::_SecureFile(bool read, bool write, bool truncate, bool append) + : __pNormalFile(null) + , __virtualFilePointer(0) + , __pKey(null) +{ + _read = read; + _write = write; + _truncate = truncate; + _append = append; +} + +_SecureFile::~_SecureFile(void) +{ + delete __pNormalFile; + delete __pKey; +} + +result +_SecureFile::Construct(const String& filePath, const char* pOpenMode, const ByteBuffer* pKeyBuffer) +{ + SysAssertf(__pNormalFile == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + + result r = E_SUCCESS; + + SysTryReturnResult(NID_IO, !(pKeyBuffer && pKeyBuffer->GetRemaining() <= 0), E_INVALID_ARG, + "Invalid Key parameter"); + + unique_ptr< Tizen::Base::ByteBuffer > pKey(_SecureIoUtil::GetSecureKeyN(pKeyBuffer)); + SysTryReturnResult(NID_IO, !(pKey == null || (pKey != null && pKey->GetRemaining() < ONE_BLOCK_SIZE)), E_INVALID_ARG, "Unable to generate key!"); + + unique_ptr< _NormalFile > pNormalFile(new (std::nothrow) _NormalFile()); + SysTryReturnResult(NID_IO, pNormalFile != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + if (!_read) + { + unique_ptr< char[] > pMode(new char[strlen(pOpenMode) + 2]); + strcpy(pMode.get(), pOpenMode); + strcat(pMode.get(), "+\0"); + r = pNormalFile->Construct(filePath, pMode.get()); + } + else + { + r = pNormalFile->Construct(filePath, pOpenMode); + } + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to open file (%ls) in openmode (%s).", + GetErrorMessage(r), filePath.GetPointer(), pOpenMode); + + if (_append) + { + r = _SecureIoUtil::GetDataLengh(pNormalFile.get(), &__virtualFilePointer); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + return r; + } + } + + if (!(_SecureIoUtil::IsEmpty(filePath))) + { + Tizen::Io::_FlagState flag; + + r = _SecureIoUtil::CheckFlag(pNormalFile.get(), &flag); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to check flags in file header.", GetErrorMessage(r)); + + if (flag == FLAG_STATE_CVF_CTF) + { + r = _SecureIoUtil::DeleteBlockReplica(pNormalFile.get(), filePath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to delete block replica of file.", GetErrorMessage(r)); + + r = _SecureIoUtil::SetFlag(pNormalFile.get(), FLAG_STATE_CVF); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set flags in file header.", GetErrorMessage(r)); + } + else if (flag == FLAG_STATE_CTF) + { + r = _SecureIoUtil::RestoreCorruptBlock(pNormalFile.get(), filePath); + SysTryReturnResult(NID_IO, !IsFailed(r), E_IO, "Failed to set flags in file header."); + + r = _SecureIoUtil::DeleteBlockReplica(pNormalFile.get(), filePath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to delete block replica of file.", GetErrorMessage(r)); + + r = _SecureIoUtil::SetFlag(pNormalFile.get(), FLAG_STATE_CVF); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set flags in file header.", GetErrorMessage(r)); + } + else if (flag == FLAG_STATE_CVF) + { + //Do Nothing + } + else + { + int readItems = 0; + int dataLen = 0; + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_10_BYTES); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek file (%ls) in openMode (%s).", + GetErrorMessage(r), filePath.GetPointer(), pOpenMode); + + readItems = pNormalFile->Read(&dataLen, SECURE_IO_LOF_SIZE); // read LoF + if (readItems < SECURE_IO_LOF_SIZE) + { + if (_SecureIoUtil::IsEndOfFile(pNormalFile.get()) && readItems == 0) + { + r = E_END_OF_FILE; + } + else + { + r = __ConvertNativeErrorToResult(errno); + } + + SysLog(NID_IO, "[%s] Failed to fread file (%ls) in openMode (%s), (errno: %d).", + GetErrorMessage(r), filePath.GetPointer(), pOpenMode, errno); + return r; + } + + if (dataLen > SECURE_FILE_HEADER_SIZE_V1) + { + r = pNormalFile->Truncate(dataLen); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to truncate file (%ls) in openMode (%ls).", GetErrorMessage(r)); + + r = pNormalFile->Flush(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to flush data to file", GetErrorMessage(r)); + + r = _SecureIoUtil::SetFlag(pNormalFile.get(), FLAG_STATE_CVF); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set flags in file header.", GetErrorMessage(r)); + } + else + { + r = pNormalFile->Truncate(0); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to truncate file (%ls) in openMode (%s).", + GetErrorMessage(r), filePath.GetPointer(), pOpenMode); + + r = pNormalFile->Flush(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to flush data to file", GetErrorMessage(r)); + + } + } + } + + __filePath = filePath; + __pNormalFile = pNormalFile.release(); + __pKey = pKey.release(); + + return E_SUCCESS; +} + +result +_SecureFile::Read(ByteBuffer& buffer) +{ + result r = E_SUCCESS; + int dataPos = 0; + int length = buffer.GetRemaining(); + int curPos = buffer.GetPosition(); + int readBytes = 0; + const byte* pTempBuffer = null; + + ClearLastResult(); + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysTryReturnResult(NID_IO, length > 0, E_INVALID_ARG, "Invalid argument passed."); + SysAssert(curPos >= 0); + + r = _SecureIoUtil::SelectCipherBlock(__pNormalFile, __virtualFilePointer, &dataPos); + if (IsFailed(r)) + { + if (r == E_STORAGE_FULL) + { + r = E_IO; + } + return r; + } + pTempBuffer = buffer.GetPointer(); + r = _SecureIoUtil::ReadDataFromCipherBlock(__pNormalFile, dataPos, length, (const_cast< byte* >(pTempBuffer) + curPos), DATA_FORMAT_BYTE, &readBytes, *__pKey); + if (IsFailed(r)) + { + SysTryReturnResult(NID_IO, !(r == E_INVALID_OPERATION), E_ILLEGAL_ACCESS, "File is not opened for reading!"); + SysLog(NID_IO, "[%s] Failed to read data from file", GetErrorMessage(r)); + return r; + } + + SysTryReturnResult(NID_IO, readBytes >= 0, E_IO, "Read bytes value is invalid"); + + r = buffer.SetPosition(curPos + readBytes); + SysAssert(!IsFailed(r)); + __virtualFilePointer = __virtualFilePointer + readBytes; + + return r; +} + +int +_SecureFile::Read(void* pBuffer, int length) +{ + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturn(NID_IO, !(pBuffer == null || length <= 0), 0, E_INVALID_ARG, "[E_INVALID_ARG] Invalid argument passed."); + + int readBytes = 0; + int dataPos = 0; + result r = E_SUCCESS; + + r = _SecureIoUtil::SelectCipherBlock(__pNormalFile, __virtualFilePointer, &dataPos); + if (IsFailed(r)) + { + if (r == E_STORAGE_FULL) + { + r = E_IO; //for security error + } + SysPropagate(NID_IO, r); + return 0; + } + + r = _SecureIoUtil::ReadDataFromCipherBlock(__pNormalFile, dataPos, length, reinterpret_cast< byte* >(pBuffer), DATA_FORMAT_BYTE, &readBytes, *__pKey); + if (IsFailed(r)) + { + SysTryReturn(NID_IO, !(r == E_INVALID_OPERATION), 0, E_ILLEGAL_ACCESS, "[E_ILLEGAL_ACCESS]File is not opended for reading!"); + SysLog(NID_IO, "[%s] Failed to read data from file", GetErrorMessage(r)); + SysPropagate(NID_IO, r); + return 0; + } + + SysTryReturn(NID_IO, readBytes >= 0, 0, E_IO, "[E_IO] Failed to read specified bytes from file."); + + __virtualFilePointer = __virtualFilePointer + readBytes; + + SetLastResult(r); + return readBytes; +} + +result +_SecureFile::Read(String& buffer) +{ + result r = E_SUCCESS; + int dataPos = 0; + int readItems = 0; + char bstrBuf[FIO_LEN_4K] = {0, }; + + ClearLastResult(); + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + + buffer.Clear(); + + r = _SecureIoUtil::SelectCipherBlock(__pNormalFile, __virtualFilePointer, &dataPos); + if (IsFailed(r)) + { + if (r == E_STORAGE_FULL) + { + r = E_IO; //for security error + } + return r; + } + + r = _SecureIoUtil::ReadDataFromCipherBlock(__pNormalFile, dataPos, sizeof(bstrBuf), reinterpret_cast< byte* >(bstrBuf), DATA_FORMAT_STRING, &readItems, *__pKey); + if (IsFailed(r)) + { + SysTryReturnResult(NID_IO, !(r == E_INVALID_OPERATION), E_ILLEGAL_ACCESS, "File is not opened for reading!"); + SysLog(NID_IO, "[%s] Failed to read data from file", GetErrorMessage(r)); + return r; + } + SysAssert(readItems > 0); + __virtualFilePointer = __virtualFilePointer + readItems; + + { + String tmp(bstrBuf); + buffer = tmp; + } + + return r; +} + +result +_SecureFile::Write(const ByteBuffer& buffer) +{ + return Write(buffer.GetPointer(), buffer.GetLimit()); +} + +result +_SecureFile::Write(const void* pBuffer, int length) +{ + result r = E_SUCCESS; + int dataPos = 0; + bool eofSet = false; + bool replica = false; + + ClearLastResult(); + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + + SysTryReturnResult(NID_IO, !(!pBuffer || length <= 0), E_INVALID_ARG, "Invalid argument passed."); + + r = _SecureIoUtil::InsertSecureFileHeader(__pNormalFile); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write file headers.", GetErrorMessage(r)); + + r = _SecureIoUtil::SaveLengthOfFile(__pNormalFile); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set length in file header.", GetErrorMessage(r)); + + r = _SecureIoUtil::SelectCipherBlock(__pNormalFile, __virtualFilePointer, &dataPos); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + + if (dataPos == 0) + { + eofSet = _SecureIoUtil::IsEndOfFile(__pNormalFile); + + if (eofSet) + { + r = _SecureIoUtil::SetFlag(__pNormalFile, FLAG_STATE_NONE); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to set flags in file header.", GetErrorMessage(r)); + + replica = false; + } + else + { + r = _SecureIoUtil::MakeCipherBlockReplica(__pNormalFile, __filePath, dataPos, length); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to make cipher block replica of file.", GetErrorMessage(r)); + + r = _SecureIoUtil::SetFlag(__pNormalFile, FLAG_STATE_CTF); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to set flags in file header.", GetErrorMessage(r)); + + replica = true; + } + + } + else + { + r = _SecureIoUtil::MakeCipherBlockReplica(__pNormalFile, __filePath, dataPos, length); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to make cipher block replica of file.", GetErrorMessage(r)); + + r = _SecureIoUtil::SetFlag(__pNormalFile, FLAG_STATE_CTF); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to set flags in file header.", GetErrorMessage(r)); + + replica = true; + } + + r = _SecureIoUtil::WriteDataInCipherBlock(__pNormalFile, dataPos, eofSet, length, const_cast< byte* >(static_cast< const byte* >(pBuffer)), *__pKey); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + + if (replica) + { + r = _SecureIoUtil::SetFlag(__pNormalFile, FLAG_STATE_CVF_CTF); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to set flags in file header.", GetErrorMessage(r)); + r = _SecureIoUtil::DeleteBlockReplica(__pNormalFile, __filePath); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failedt to delete block replica of file.", GetErrorMessage(r)); + } + + r = _SecureIoUtil::SetFlag(__pNormalFile, FLAG_STATE_CVF); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to set flags in file header.", GetErrorMessage(r)); + + __virtualFilePointer = __virtualFilePointer + length; + +CATCH: + + SysTryReturnResult(NID_IO, !(r == E_INVALID_OPERATION), E_ILLEGAL_ACCESS, "File is not opened for writing!"); + + return r; +} + +result +_SecureFile::Write(const String& buffer) +{ + unique_ptr< char[] > pData(_StringConverter::CopyToCharArrayN(buffer)); + + SysTryReturn(NID_IO, pData != null, GetLastResult(), GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult())); + + return Write(pData.get(), buffer.GetLength()); +} + +result +_SecureFile::Flush(void) +{ + result r = E_SUCCESS; + ClearLastResult(); + + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + r = __pNormalFile->Flush(); + return r; +} + +int +_SecureFile::Tell(void) const +{ + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + + long dataLen = 0; + result r = E_SUCCESS; + int ret = 0; + + r = _SecureIoUtil::GetDataLengh(__pNormalFile, &dataLen); + if (IsFailed(r)) + { + if (r == E_ILLEGAL_ACCESS || r == E_STORAGE_FULL || r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + + SysTryCatch(NID_IO, (dataLen >= __virtualFilePointer), r = E_IO, E_IO, "[E_IO] Failed to tell in file."); + + ret = __virtualFilePointer; + + // fall through +CATCH: + return ret; +} + +result +_SecureFile::Seek(FileSeekPosition position, long offset) +{ + result r = E_SUCCESS; + long fileEndPos = 0; + long tempFilePointer = 0; + + ClearLastResult(); + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + + r = _SecureIoUtil::GetDataLengh(__pNormalFile, &fileEndPos); + if (IsFailed(r)) + { + if (r == E_ILLEGAL_ACCESS || r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + return r; + } + + switch (position) + { + case FILESEEKPOSITION_BEGIN: + tempFilePointer = 0; + break; + + case FILESEEKPOSITION_CURRENT: + tempFilePointer = __virtualFilePointer; + break; + + case FILESEEKPOSITION_END: + tempFilePointer = fileEndPos; + break; + + default: + SysAssert(false); + break; + } + + if (tempFilePointer + offset > fileEndPos) + { + //In Linux , Seek () will set file position beyond end of file also even if file is opened in READONLY. + if (_write == false) + { + return E_ILLEGAL_ACCESS; + } + else + { + unique_ptr< byte[] > pTempBuffer(new (std::nothrow) byte[tempFilePointer + offset - fileEndPos]); + SysTryReturnResult(NID_IO, pTempBuffer != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memset(pTempBuffer.get(), 0, tempFilePointer + offset - fileEndPos); + __virtualFilePointer = fileEndPos; + + r = this->Write(pTempBuffer.get(), tempFilePointer + offset - fileEndPos); + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write data in to the file.", GetErrorMessage(r)); + + } + } + else if (tempFilePointer + offset == fileEndPos) + { + __virtualFilePointer = fileEndPos; + } + else if (tempFilePointer + offset < 0) + { + return E_INVALID_ARG; + } + else if (tempFilePointer + offset == 0) + { + __virtualFilePointer = 0; + } + else + { + __virtualFilePointer = tempFilePointer + offset; + } + + return r; +} + +result +_SecureFile::Truncate(int length) +{ + result r = E_SUCCESS; + long fileEndPos = 0; + int readItems = 0; + int dataPos = 0; + + ClearLastResult(); + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + SysTryReturnResult(NID_IO, length >= 0, E_INVALID_ARG, "Invalid argument is passed (length < 0)"); + + if (length == 0) + { + r = __pNormalFile->Truncate(length); + if (r != E_SUCCESS) + { + SysLog(NID_IO, "[%s] Failed to truncate data to file", GetErrorMessage(r)); + } + __virtualFilePointer = 0; + + goto CATCH; + } + + r = _SecureIoUtil::GetDataLengh(__pNormalFile, &fileEndPos); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + + if (length >= fileEndPos) + { + if (length == fileEndPos) + { + this->Seek(FILESEEKPOSITION_END, 0); + goto CATCH; + } + else + { + unique_ptr< byte[] > pTempBuffer(new (std::nothrow) byte[length - fileEndPos]); + SysTryCatch(NID_IO, pTempBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + + memset(pTempBuffer.get(), 0, length - fileEndPos); + r = this->Seek(FILESEEKPOSITION_END, 0); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + r = this->Write(pTempBuffer.get(), length - fileEndPos); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to write data in file.", GetErrorMessage(r)); + } + } + else + { + unique_ptr< byte[] > pTempBuffer(null); + + __virtualFilePointer = length; + r = _SecureIoUtil::SelectCipherBlock(__pNormalFile, __virtualFilePointer, &dataPos); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + + if (dataPos != 0) + { + pTempBuffer = unique_ptr< byte[] >(new (std::nothrow) byte[dataPos]); + SysTryCatch(NID_IO, pTempBuffer, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = _SecureIoUtil::ReadDataFromCipherBlock(__pNormalFile, 0, dataPos, pTempBuffer.get(), DATA_FORMAT_BYTE, &readItems, *__pKey); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + + SysAssert(readItems == dataPos); + r = _SecureIoUtil::SelectCipherBlock(__pNormalFile, __virtualFilePointer, &dataPos); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + } + + length = __pNormalFile->Tell(); + SysTryCatch(NID_IO, length != -1, r = __ConvertNativeErrorToResult(errno), r, "[%s] Failed to tell in file", GetErrorMessage(r)); + + r = __pNormalFile->Truncate(length); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to truncate data to file", GetErrorMessage(r)); + + + r = __pNormalFile->Flush(); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to flush data to file", GetErrorMessage(r)); + + + r = _SecureIoUtil::GetDataLengh(__pNormalFile, &__virtualFilePointer); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + + if (pTempBuffer != null) + { + r = this->Write(static_cast< void* >(pTempBuffer.get()), dataPos); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to write data in file.", GetErrorMessage(r)); + } + } + r = _SecureIoUtil::GetDataLengh(__pNormalFile, &__virtualFilePointer); + if (IsFailed(r)) + { + if (r == E_END_OF_FILE) + { + r = E_IO; //for security error + } + goto CATCH; + } + +CATCH: + + __pNormalFile->Flush(); + return r; +} + +String +_SecureFile::GetName(void) +{ + SysAssertf(__pNormalFile != null, "Not yet constructed. Construct() should be called before use.\n"); + + SetLastResult(E_SUCCESS); // for OSP 2.0 compatibility + return __filePath; +} + +}} // Tizen::Io diff --git a/src/io/FIo_SecureIoUtil.cpp b/src/io/FIo_SecureIoUtil.cpp new file mode 100644 index 0000000..ddf0a69 --- /dev/null +++ b/src/io/FIo_SecureIoUtil.cpp @@ -0,0 +1,1962 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_SecureIoUtil.cpp + * @brief This is the implementation file for the %_SecureIoUilt class. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Security; +using namespace Tizen::Security::Crypto; +using namespace Tizen::App; + +namespace Tizen { namespace Io +{ + +static const int SECURE_IO_4_BITS = 4; +static const int SECURE_IO_8_BITS = 8; +static const int SECURE_IO_3_BYTES = 3; +static const int SECURE_IO_4_BYTES = 4; +static const int SECURE_IO_5_BYTES = 5; +static const int SECURE_IO_8_BYTES = 8; +static const int SECURE_IO_9_BYTES = 9; +static const int SECURE_IO_HEX_0F = 0x0f; +static const int SECURE_IO_HEX_FC = 0xfc; +static const int SECURE_IO_HEX_FD = 0xfd; +static const int SECURE_IO_HEX_FE = 0xfe; +static const int SECURE_IO_HEX_FF = 0xff; +static const int DATABASE_KEY_LENGTH = 16; +static const int AES_KEY_LENGTH = 16; + +const char SECURE_FILE_HEADER_STRING[] = {0x74, 0x69, 0x7a, 0x65, 0x6e, 0x20, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x66, 0x69, 0x6c, 0x65}; +const char SECURE_REG_HEADER_STRING[] = {0x74, 0x69, 0x7a, 0x65, 0x6e, 0x20, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79}; +static const wchar_t* _CIPHER_INFORMATION = L"CBC/128/NOPADDING"; + +ByteBuffer* +_SecureIoUtil::GetSecureKeyN(const ByteBuffer* pUserKey) +{ + result r = E_SUCCESS; + + unique_ptr< Tizen::Base::ByteBuffer > pKey(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_IO, pKey != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pKey->Construct(AES_KEY_LENGTH); + SysTryReturn(NID_IO, !IsFailed(r), null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + if (pUserKey->GetRemaining() >= AES_KEY_LENGTH) + { + r = pKey->SetArray(pUserKey->GetPointer(), 0, AES_KEY_LENGTH); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + } + + else + { + int tempLength = pUserKey->GetRemaining(); + int loopCount = AES_KEY_LENGTH / tempLength; + + for(int i = 0; i < loopCount; i++) + { + + r = pKey->SetArray(pUserKey->GetPointer(), 0, tempLength); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + } + + if (AES_KEY_LENGTH % tempLength) + { + r = pKey->SetArray(pUserKey->GetPointer(), 0, (AES_KEY_LENGTH % tempLength)); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + } + + } + + pKey->Flip(); + + SetLastResult(r); + return pKey.release(); +} + +ByteBuffer* +_SecureIoUtil::DoCipherAesN(const String transformation, const ByteBuffer& input, const ByteBuffer& key, CipherOperation encMode) +{ + result r = E_SUCCESS; + ByteBuffer ivBuffer; + AesCipher aesCipher; + SecretKeyGenerator secKeyGenerator; + + static byte ivArray[] = {0x3E, 0xB5, 0x01, 0x45, 0xE4, 0xF8, 0x75, 0x3F, 0x08, 0x9D, 0x9F, 0x57, 0x3B, 0x63, 0xEF, 0x4B }; + + r = aesCipher.Construct(transformation, encMode); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = ivBuffer.Construct(sizeof(ivArray)); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = ivBuffer.SetArray(ivArray, 0, sizeof(ivArray)); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + ivBuffer.Flip(); + + r = aesCipher.SetInitialVector(ivBuffer); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = secKeyGenerator.Construct(key); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + unique_ptr< ISecretKey > pKey(reinterpret_cast< ISecretKey* >(secKeyGenerator.GenerateKeyN())); + SysTryReturn(NID_IO, pKey != null, null, GetLastResult(), "[%s] Failed to generate key.", GetErrorMessage(GetLastResult())); + + r = aesCipher.SetKey(*pKey.get()); + SysTryReturn(NID_IO, !IsFailed(r), null, r, "[%s] Failed to set secret key.", GetErrorMessage(r)); + + unique_ptr< ByteBuffer > pOutBuf(null); + + if (encMode == CIPHER_ENCRYPT) + { + pOutBuf = unique_ptr< ByteBuffer >(aesCipher.EncryptN(input)); + } + else + { + pOutBuf = unique_ptr< ByteBuffer >(aesCipher.DecryptN(input)); + } + + SysTryReturn(NID_IO, pOutBuf != null, null, GetLastResult(), "[%s] Failed to decrypt data.", GetErrorMessage(GetLastResult())); + + SetLastResult(E_SUCCESS); + return pOutBuf.release(); +} + +bool +_SecureIoUtil::IsEndOfFile(_NormalFile* pNormalFile) +{ + result r = E_SUCCESS; + bool eofSet = false; + byte flag = 0; + int current = pNormalFile->Tell(); + SysTryReturn(NID_IO, current != -1, false, GetLastResult(), "[%s] Failed to tell in file.", GetErrorMessage(GetLastResult())); + + int ret = pNormalFile->Read(&flag, 1); //ignore ret as we are only looking for EOF. + if (GetLastResult() == E_END_OF_FILE && ret == 0) + { + eofSet = true; + } + + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, current); + SysTryReturn(NID_IO, !IsFailed(r), false, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + return eofSet; +} + +result +_SecureIoUtil::InsertSecureFileHeader(_NormalFile* pNormalFile) +{ + result r = E_SUCCESS; + int ret = 0; + byte secureHeader[SECURE_FILE_HEADER_SIZE_V1]; + byte reservedValue[SECURE_IO_STATIC_BIN_LEN] = {0xCA, 0xFE, 0xBE, 0xBE, 0xDA, 0xEF, 0xEB, 0xEB}; + + ClearLastResult(); + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + ret = pNormalFile->Read(secureHeader, SECURE_FILE_HEADER_SIZE_V1); + if (ret < SECURE_FILE_HEADER_SIZE_V1) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) //is true + { + memcpy(secureHeader, SECURE_FILE_HEADER_STRING, SECURE_FILE_HEADER_STRING_SIZE); + memcpy(secureHeader + SECURE_FILE_HEADER_STRING_SIZE, reservedValue, SECURE_IO_STATIC_BIN_LEN); + secureHeader[SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN] = SECURE_IO_2_BYTES; + secureHeader[SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN + SECURE_IO_FLAG_SIZE] = 0; + memset(secureHeader + SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN + SECURE_IO_FLAG_SIZE + SECURE_IO_INDEX_SIZE, 0, SECURE_IO_LOF_SIZE); + memset(secureHeader + SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN + SECURE_IO_FLAG_SIZE + SECURE_IO_INDEX_SIZE + SECURE_IO_LOF_SIZE, 0, SECURE_IO_LOF_SIZE); + + r = pNormalFile->Write(secureHeader, SECURE_FILE_HEADER_SIZE_V1); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] [%s] Failed to write in file.", GetErrorMessage(r)); + + } + else + { + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + } + } //Else it means that header is already written + + return r; +} + +result +_SecureIoUtil::SaveLengthOfFile(_NormalFile* pNormalFile) +{ + result r = E_SUCCESS; + int length = 0; + byte lengthOfFile[SECURE_IO_LOF_SIZE] = {0, 0, 0, 0}; + + ClearLastResult(); + r = pNormalFile->Seek(FILESEEKPOSITION_END, 0); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + length = pNormalFile->Tell(); + SysTryReturn(NID_IO, length != -1, GetLastResult(), GetLastResult(), "[%s] Failed to tell in file.", GetErrorMessage(GetLastResult())); + + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_10_BYTES); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + if (sizeof(length) != SECURE_IO_LOF_SIZE) + { + memcpy(lengthOfFile + SECURE_IO_LOF_SIZE - sizeof(length), &length, sizeof(length)); + } + else + { + memcpy(lengthOfFile, &length, SECURE_IO_LOF_SIZE); + } + + r = pNormalFile->Write(lengthOfFile, SECURE_IO_LOF_SIZE); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file.", GetErrorMessage(r)); + + return r; +} + +result +_SecureIoUtil::SelectCipherBlock(_NormalFile* pNormalFile, long virtualFilePointer, int* pPosition) +{ + result r = E_SUCCESS; + int count = 0; + int dataSize = 0; + int ret = 0; + long blockDataSize = 0; + byte secureHeader[SECURE_FILE_HEADER_SIZE_V1] = {0, }; + byte blockHeader[CIPHER_BLOCK_HEADER_SIZE] = {0, 0, 0}; + byte* pBlockDataCur = null; + + ClearLastResult(); + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, 0); + *pPosition = 0; + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + ret = pNormalFile->Read(secureHeader, SECURE_FILE_HEADER_SIZE_V1); + if (ret < SECURE_FILE_HEADER_SIZE_V1) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + return E_SUCCESS; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + //read 1byte to check padding size + while (true) + { + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, count * (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE) + SECURE_FILE_HEADER_SIZE_V1); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + ret = pNormalFile->Read(blockHeader, CIPHER_BLOCK_HEADER_SIZE); + if (ret < CIPHER_BLOCK_HEADER_SIZE) //less data read + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + return E_SUCCESS; + } + + SysLog(NID_IO, "[%s] Failed to read data from file", GetErrorMessage(r)); + return r; + } + + + blockDataSize = 0; + pBlockDataCur = (byte*) (&blockDataSize); + *pBlockDataCur = blockHeader[SECURE_IO_2_BYTES]; + *(pBlockDataCur + 1) = blockHeader[1]; + *(pBlockDataCur + SECURE_IO_2_BYTES) = blockHeader[0]; + + if (virtualFilePointer <= dataSize + blockDataSize) + { + *pPosition = virtualFilePointer - dataSize; + if (*pPosition == CIPHER_BLOCK_SIZE) + { + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, CIPHER_BLOCK_SIZE); + *pPosition = 0; + } + else + { + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, -CIPHER_BLOCK_HEADER_SIZE); + } + + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + break; + } + else + { + dataSize = dataSize + blockDataSize; + } + + count++; + } + + return E_SUCCESS; +} + +bool +_SecureIoUtil::DetectNewLine(byte* pData, int readSize, int preReadSize, int* pTerminationCur, int* newLineSize) +{ + int count = 0; + + *newLineSize = 0; + ClearLastResult(); + for (count = preReadSize; count < readSize; count++) + { + if (pData[count] == '\r' && pData[count + 1] == '\n') + { + *pTerminationCur = count; + *newLineSize = SECURE_IO_2_BYTES; + return true; + } + + if (pData[count] == '\n') + { + *pTerminationCur = count; + *newLineSize = 1; + return true; + } + } + + return false; +} + +result +_SecureIoUtil::MakeCipherBlock(byte* pData, int dataSize, byte** ppEncryptedData, int* pEncryptedDataSize, const ByteBuffer& key) +{ + result r = E_SUCCESS; + int blockCount = 0; + int lastDataSize = 0; + int tempSize = 0; + int inputSize = 0; + byte* pTempRealloc = null; + byte* pTempEncryptedData = null; + ByteBuffer input; + + SysTryReturnResult(NID_SEC, dataSize > 0, E_INVALID_ARG, "Input data is not valid."); + + ClearLastResult(); + *pEncryptedDataSize = 0; + + blockCount = dataSize / CIPHER_BLOCK_SIZE; + lastDataSize = dataSize % CIPHER_BLOCK_SIZE; + if (lastDataSize != 0) + { + blockCount = blockCount + 1; + } + else + { + lastDataSize = CIPHER_BLOCK_SIZE; + } + + for (int i = 0; i < blockCount; i++) + { + if (i == blockCount - 1) + { + tempSize = lastDataSize; + } + else + { + tempSize = CIPHER_BLOCK_SIZE; + } + + inputSize = tempSize; + + if (tempSize % ONE_BLOCK_SIZE != 0) + { + tempSize = (tempSize / ONE_BLOCK_SIZE) * ONE_BLOCK_SIZE + ONE_BLOCK_SIZE; + } + + r = input.Construct(tempSize); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + + r = input.SetArray((byte*) (pData + i * CIPHER_BLOCK_SIZE), 0, inputSize); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + + if (inputSize < tempSize) + { + unique_ptr< char[] > pFill(new (std::nothrow) char[tempSize - inputSize]); + SysTryCatch(NID_IO, pFill != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + memset(pFill.get(), 0, tempSize - inputSize); + + r = input.SetArray(reinterpret_cast< byte* >(pFill.get()), 0, tempSize - inputSize); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Propagated.", GetErrorMessage(r)); + + } + + input.Flip(); + + unique_ptr< ByteBuffer > pEncryptedBuffer(DoCipherAesN(_CIPHER_INFORMATION, input, key, CIPHER_ENCRYPT)); + SysTryCatch(NID_IO, pEncryptedBuffer != null, r = E_IO, E_IO, "[E_IO] Failed to encrypt data."); + + pTempEncryptedData = const_cast< byte* >(pEncryptedBuffer->GetPointer()); + SysTryCatch(NID_IO, pTempEncryptedData != null, , r, "[%s] Failed to get encrypted data.", GetErrorMessage(r)); + + pTempRealloc = (byte*) new (std::nothrow) byte[*pEncryptedDataSize + tempSize + CIPHER_BLOCK_HEADER_SIZE]; + SysTryCatch(NID_IO, pTempRealloc != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + if (*ppEncryptedData) + { + memcpy(pTempRealloc, *ppEncryptedData, *pEncryptedDataSize); + + delete[]* ppEncryptedData; + *ppEncryptedData = null; + } + + *ppEncryptedData = pTempRealloc; + + if (i == blockCount - 1) + { + + *(*ppEncryptedData + i * (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE) + SECURE_IO_2_BYTES) \ + = (byte) (lastDataSize & SECURE_IO_HEX_FF); + *(*ppEncryptedData + i * (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE) + 1) \ + = (byte) ((lastDataSize >> SECURE_IO_8_BITS) & SECURE_IO_HEX_FF); + *(*ppEncryptedData + i * (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE)) \ + = (byte) ((lastDataSize >> (SECURE_IO_8_BITS * SECURE_IO_2_BYTES)) & SECURE_IO_HEX_FF); + } + else + { + *(*ppEncryptedData + i * (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE) + SECURE_IO_2_BYTES) \ + = (byte) (CIPHER_BLOCK_SIZE & SECURE_IO_HEX_FF); + *(*ppEncryptedData + i * (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE) + 1) \ + = (byte) ((CIPHER_BLOCK_SIZE >> SECURE_IO_8_BITS) & SECURE_IO_HEX_FF); + *(*ppEncryptedData + i * (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE)) \ + = (byte) ((CIPHER_BLOCK_SIZE >> (SECURE_IO_8_BITS * SECURE_IO_2_BYTES)) & SECURE_IO_HEX_FF); + } + + memcpy(*ppEncryptedData + i * (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE) + CIPHER_BLOCK_HEADER_SIZE, pTempEncryptedData, tempSize); + *pEncryptedDataSize = *pEncryptedDataSize + tempSize + CIPHER_BLOCK_HEADER_SIZE; + } + + CATCH: + + if (IsFailed(r)) + { + *pEncryptedDataSize = 0; + delete[]* ppEncryptedData; + *ppEncryptedData = null; + } + + return r; +} + +result +_SecureIoUtil::WriteDataInCipherBlock(_NormalFile* pNormalFile, int dataPosition, bool eofSet, int dataSize, byte* pData, const ByteBuffer& key) +{ + result r = E_SUCCESS; + int availableSize = 0; + int encryptedDataSize = 0; + int ret = 0; + long blockDataSize = 0; + long tempBlockDataSize = 0; + bool isFirstBlockSet = false; + byte* pBlockDataCur = null; + byte* pCipherBlockData = null; + byte* pDataPos = null; + byte blockHeader[CIPHER_BLOCK_HEADER_SIZE] = {0, 0, 0}; + ByteBuffer input; + + pDataPos = pData; + + ClearLastResult(); + while (true) + { + if (eofSet != false && dataPosition == 0) + { + r = MakeCipherBlock(pDataPos, dataSize, &pCipherBlockData, &encryptedDataSize, key); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + unique_ptr< byte[] > pEncryptedBlockData(pCipherBlockData); + pCipherBlockData = null; + + SysTryReturn(NID_IO, pEncryptedBlockData != null, r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + r = pNormalFile->Write(pEncryptedBlockData.get(), encryptedDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + break; + } + else + { + ret = pNormalFile->Read(blockHeader, CIPHER_BLOCK_HEADER_SIZE); + if (ret < CIPHER_BLOCK_HEADER_SIZE) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + blockDataSize = 0; + pBlockDataCur = (byte*) (&blockDataSize); + *pBlockDataCur = blockHeader[SECURE_IO_2_BYTES]; + *(pBlockDataCur + 1) = blockHeader[1]; + *(pBlockDataCur + SECURE_IO_2_BYTES) = blockHeader[0]; + + unique_ptr< byte[] > pTempEncryptedData(new (std::nothrow) byte[CIPHER_BLOCK_SIZE]); + SysTryReturnResult(NID_IO, pTempEncryptedData != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memset(pTempEncryptedData.get(), 0, CIPHER_BLOCK_SIZE); + + if (blockDataSize % ONE_BLOCK_SIZE != 0) + { + tempBlockDataSize = blockDataSize + ONE_BLOCK_SIZE - blockDataSize % ONE_BLOCK_SIZE; + } + else + { + tempBlockDataSize = blockDataSize; + } + + ret = pNormalFile->Read(pTempEncryptedData.get(), tempBlockDataSize); + if (ret < tempBlockDataSize) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + r = input.Construct(tempBlockDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = input.SetArray(pTempEncryptedData.get(), 0, tempBlockDataSize); + + pTempEncryptedData.reset(null); + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + input.Flip(); + + unique_ptr< ByteBuffer > pDecryptedBuffer(DoCipherAesN(_CIPHER_INFORMATION, input, key, CIPHER_DECRYPT)); + SysTryReturn(NID_IO, pDecryptedBuffer != null, E_IO, E_IO, "[E_IO] Failed to encrypt data."); + + unique_ptr< byte[] > pDecryptedBlockData(new (std::nothrow) byte[tempBlockDataSize]); + SysTryReturnResult(NID_IO, pDecryptedBlockData != null, E_OUT_OF_MEMORY, "The memory is insufficient"); + + r = pDecryptedBuffer->GetArray(reinterpret_cast< byte* >(pDecryptedBlockData.get()), 0, tempBlockDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to get decrypted buffer.", GetErrorMessage(r)); + + pDecryptedBuffer->Flip(); + + pDecryptedBuffer.reset(null); + + if (isFirstBlockSet == false) + { + availableSize = CIPHER_BLOCK_SIZE - dataPosition; + if (availableSize >= dataSize) + { + if (tempBlockDataSize < dataPosition + dataSize) + { + unique_ptr< byte[] > pTempRealloc(new (std::nothrow) byte[dataPosition + dataSize]); + SysTryReturnResult(NID_IO, pTempRealloc != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memcpy(pTempRealloc.get(), pDecryptedBlockData.get(), tempBlockDataSize); + + pDecryptedBlockData.reset(null); + pDecryptedBlockData = move(pTempRealloc); + } + + memcpy(reinterpret_cast< byte* >(pDecryptedBlockData.get()) + dataPosition, pDataPos, dataSize); + + if (blockDataSize < dataPosition + dataSize) + { + r = MakeCipherBlock(pDecryptedBlockData.get(), dataPosition + dataSize, &pCipherBlockData, &encryptedDataSize, key); + } + else + { + r = MakeCipherBlock(pDecryptedBlockData.get(), blockDataSize, &pCipherBlockData, &encryptedDataSize, key); + } + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + unique_ptr< byte[] > pEncryptedBlockData(pCipherBlockData); + pCipherBlockData = null; + + SysTryReturn(NID_IO, pEncryptedBlockData != null, r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, -(tempBlockDataSize + CIPHER_BLOCK_HEADER_SIZE)); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + r = pNormalFile->Write(pEncryptedBlockData.get(), encryptedDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file.", GetErrorMessage(r)); + + + break; + } + else //(availableSize < dataSize) + { + if (tempBlockDataSize < dataPosition + availableSize) + { + unique_ptr< byte[] > pTempRelloc(new (std::nothrow) byte[dataPosition + availableSize]); + SysTryReturnResult(NID_IO, pTempRelloc != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memcpy(pTempRelloc.get(), pDecryptedBlockData.get(), tempBlockDataSize); + + pDecryptedBlockData.reset(null); + pDecryptedBlockData = move(pTempRelloc); + } + + memcpy(reinterpret_cast< byte* >(pDecryptedBlockData.get()) + dataPosition, pDataPos, availableSize); + + pDataPos = pDataPos + availableSize; + dataSize = dataSize - availableSize; + + r = MakeCipherBlock(pDecryptedBlockData.get(), CIPHER_BLOCK_SIZE, &pCipherBlockData, &encryptedDataSize, key); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + unique_ptr< byte[] > pEncryptedBlockData(pCipherBlockData); + pCipherBlockData = null; + SysTryReturn(NID_IO, pEncryptedBlockData != null, r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, -(tempBlockDataSize + CIPHER_BLOCK_HEADER_SIZE)); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + r = pNormalFile->Write(pEncryptedBlockData.get(), encryptedDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file.", GetErrorMessage(r)); + + + dataPosition = 0; + } + + isFirstBlockSet = true; + } + else + { + availableSize = CIPHER_BLOCK_SIZE; + if (availableSize >= dataSize) + { + if (tempBlockDataSize < dataSize) + { + unique_ptr< byte[] > pTempRelloc(new (std::nothrow) byte[dataSize]); + SysTryReturnResult(NID_IO, pTempRelloc != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memcpy(pTempRelloc.get(), pDecryptedBlockData.get(), tempBlockDataSize); + + pDecryptedBlockData.reset(null); + pDecryptedBlockData = move(pTempRelloc); + } + + memcpy(pDecryptedBlockData.get(), pDataPos, dataSize); + + if (blockDataSize < dataPosition + dataSize) + { + r = MakeCipherBlock(pDecryptedBlockData.get(), dataSize, &pCipherBlockData, &encryptedDataSize, key); + } + else + { + r = MakeCipherBlock(pDecryptedBlockData.get(), blockDataSize, &pCipherBlockData, &encryptedDataSize, key); + } + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + unique_ptr< byte[] > pEncryptedBlockData(pCipherBlockData); + pCipherBlockData = null; + + SysTryReturn(NID_IO, pEncryptedBlockData != null, r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, -(tempBlockDataSize + CIPHER_BLOCK_HEADER_SIZE)); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + r = pNormalFile->Write(pEncryptedBlockData.get(), encryptedDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file.", GetErrorMessage(r)); + + break; + } + else //availableSize < dataSize + { + if (tempBlockDataSize < availableSize) + { + unique_ptr< byte[] > pTempRelloc(new (std::nothrow) byte[availableSize]); + SysTryReturnResult(NID_IO, pTempRelloc != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memcpy(pTempRelloc.get(), pDecryptedBlockData.get(), tempBlockDataSize); + + pDecryptedBlockData.reset(null); + pDecryptedBlockData = move(pTempRelloc); + } + + memcpy(pDecryptedBlockData.get(), pDataPos, availableSize); + + pDataPos = pDataPos + availableSize; + dataSize = dataSize - availableSize; + + r = MakeCipherBlock(pDecryptedBlockData.get(), CIPHER_BLOCK_SIZE, &pCipherBlockData, &encryptedDataSize, key); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + unique_ptr< byte[] > pEncryptedBlockData(pCipherBlockData); + pCipherBlockData = null; + + SysTryReturn(NID_IO, pEncryptedBlockData != null, r, r, "[%s] Failed to make cipher block for file.", GetErrorMessage(r)); + + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, -(tempBlockDataSize + CIPHER_BLOCK_HEADER_SIZE)); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + r = pNormalFile->Write(pEncryptedBlockData.get(), encryptedDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file.", GetErrorMessage(r)); + + dataPosition = 0; + } + } + } + + eofSet = IsEndOfFile(pNormalFile); + } + + return E_SUCCESS; +} + +result +_SecureIoUtil::ReadDataFromCipherBlock(_NormalFile* pNormalFile, int dataPosition, int bufferSize, byte* pData, _DataFormat dataMode, int* readItems, const ByteBuffer& key) +{ + result r = E_SUCCESS; + int readingSize = 0; + int tempSize = 0; + int terminationCur = 0; + bool eofSet = false; + int newLineSize = 0; + int ret = 0; + long blockDataSize = 0; + long tempBlockDataSize = 0; + byte* pBlockDataCur = null; + byte* pDecryptedBlockData = null; + byte blockHeader[CIPHER_BLOCK_HEADER_SIZE] = {0, 0, 0}; + ByteBuffer input; + + ClearLastResult(); + ret = pNormalFile->Read(blockHeader, CIPHER_BLOCK_HEADER_SIZE); + if (ret < CIPHER_BLOCK_HEADER_SIZE) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + blockDataSize = 0; + pBlockDataCur = (byte*) (&blockDataSize); + *pBlockDataCur = blockHeader[SECURE_IO_2_BYTES]; + *(pBlockDataCur + 1) = blockHeader[1]; + *(pBlockDataCur + SECURE_IO_2_BYTES) = blockHeader[0]; + + unique_ptr< byte[] > pBlockData(new (std::nothrow) byte[CIPHER_BLOCK_SIZE]); + SysTryReturnResult(NID_IO, pBlockData != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memset(pBlockData.get(), 0, CIPHER_BLOCK_SIZE); + + if (blockDataSize % ONE_BLOCK_SIZE != 0) + { + tempBlockDataSize = blockDataSize + ONE_BLOCK_SIZE - blockDataSize % ONE_BLOCK_SIZE; + } + else + { + tempBlockDataSize = blockDataSize; + } + + ret = pNormalFile->Read(pBlockData.get(), tempBlockDataSize); + if (ret < tempBlockDataSize) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + readingSize = blockDataSize - dataPosition; + SysTryReturn(NID_IO, readingSize != 0, r = E_END_OF_FILE, r, "[%s] Failed to get positive value of readingSize.", GetErrorMessage(r)); + + r = input.Construct(tempBlockDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = input.SetArray(pBlockData.get(), 0, tempBlockDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + input.Flip(); + + unique_ptr< ByteBuffer > pDecryptedBuffer(DoCipherAesN(_CIPHER_INFORMATION, input, key, CIPHER_DECRYPT)); + SysTryReturn(NID_IO, pDecryptedBuffer != null, E_IO, E_IO, "[E_IO] Failed to encrypt data."); + + pDecryptedBlockData = const_cast< byte* >(pDecryptedBuffer->GetPointer()); + SysTryReturn(NID_IO, pDecryptedBlockData, r, r, "[%s] Failed to get encrypted data.", GetErrorMessage(r)); + + unique_ptr< byte[] > pTemp(new (std::nothrow) byte[readingSize]); + SysTryReturnResult(NID_IO, pTemp != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memcpy(pTemp.get(), pDecryptedBlockData + dataPosition, readingSize); + + pDecryptedBuffer.reset(null); + + while (true) + { + eofSet = IsEndOfFile(pNormalFile); + + if (dataMode == DATA_FORMAT_BYTE && (readingSize >= bufferSize)) + { + memcpy(pData, pTemp.get(), bufferSize); + *readItems = bufferSize; + break; + } + else if (dataMode == DATA_FORMAT_STRING && ((readingSize >= bufferSize) || DetectNewLine(pTemp.get(), readingSize, tempSize, &terminationCur, &newLineSize))) + { + if (terminationCur != 0) + { + memcpy(pData, pTemp.get(), terminationCur); + *(pData + terminationCur) = '\n'; + *readItems = terminationCur + newLineSize; + } + else + { + memcpy(pData, pTemp.get(), bufferSize); + *readItems = bufferSize; + } + break; + } + else if (eofSet && (readingSize < bufferSize)) + { + memcpy(pData, pTemp.get(), readingSize); + *readItems = readingSize; + break; + } + else + { + ret = pNormalFile->Read(blockHeader, CIPHER_BLOCK_HEADER_SIZE); + if (ret < CIPHER_BLOCK_HEADER_SIZE) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_SUCCESS; + continue; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + blockDataSize = 0; + pBlockDataCur = (byte*) (&blockDataSize); + *pBlockDataCur = blockHeader[SECURE_IO_2_BYTES]; + *(pBlockDataCur + 1) = blockHeader[1]; + *(pBlockDataCur + SECURE_IO_2_BYTES) = blockHeader[0]; + + memset(pBlockData.get(), 0, CIPHER_BLOCK_SIZE); + + if (blockDataSize % ONE_BLOCK_SIZE != 0) + { + tempBlockDataSize = blockDataSize + ONE_BLOCK_SIZE - blockDataSize % ONE_BLOCK_SIZE; + } + else + { + tempBlockDataSize = blockDataSize; + } + + ret = pNormalFile->Read(pBlockData.get(), tempBlockDataSize); + if (ret < tempBlockDataSize) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + r = input.Construct(tempBlockDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = input.SetArray(pBlockData.get(), 0, tempBlockDataSize); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + input.Flip(); + + unique_ptr< ByteBuffer > pDecryptedNextBuffer(DoCipherAesN(_CIPHER_INFORMATION, input, key, CIPHER_DECRYPT)); + SysTryReturn(NID_IO, pDecryptedNextBuffer != null, E_IO, E_IO, "[E_IO] Failed to encrypt data."); + + pDecryptedBlockData = const_cast< byte* >(pDecryptedNextBuffer->GetPointer()); + SysTryReturn(NID_IO, pDecryptedBlockData != null, r, r, "[%s] Failed to get encrypted data.", GetErrorMessage(r)); + + tempSize = readingSize; + readingSize = readingSize + blockDataSize; + + unique_ptr< byte[] > pTempRealloc(new (std::nothrow) byte[readingSize]); + SysTryReturnResult(NID_IO, pTempRealloc != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memcpy(pTempRealloc.get(), pTemp.get(), tempSize); + + pTemp.reset(null); + pTemp = move(pTempRealloc); + + memcpy(reinterpret_cast< byte* >(pTemp.get()) + tempSize, pDecryptedBlockData, blockDataSize); + } + + } + + return E_SUCCESS; +} + +result +_SecureIoUtil::GetDataLengh(_NormalFile* pNormalFile, long int* dataLength) +{ + result r = E_SUCCESS; + int ret = 0; + long blockDataSize = 0; + byte* pBlockDataCur = null; + byte secureHeader[SECURE_FILE_HEADER_SIZE_V1]; + byte blockHeader[CIPHER_BLOCK_HEADER_SIZE] = {0, 0, 0}; + + *dataLength = 0; + + ClearLastResult(); + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + ret = pNormalFile->Read(secureHeader, SECURE_FILE_HEADER_SIZE_V1); + if (ret < SECURE_FILE_HEADER_SIZE_V1) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + return E_SUCCESS; + } + + SysLog(NID_IO, "[%s] Failed to seek in file", GetErrorMessage(r)); + return r; + } + while (true) + { + ret = pNormalFile->Read(blockHeader, CIPHER_BLOCK_HEADER_SIZE); + if (ret < CIPHER_BLOCK_HEADER_SIZE) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_SUCCESS; + break; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + blockDataSize = 0; + pBlockDataCur = (byte*) (&blockDataSize); + *pBlockDataCur = blockHeader[SECURE_IO_2_BYTES]; + *(pBlockDataCur + 1) = blockHeader[1]; + *(pBlockDataCur + SECURE_IO_2_BYTES) = blockHeader[0]; + *dataLength = *dataLength + blockDataSize; + + if (blockDataSize % ONE_BLOCK_SIZE != 0) + { + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, blockDataSize + ONE_BLOCK_SIZE - blockDataSize % ONE_BLOCK_SIZE); + } + else + { + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, blockDataSize); + } + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + } + + return pNormalFile->Seek(FILESEEKPOSITION_END, 0); +} + +result +_SecureIoUtil::CheckSecureFileHeader(const Tizen::Base::String& filePath, const ByteBuffer* pSecretKey) +{ + result r = E_SUCCESS; + int ret = 0; + _NormalFile normalFile; + byte secureFileHeader[SECURE_FILE_HEADER_SIZE_V1]; + byte reservedValue[SECURE_IO_STATIC_BIN_LEN] = {0xCA, 0xFE, 0xBE, 0xBE, 0xDA, 0xEF, 0xEB, 0xEB}; + + ClearLastResult(); + + r = normalFile.Construct(filePath, "r"); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to call constuct.", GetErrorMessage(r)); + + ret = normalFile.Read(secureFileHeader, SECURE_FILE_HEADER_SIZE_V1); + if (ret < SECURE_FILE_HEADER_SIZE_V1) + { + r = GetLastResult(); + if (IsEndOfFile(&normalFile)) + { + if (ret && pSecretKey) + { + return E_INVALID_ARG; + } + else + { + return E_SUCCESS; + } + } + return r; + } + + //check if the file is encrypted file. (in normal and secure mode) + ret = memcmp(secureFileHeader, SECURE_FILE_HEADER_STRING, SECURE_FILE_HEADER_STRING_SIZE); + ret |= memcmp(secureFileHeader + SECURE_FILE_HEADER_STRING_SIZE, reservedValue, SECURE_IO_STATIC_BIN_LEN); + + SysTryReturnResult(NID_IO, !(ret && pSecretKey), E_INVALID_ARG, "Failed to match secure header in file."); + + return E_SUCCESS; +} + +result +_SecureIoUtil::SetRegistryFlag(void* pFileSecure, _FlagState flag) +{ + result r = E_SUCCESS; + int readItems = 0; + int current = 0; + byte currentFlag = 0; + _FileImpl* pFile = (_FileImpl*) pFileSecure; + + ClearLastResult(); + current = pFile->Tell(); + SysTryReturn(NID_IO, current != -1, GetLastResult(), GetLastResult(), "[%s] Tell file has failed.", GetErrorMessage(GetLastResult())); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + readItems = pFile->Read(¤tFlag, 1); + SysTryReturn(NID_IO, readItems == 1, r = E_INVALID_STATE, E_INVALID_STATE, "[E_INVALID_STATE] Tell file has failed."); + + if (flag == FLAG_STATE_CVF) + { + currentFlag = currentFlag | SECURE_IO_2_BYTES; + currentFlag = currentFlag & SECURE_IO_HEX_FE; + } + else if (flag == FLAG_STATE_CTF) + { + currentFlag = currentFlag | 1; + currentFlag = currentFlag & SECURE_IO_HEX_FD; + } + else if (flag == FLAG_STATE_CVF_CTF) + { + currentFlag = currentFlag | SECURE_IO_3_BYTES; + } + else if (flag == FLAG_STATE_NONE) + { + currentFlag = currentFlag & SECURE_IO_HEX_FC; + } + else + { + return E_INVALID_STATE; + } + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + r = pFile->Write(¤tFlag, 1); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write data in file.", GetErrorMessage(r)); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, current); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + return r; +} + +_FlagState +_SecureIoUtil::CheckRegistryFlag(byte* pHeader) +{ + ClearLastResult(); + byte flag = *(pHeader + SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN); + + if (((flag | SECURE_IO_HEX_FD) == SECURE_IO_HEX_FF) && ((flag | SECURE_IO_HEX_FE) != SECURE_IO_HEX_FF)) + { + return FLAG_STATE_CVF; + } + else if (((flag | SECURE_IO_HEX_FD) != SECURE_IO_HEX_FF) && ((flag | SECURE_IO_HEX_FE) == SECURE_IO_HEX_FF)) + { + return FLAG_STATE_CTF; + } + else if ((flag | SECURE_IO_HEX_FC) == SECURE_IO_HEX_FF) + { + return FLAG_STATE_CVF_CTF; + } + else + { + return FLAG_STATE_NONE; + } +} + +const String +_SecureIoUtil::MakeRegistryReplica(const String fileName, byte* pNameIndex) +{ + result r = E_SUCCESS; + String replicaName; + int nameIndex = *pNameIndex; + + ClearLastResult(); + while (true) + { + SysTryReturn(NID_IO, nameIndex <= SECURE_IO_HEX_64, replicaName, E_INVALID_ARG, "[E_INVALID_ARG] Index number is too big."); + + if (nameIndex == 0) + { + replicaName = fileName + L".rpa "; + if (!File::IsFileExist(replicaName)) + { + break; + } + } + else + { + replicaName = fileName + L"_"; + replicaName.Append((int) nameIndex); + replicaName.Append(L".rpa"); + + if (!File::IsFileExist(replicaName)) + { + break; + } + } + + nameIndex++; + } + + *pNameIndex = nameIndex; + + if (_FileImpl::IsFileExist(fileName)) + { + r = _FileImpl::Copy(fileName, replicaName, true); + SysTryReturn(NID_IO, !IsFailed(r), replicaName, r, "[%s] Failed to copy file.", GetErrorMessage(r)); + } + else + { + // open registry replica file + _FileImpl fileImpl; + r = fileImpl.Construct(replicaName, "w", false, null); + SysTryReturn(NID_IO, !IsFailed(r), replicaName, r, "[%s] Failed to create empty file.", GetErrorMessage(r)); + } + + SetLastResult(r); + return replicaName; +} + +result +_SecureIoUtil::DeleteRegistryReplica(byte* pHeader, const String fileName) +{ + result r = E_SUCCESS; + String replicaName; + byte nameIndex = *(pHeader + SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_9_BYTES); + + ClearLastResult(); + + SysTryReturnResult(NID_IO, nameIndex <= SECURE_IO_HEX_64, E_INVALID_ARG, "Index number is too big."); + + if (nameIndex == 0) + { + replicaName = fileName + L".rpa "; + } + else + { + replicaName = fileName + L"_"; + replicaName.Append((int) nameIndex); + replicaName.Append(L".rpa"); + } + + _FileImpl::Remove(replicaName); + + return r; +} + +result +_SecureIoUtil::LoadRegistryReplica(byte** pHeader, int* pHeaderLen, const String fileName) +{ + result r = E_SUCCESS; + int readItems = 0; + int length = 0; + char indexStr[MAX_BLOCK_INDEX_LEN]; + String replicaName; + byte nameIndex = 0; + _FileImpl replicaFile; + + ClearLastResult(); + memset(indexStr, 0, MAX_BLOCK_INDEX_LEN); + nameIndex = *(*pHeader + SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_9_BYTES); + + delete[]* pHeader; + *pHeader = null; + *pHeaderLen = 0; + + SysTryReturnResult(NID_IO, nameIndex <= SECURE_IO_HEX_64, E_INVALID_ARG, "Index number is too big."); + + if (nameIndex == 0) + { + replicaName = fileName + L".rpa "; + } + else + { + replicaName = fileName + L"_"; + replicaName.Append((int) nameIndex); + replicaName.Append(L".rpa"); + } + + if (Tizen::Io::_FileImpl::IsFileExist(replicaName)) + { + r = replicaFile.Construct(replicaName, "r", false, null); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Constructing the file has failed.", GetErrorMessage(r)); + + r = replicaFile.Seek(FILESEEKPOSITION_END, 0); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + length = replicaFile.Tell(); + if (length > 0) + { + *pHeader = new (std::nothrow) byte[length]; + SysTryCatch(NID_IO, *pHeader != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + *pHeaderLen = length; + + r = replicaFile.Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + readItems = replicaFile.Read(*pHeader, length); + SysTryCatch(NID_IO, readItems >= length, r = GetLastResult(), GetLastResult(), "[%s] Failed to read data from file.", GetErrorMessage(GetLastResult())); + + } + } + + CATCH: + + if (IsFailed(r)) + { + delete[]* pHeader; + *pHeader = null; + *pHeaderLen = 0; + } + return r; +} + +result +_SecureIoUtil::CheckSecureRegistryHeader(byte** pHeader, int* pHeaderLen, const String strFilePathPath, bool secureMode) +{ + result r = E_SUCCESS; + int readLen = 0; + int ret = 0; + _FileImpl fileImpl; + _FlagState flag = FLAG_STATE_NONE; + byte reservedValue[SECURE_IO_STATIC_BIN_LEN] = {0xCA, 0xFE, 0xBE, 0xBE, 0xDA, 0xEF, 0xEB, 0xEB}; + byte* pSecureRegistryHeader = *pHeader; + + ClearLastResult(); + //check if the registry is encrypted . (in normal and secure mode) + ret = memcmp(pSecureRegistryHeader, SECURE_REG_HEADER_STRING, SECURE_REG_HEADER_STRING_SIZE); + ret |= memcmp(pSecureRegistryHeader + SECURE_REG_HEADER_STRING_SIZE, reservedValue, SECURE_IO_STATIC_BIN_LEN); + SysTryReturnResult(NID_IO, !(ret && secureMode == true), E_INVALID_ARG, "Failed to match secure header in file."); + + if (secureMode) + { + flag = CheckRegistryFlag(pSecureRegistryHeader); + + if (_FileImpl::IsFileExist(strFilePathPath) && !_SecureIoUtil::IsEmpty(strFilePathPath)) + { + r = fileImpl.Construct(strFilePathPath, "a+", false, null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Constructing the file has failed.", GetErrorMessage(r)); + + if (flag == FLAG_STATE_CVF_CTF) + { + r = DeleteRegistryReplica(pSecureRegistryHeader, strFilePathPath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to delete registry replica.", GetErrorMessage(r)); + + r = SetRegistryFlag(&fileImpl, FLAG_STATE_CVF); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set registry flags.", GetErrorMessage(r)); + + } + else if (flag == FLAG_STATE_CTF) + { + r = LoadRegistryReplica(pHeader, &readLen, strFilePathPath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to load registry replica.", GetErrorMessage(r)); + + SysTryReturn(NID_IO, *pHeader, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to read secure registry file header."); + + pSecureRegistryHeader = *pHeader; + *pHeaderLen = readLen; + + r = DeleteRegistryReplica(pSecureRegistryHeader, strFilePathPath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to delete registry replica.", GetErrorMessage(r)); + + r = SetRegistryFlag(&fileImpl, FLAG_STATE_CVF); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set registry flags.", GetErrorMessage(r)); + } + else if (flag == FLAG_STATE_CVF) + { + ; //Do nothing + } + else + { + r = E_INVALID_STATE; + } + } + } + + return r; +} + +result +_SecureIoUtil::CheckFlag(_NormalFile* pNormalFile, _FlagState* pFlag) +{ + result r = E_SUCCESS; + int ret = 0; + byte flag = 0; + + ClearLastResult(); + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN); + if (r != E_SUCCESS) + { + return r; + } + ret = pNormalFile->Read(&flag, SECURE_IO_FLAG_SIZE); + if (ret < 1) + { +#if 1 + r = GetLastResult(); + SysTryReturnResult(NID_IO, !(ret == 0 && r == E_END_OF_FILE), E_INVALID_ARG, "Failed to read secure file header."); +#else + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); +#endif + return r; + } + + if (((flag | SECURE_IO_HEX_FD) == SECURE_IO_HEX_FF) && ((flag | SECURE_IO_HEX_FE) != SECURE_IO_HEX_FF)) + { + *pFlag = FLAG_STATE_CVF; + } + else if (((flag | SECURE_IO_HEX_FD) != SECURE_IO_HEX_FF) && ((flag | SECURE_IO_HEX_FE) == SECURE_IO_HEX_FF)) + { + *pFlag = FLAG_STATE_CTF; + } + else if ((flag | SECURE_IO_HEX_FC) == SECURE_IO_HEX_FF) + { + *pFlag = FLAG_STATE_CVF_CTF; + } + else + { + *pFlag = FLAG_STATE_NONE; + } + + return r; +} + +result +_SecureIoUtil::SetFlag(_NormalFile* pNormalFile, _FlagState flag) +{ + result r = E_SUCCESS; + int readItems = 0; + int current = 0; + byte currentFlag = 0; + + ClearLastResult(); + current = pNormalFile->Tell(); + if (current == -1) + { + r = GetLastResult(); + SysLog(NID_IO, "[%s] Failed to tell in file", GetErrorMessage(r)); + return r; + } + + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file", GetErrorMessage(r)); + + readItems = pNormalFile->Read(¤tFlag, SECURE_IO_FLAG_SIZE); + if (readItems < 1) + { + r = GetLastResult(); + + if (readItems == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + if (flag == FLAG_STATE_CVF) + { + currentFlag = currentFlag | SECURE_IO_2_BYTES; + currentFlag = currentFlag & SECURE_IO_HEX_FE; + } + else if (flag == FLAG_STATE_CTF) + { + currentFlag = currentFlag | 1; + currentFlag = currentFlag & SECURE_IO_HEX_FD; + } + else if (flag == FLAG_STATE_CVF_CTF) + { + currentFlag = currentFlag | SECURE_IO_3_BYTES; + } + else if (flag == FLAG_STATE_NONE) + { + currentFlag = currentFlag & SECURE_IO_HEX_FC; + } + else + { + SysAssert(false); // should not happen! + } + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file", GetErrorMessage(r)); + + r = pNormalFile->Write(¤tFlag, SECURE_IO_FLAG_SIZE); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file", GetErrorMessage(r)); + + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, current); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file", GetErrorMessage(r)); + + return r; +} + +result +_SecureIoUtil::DeleteBlockReplica(_NormalFile* pNormalFile, const String filePath) +{ + result r = E_SUCCESS; + int readItems = 0; + String replicaName; + byte nameIndex = 0; + + ClearLastResult(); + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_9_BYTES); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file", GetErrorMessage(r)); + + readItems = pNormalFile->Read(&nameIndex, SECURE_IO_INDEX_SIZE); + if (readItems < 1) + { + r = GetLastResult(); + + if (readItems == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + SysTryReturnResult(NID_IO, nameIndex <= SECURE_IO_HEX_64, E_INVALID_ARG, "Index number is too big."); + + if (nameIndex == 0) + { + replicaName = filePath + L".rpa "; + } + else + { + replicaName = filePath + L"_"; + replicaName.Append((int) nameIndex); + replicaName.Append(L".rpa"); + } + + _FileImpl::Remove(replicaName); + + return r; +} + +result +_SecureIoUtil::RestoreCorruptBlock(_NormalFile* pNormalFile, String fileName) +{ + result r = E_SUCCESS; + String blockName = null; + byte nameIndex = 0; + byte blockHeader[CIPHER_BLOCK_HEADER_SIZE] = {0, 0, 0}; + byte* pBlockDataCur = null; + _NormalFile replicaFile; + int startBlockNum = 0; + int readItems = 0; + int fileLength = 0; + int dataLen = 0; + + ClearLastResult(); + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_FILE_HEADER_STRING_SIZE + SECURE_IO_9_BYTES); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file", GetErrorMessage(r)); + + readItems = pNormalFile->Read(&nameIndex, SECURE_IO_INDEX_SIZE); // read index of temporary block name + if (readItems < SECURE_IO_INDEX_SIZE) + { + r = GetLastResult(); + + if (readItems == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + readItems = pNormalFile->Read(&dataLen, SECURE_IO_LOF_SIZE); + if (readItems < SECURE_IO_LOF_SIZE) + { + r = GetLastResult(); + + if (readItems == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + SysTryReturnResult(NID_IO, nameIndex < SECURE_IO_HEX_64, E_INVALID_ARG, "Index number is too big."); + + if (nameIndex == 0) + { + blockName = fileName + L".rpa "; + } + else + { + blockName = fileName + L"_"; + blockName.Append((int) nameIndex); + blockName.Append(L".rpa"); + } + + if (_FileUtil::IsFileExist(blockName)) + { + r = replicaFile.Construct(blockName, "r"); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to conctruct replica file.", GetErrorMessage(r)); + + readItems = replicaFile.Read(blockHeader, CIPHER_BLOCK_HEADER_SIZE); //Read start block number (3bytes) + if (readItems < CIPHER_BLOCK_HEADER_SIZE) + { + r = GetLastResult(); + + if (readItems == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + pBlockDataCur = (byte*) (&startBlockNum); + *pBlockDataCur = blockHeader[SECURE_IO_2_BYTES]; + *(pBlockDataCur + 1) = blockHeader[1]; + *(pBlockDataCur + SECURE_IO_2_BYTES) = blockHeader[0]; + + r = replicaFile.Seek(FILESEEKPOSITION_END, 0); + fileLength = replicaFile.Tell(); + SysTryReturn(NID_IO, fileLength != -1, GetLastResult(), GetLastResult(), "[%s] Failed to tell in file.", GetErrorMessage(GetLastResult())); + + r = replicaFile.Seek(FILESEEKPOSITION_BEGIN, CIPHER_BLOCK_HEADER_SIZE); + unique_ptr< byte[] > pBlock(new (std::nothrow) byte[fileLength - CIPHER_BLOCK_HEADER_SIZE]); + SysTryReturnResult(NID_IO, pBlock != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + memset(pBlock.get(), 0, fileLength - CIPHER_BLOCK_HEADER_SIZE); + + readItems = replicaFile.Read(pBlock.get(), fileLength - CIPHER_BLOCK_HEADER_SIZE); + if (readItems < (fileLength - CIPHER_BLOCK_HEADER_SIZE)) + { + r = GetLastResult(); + + if (readItems == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_FILE_HEADER_SIZE_V1 + (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE) * startBlockNum); + + r = pNormalFile->Write(pBlock.get(), fileLength - CIPHER_BLOCK_HEADER_SIZE); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file.", GetErrorMessage(r)); + + } + + r = pNormalFile->Truncate(dataLen); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to truncate in file.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_SecureIoUtil::MakeCipherBlockReplica(_NormalFile* pNormalFile, const String filePath, int dataPosition, int dataSize) +{ + result r = E_SUCCESS; + int totalDataSize = 0; + int blockSize = 0; + int headPos = 0; + int tailPos = 0; + int startBlockNum = 0; + int ret = 0; + long blockDataSize = 0; + bool isEndOfBlock = false; + String replicaName; + byte* pBlockDataCur = null; + byte blockHeader[CIPHER_BLOCK_HEADER_SIZE] = {0, 0, 0}; + byte nameIndex = 0; + _NormalFile tempBlockFile; + + totalDataSize = dataPosition + dataSize; + + ClearLastResult(); + headPos = pNormalFile->Tell(); + SysTryReturn(NID_IO, headPos != -1, GetLastResult(), GetLastResult(), "[%s] Failed to tell in file.", GetErrorMessage(GetLastResult())); + + ret = pNormalFile->Read(blockHeader, CIPHER_BLOCK_HEADER_SIZE); + if (ret < CIPHER_BLOCK_HEADER_SIZE) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + while (true) + { + blockDataSize = 0; + pBlockDataCur = (byte*) (&blockDataSize); + *pBlockDataCur = blockHeader[SECURE_IO_2_BYTES]; + *(pBlockDataCur + 1) = blockHeader[1]; + *(pBlockDataCur + SECURE_IO_2_BYTES) = blockHeader[0]; + blockSize = blockSize + blockDataSize; + + if (blockSize >= totalDataSize) + { + isEndOfBlock = true; + } + + if (blockDataSize % ONE_BLOCK_SIZE != 0) + { + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, blockDataSize + ONE_BLOCK_SIZE - blockDataSize % ONE_BLOCK_SIZE); + } + else + { + r = pNormalFile->Seek(FILESEEKPOSITION_CURRENT, blockDataSize); + } + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + if (isEndOfBlock) + { + break; + } + + if (IsEndOfFile(pNormalFile)) + { + break; + } + + ret = pNormalFile->Read(blockHeader, CIPHER_BLOCK_HEADER_SIZE); + if (ret < CIPHER_BLOCK_HEADER_SIZE) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + break; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + } + + tailPos = pNormalFile->Tell(); + SysTryReturn(NID_IO, tailPos != -1, GetLastResult(), GetLastResult(), "[%s] Failed to tell in file.", GetErrorMessage(GetLastResult())); + + startBlockNum = (headPos - SECURE_FILE_HEADER_SIZE_V1) / (CIPHER_BLOCK_SIZE + CIPHER_BLOCK_HEADER_SIZE); + + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, headPos); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + unique_ptr< byte[] > pBlockReplica(new (std::nothrow) byte[tailPos - headPos + CIPHER_BLOCK_HEADER_SIZE]); + SysTryReturnResult(NID_IO, pBlockReplica != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + *(reinterpret_cast< byte* >(pBlockReplica.get()) + SECURE_IO_2_BYTES) = (byte) (startBlockNum & SECURE_IO_HEX_FF); + *(reinterpret_cast< byte* >(pBlockReplica.get()) + 1) = (byte) ((startBlockNum >> SECURE_IO_8_BITS) & SECURE_IO_HEX_FF); + *(reinterpret_cast< byte* >(pBlockReplica.get())) = (byte) ((startBlockNum >> (SECURE_IO_8_BITS * SECURE_IO_2_BYTES)) & SECURE_IO_HEX_FF); + + ret = pNormalFile->Read(reinterpret_cast< byte* >(pBlockReplica.get()) + CIPHER_BLOCK_HEADER_SIZE, tailPos - headPos); + if (ret < (tailPos - headPos)) + { + r = GetLastResult(); + + if (ret == 0 && IsEndOfFile(pNormalFile)) + { + r = E_END_OF_FILE; + } + + SysLog(NID_IO, "[%s] Failed to read data from file.", GetErrorMessage(r)); + return r; + } + + while (true) + { + SysTryReturnResult(NID_IO, nameIndex <= SECURE_IO_HEX_64, E_INVALID_ARG, "Index number is too big."); + + if (nameIndex == 0) + { + replicaName = filePath + L".rpa "; + if (!File::IsFileExist(replicaName)) + { + break; + } + } + else + { + replicaName = filePath + L"_"; + replicaName.Append((int) nameIndex); + replicaName.Append(L".rpa"); + + if (!File::IsFileExist(replicaName)) + { + break; + } + } + nameIndex++; + } + + r = tempBlockFile.Construct(replicaName, "w"); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to call construct.", GetErrorMessage(r)); + + r = tempBlockFile.Write(pBlockReplica.get(), tailPos - headPos + CIPHER_BLOCK_HEADER_SIZE); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file.", GetErrorMessage(r)); + + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, 25); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + r = pNormalFile->Write(&nameIndex, 1); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write in file.", GetErrorMessage(r)); + + r = pNormalFile->Seek(FILESEEKPOSITION_BEGIN, headPos); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + return r; +} + +bool +_SecureIoUtil::IsNormalDatabase(_DatabaseMode mode) +{ + ClearLastResult(); + if (mode == DATABASE_MODE_NORMAL) + { + return true; + } + return false; +} + +bool +_SecureIoUtil::IsSecureDatabase(_DatabaseMode mode) +{ + ClearLastResult(); + if (mode == DATABASE_MODE_SECURE) + { + return true; + } + return false; +} + +_DatabaseMode +_SecureIoUtil::GetDatabaseMode(char* pStrPhysicalDbPath) +{ + result r = E_SUCCESS; + int fileLength = 0; + unsigned long readBytes = 0; + char buffer[SQLITE_HEADER_SIZE] = {0, }; + char magicNum1[SECURE_IO_MAGIC_NUMBER_SIZE] = {0xCA, 0xFE, 0xBE, 0xBE}; + char magicNum2[SECURE_IO_MAGIC_NUMBER_SIZE] = {0xDA, 0xEF, 0xEF, 0xEB}; + _NormalFile normalFile; + + ClearLastResult(); + + r = normalFile.Construct(pStrPhysicalDbPath, "r"); + SysTryReturn(NID_IO, !IsFailed(r), DATABASE_MODE_ERROR, r, "[%s] Failed to open file (%s) in read mode", GetErrorMessage(r), pStrPhysicalDbPath); + + r = normalFile.Seek(FILESEEKPOSITION_END, 0); + SysTryReturn(NID_IO, !IsFailed(r), DATABASE_MODE_ERROR, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + fileLength = normalFile.Tell(); + if (fileLength <= 0) + { + return DATABASE_MODE_NONE; + } + + r = normalFile.Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryReturn(NID_IO, !IsFailed(r), DATABASE_MODE_ERROR, r, "[%s] Failed to seek in file.", GetErrorMessage(r)); + + readBytes = normalFile.Read(buffer, SQLITE_HEADER_SIZE); + r = GetLastResult(); + SysTryReturn(NID_IO, readBytes > 0, DATABASE_MODE_ERROR, r, "[%s] File is not opened for reading or else failed to read data from file.", GetErrorMessage(r)); + + if (!strncmp(buffer, "SQLite format 3", SQLITE_FORMAT_STR_SIZE)) + { + return DATABASE_MODE_NORMAL; + } //is normal file + else if (!memcmp((void*) buffer, magicNum1, SECURE_IO_MAGIC_NUMBER_SIZE) && !memcmp((void*) (buffer + SECURE_IO_12_BYTES), magicNum2, SECURE_IO_MAGIC_NUMBER_SIZE)) + { + return DATABASE_MODE_SECURE; + } //is secure file + + return DATABASE_MODE_ERROR; +} + +byte* +_SecureIoUtil::GenerateDatabaseKeyN(const Tizen::Base::ByteBuffer* pUserKey) +{ + byte lowByte = 0; + byte highByte = 0; + byte* pKey = null; + byte* pDbKey = null; + + ClearLastResult(); + + unique_ptr< ByteBuffer > pKeyBuffer(GetSecureKeyN(pUserKey)); + + SysTryReturn(NID_IO, pKeyBuffer != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Failed to generate secure key."); + + pKey = const_cast< byte* >(pKeyBuffer->GetPointer()); + + pDbKey = new (std::nothrow) byte[DATABASE_KEY_LENGTH * SECURE_IO_2_BYTES + 1]; + SysTryReturn(NID_IO, pDbKey != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + memset(pDbKey, 0, DATABASE_KEY_LENGTH * SECURE_IO_2_BYTES + 1); + + for (int i = 0; i < DATABASE_KEY_LENGTH; i++) + { + lowByte = pKey[i] & SECURE_IO_HEX_0F; + highByte = (pKey[i] >> SECURE_IO_4_BITS) & SECURE_IO_HEX_0F; + if (lowByte <= SECURE_IO_9_BYTES) + { + pDbKey[i * SECURE_IO_2_BYTES + 1] = lowByte + '0'; + } + else + { + pDbKey[i * SECURE_IO_2_BYTES + 1] = lowByte - SECURE_IO_10_BYTES + 'A'; + } + + if (highByte <= SECURE_IO_9_BYTES) + { + pDbKey[i * SECURE_IO_2_BYTES] = highByte + '0'; + } + else + { + pDbKey[i * SECURE_IO_2_BYTES] = highByte - SECURE_IO_10_BYTES + 'A'; + } + } + + return pDbKey; +} + +bool +_SecureIoUtil::IsEmpty(const String& filePath) +{ + result r = E_SUCCESS; + FileAttributes attribute; + + SetLastResult(r); + r = File::GetAttributes(filePath, attribute); + if (IsFailed(r)) + { + SetLastResult(r); + return false; + } + + if (attribute.GetFileSize() == 0) + { + return true; + } + else + { + return false; + } +} + +} } //Tizen::Io diff --git a/src/io/FIo_SecureRegistry.cpp b/src/io/FIo_SecureRegistry.cpp new file mode 100644 index 0000000..321dc86 --- /dev/null +++ b/src/io/FIo_SecureRegistry.cpp @@ -0,0 +1,307 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_SecureRegistry.cpp + * @brief This is the implementation file for _SecureRegistry class. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +static const wchar_t* _CIPHER_INFORMATRION = L"CBC/128/PKCS7PADDING"; + +static result +_SaveLengthOfFile(void* pFileSecure) +{ + int length = 0; + byte legnthOfFile[SECURE_IO_LOF_SIZE] = {0, 0, 0, 0}; + _FileImpl* pFile = reinterpret_cast< _FileImpl* >(pFileSecure); + result r = pFile->Seek(FILESEEKPOSITION_END, 0); + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Seek file has failed.", GetErrorMessage(r)); + + length = pFile->Tell(); + SysTryReturn(NID_IO, length != -1, r = GetLastResult(), GetLastResult(), "[%s] Tell file has failed.", GetErrorMessage(GetLastResult())); + + r = pFile->Seek(FILESEEKPOSITION_BEGIN, SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_10_BYTES); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Seek file has failed.", GetErrorMessage(r)); + + if (sizeof(length) != SECURE_IO_LOF_SIZE) + { + memcpy(legnthOfFile + SECURE_IO_LOF_SIZE - sizeof(length), &length, sizeof(length)); + } + else + { + memcpy(legnthOfFile, &length, SECURE_IO_LOF_SIZE); + } + + r = pFile->Write(legnthOfFile, SECURE_IO_LOF_SIZE); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Write file has failed.", GetErrorMessage(r)); + + return r; +} + +_SecureRegistry::_SecureRegistry(void) + : __pSecretKey(null) +{ +} + +_SecureRegistry::~_SecureRegistry(void) +{ + if (_write == true && _FileImpl::IsFileExist(_regPath) == true) + { + this->Flush(); + } + + _sectionList.RemoveAll(true); + + delete __pSecretKey; + __pSecretKey = null; +} + +result +_SecureRegistry::Construct(const String& regPath, const char* pOpenMode, const ByteBuffer* pSecretKey) +{ + SysAssertf(_constructed == false, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class\n"); + SysTryReturnResult(NID_IO, !(pSecretKey != null && (pSecretKey->GetRemaining() <= 0)), E_INVALID_ARG, + "A key is not valid to encrypt or decrypt a registry file"); + + bool isValidOpenMode = this->VerifyRegistryOpenMode(pOpenMode); + SysTryReturnResult(NID_IO, isValidOpenMode == true, E_INVALID_ARG, "The specified openMode is invalid. (%s)", pOpenMode); + + int length = 0; + byte* pRegCont = null; + ByteBuffer registryContent; + unique_ptr< ByteBuffer > pDecryptedRegBuffer(null); + result r = Load(regPath, pOpenMode); + + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Registry file read is failed.", GetErrorMessage(r)); + + unique_ptr< ByteBuffer > pKey(_SecureIoUtil::GetSecureKeyN(pSecretKey)); + SysTryReturnResult(NID_IO, !(pKey != null && (pKey->GetRemaining() < ONE_BLOCK_SIZE)), E_INVALID_ARG, "Failed to get a key."); + + if (_pBuffer == null) + { + _constructed = true; + //Save registry file path and file open mode + _regPath.Clear(); + _regPath.Append(regPath); + __pSecretKey = pKey.release(); + return E_SUCCESS; + } + + r = _SecureIoUtil::CheckSecureRegistryHeader(&_pBuffer, &_length, regPath, true); + SysTryCatch(NID_IO, (!IsFailed(r)), , r, "[%s] Failed to check registry header.", GetErrorMessage(r)); + + length = _length; + pRegCont = _pBuffer; + + pRegCont = pRegCont + SECURE_REG_HEADER_SIZE_V1; + length -= SECURE_REG_HEADER_SIZE_V1; + + SysTryReturnResult(NID_IO, length > 0, E_SUCCESS, "Only header, no data to parse."); + + r = registryContent.Construct(length); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to construct byte buffer.", GetErrorMessage(r)); + + r = registryContent.SetArray((byte*) pRegCont, 0, length); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to set array elements.", GetErrorMessage(r)); + + registryContent.Flip(); + + pDecryptedRegBuffer = unique_ptr< ByteBuffer >(_SecureIoUtil::DoCipherAesN(_CIPHER_INFORMATRION, registryContent, *pKey.get(), Tizen::Security::Crypto::CIPHER_DECRYPT)); + SysTryCatch(NID_IO, pDecryptedRegBuffer != null, r = E_IO, E_IO, "[E_IO] Failed to decrypt registry data."); + + delete[] _pBuffer; + _pBuffer = null; + _length = 0; + + length = pDecryptedRegBuffer->GetRemaining(); + + _pBuffer = new (std::nothrow) byte[length + 1]; + SysTryCatch(NID_IO, _pBuffer, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pDecryptedRegBuffer->GetArray(_pBuffer, 0, length); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to get array elements.", GetErrorMessage(r)); + + _pBuffer[length] = 0; + _length = length; + + r = Parse(); + SysTryCatch(NID_IO, !IsFailed(r), , r, "[%s] Failed to parse registry.", GetErrorMessage(r)); + + _constructed = true; + //Save registry file path and file open mode + _regPath.Clear(); + _regPath.Append(regPath); + + __pSecretKey = pKey.release(); + + return r; + +CATCH: + + if (IsFailed(r)) + { + delete[] _pBuffer; + _pBuffer = null; + + _length = 0; + } + + return r; +} + +result +_SecureRegistry::Flush(void) +{ + SysAssertf(_constructed == true, "Not yet constructed. Construct() should be called before use.\n"); + SysAssertf(!(__pSecretKey == null || (__pSecretKey != null && __pSecretKey->GetRemaining() < ONE_BLOCK_SIZE)), + "_SecureRegistry is not constructed."); + + int dataSize = 0; + int length = 0; + byte nameIndex = 0; + byte regHeader[SECURE_REG_HEADER_SIZE_V1]; + byte reservedValue[SECURE_IO_STATIC_BIN_LEN] = {0xCA, 0xFE, 0xBE, 0xBE, 0xDA, 0xEF, 0xEB, 0xEB}; + ByteBuffer regBuffer; + String replicaFileName; + String fileOpenMode(L"w+"); + bool fileExists = false; + result r = PrepareToWrite(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Registry data make is failed.", GetErrorMessage(r)); + + SysTryReturnResult(NID_IO, (_pBuffer && _length > 0), E_SUCCESS, "Buffer length 0, Nothing to write, so success!"); + + fileExists = _FileImpl::IsFileExist(_regPath); + + replicaFileName = _SecureIoUtil::MakeRegistryReplica(_regPath, &nameIndex); + SysTryReturn(NID_IO, GetLastResult() == E_SUCCESS, GetLastResult(), GetLastResult(), "[%s] Failed to make registry replica.", GetErrorMessage(GetLastResult())); + + unique_ptr< _FileImpl > pFileImpl(new (std::nothrow) _FileImpl()); + SysTryReturnResult(NID_IO, pFileImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pFileImpl->Construct(_regPath, fileOpenMode, false, null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Constructing the file has failed.", GetErrorMessage(r)); + + if (fileExists && _SecureIoUtil::IsEmpty(_regPath) == false) + { + r = _SecureIoUtil::SetRegistryFlag(pFileImpl.get(), FLAG_STATE_CTF); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set flags in registry header.", GetErrorMessage(r)); + + r = pFileImpl->Truncate(SECURE_REG_HEADER_SIZE_V1); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to trucate registry file.", GetErrorMessage(r)); + } + + length = _length; + + r = regBuffer.Construct(length); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = regBuffer.SetArray((byte*) _pBuffer, 0, length); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + regBuffer.Flip(); + + unique_ptr< ByteBuffer > pEncryptedData(_SecureIoUtil::DoCipherAesN(_CIPHER_INFORMATRION, regBuffer, *__pSecretKey, Tizen::Security::Crypto::CIPHER_ENCRYPT)); + SysTryReturn(NID_IO, pEncryptedData != null, E_IO, E_IO, "[E_IO] Failed to encrypt data."); + + r = pFileImpl->Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Seek file has failed.", GetErrorMessage(r)); + + memcpy(regHeader, SECURE_REG_HEADER_STRING, SECURE_REG_HEADER_STRING_SIZE); + memcpy(regHeader + SECURE_REG_HEADER_STRING_SIZE, reservedValue, SECURE_IO_STATIC_BIN_LEN); + regHeader[SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN] = 1; + regHeader[SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN + 1] = nameIndex; + memset(regHeader + SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN + SECURE_IO_2_BYTES, 0, SECURE_IO_LOF_SIZE); + memset(regHeader + SECURE_REG_HEADER_STRING_SIZE + SECURE_IO_STATIC_BIN_LEN + SECURE_IO_2_BYTES + SECURE_IO_LOF_SIZE, 0, SECURE_IO_LOF_SIZE); + + r = pFileImpl->Write(regHeader, SECURE_REG_HEADER_SIZE_V1); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write secure header to registry file!", GetErrorMessage(r)); + + r = pFileImpl->Write(*pEncryptedData); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to write secure header to registry file!", GetErrorMessage(r)); + + r = pFileImpl->Flush(); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to flush the registry.", GetErrorMessage(r)); + + pFileImpl.reset(null); + + //reopen file to update LOF and replica flag. + pFileImpl = unique_ptr< _FileImpl >(new (std::nothrow) _FileImpl()); + SysTryReturnResult(NID_IO, pFileImpl != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = pFileImpl->Construct(_regPath, L"r+", false, null); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Constructing the file has failed.", GetErrorMessage(r)); + + r = _SecureIoUtil::SetRegistryFlag(pFileImpl.get(), FLAG_STATE_CVF_CTF); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set flags to registry header.", GetErrorMessage(r)); + + r = _SaveLengthOfFile(pFileImpl.get()); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set length to registry header.", GetErrorMessage(r)); + + r = pFileImpl->Seek(FILESEEKPOSITION_BEGIN, 0); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Seek file has failed.", GetErrorMessage(r)); + + memset(regHeader, 0, sizeof(regHeader)); + dataSize = pFileImpl->Read(regHeader, SECURE_REG_HEADER_SIZE_V1); + + if (dataSize < SECURE_REG_HEADER_SIZE_V1) + { + r = GetLastResult(); + SysLog(NID_IO, "[%s]Failed to read secure header", GetErrorMessage(r)); + return r; + } + + if (_FileImpl::IsFileExist(replicaFileName)) + { + r = _FileImpl::Remove(replicaFileName); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s]Failed to delete replica file.", GetErrorMessage(r)); + } + + r = _SecureIoUtil::DeleteRegistryReplica(regHeader, _regPath); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to delete replica file.", GetErrorMessage(r)); + + r = _SecureIoUtil::SetRegistryFlag(pFileImpl.get(), FLAG_STATE_CVF); + SysTryReturn(NID_IO, !IsFailed(r), r, r, "[%s] Failed to set flags in registry file.", GetErrorMessage(r)); + + return r; +} + +}} // Tizen::Io diff --git a/src/io/FIo_SerialPortImpl.cpp b/src/io/FIo_SerialPortImpl.cpp new file mode 100644 index 0000000..5fb4d57 --- /dev/null +++ b/src/io/FIo_SerialPortImpl.cpp @@ -0,0 +1,184 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://floralicense.org/license/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_SerialPortImpl.cpp + * @brief This is the implementation file for _SerialPortImpl class. + */ +#include +#include + +#include +#include + +#include +#include +#include "FIo_SerialPortImpl.h" + +using namespace std; +using namespace Tizen::App; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +const String COMMUNICATION_DISPATCHER_IPC_ID = L"osp.app.ipcserver.communicationdispatcher"; +const String ACCESSORY_MANAGER_SERVICE_ID = L"osp.accessorymanager.service"; + +const String SERIAL_COMMAND_OPEN = L"Open"; +const String SERIAL_COMMAND_CLOSE = L"Close"; +const String SERIAL_COMMAND_WRITE = L"Write"; +const String SERIAL_COMMAND_DATA = L"Data"; +const String SERIAL_COMMAND_ERROR = L"Error"; + +const int SERIAL_BUFFER_SIZE = 536870912; //512KB +const int SERIAL_DATA_HEAD = 1; +const int SERIAL_DATA_BODY = 2; + +_SerialPortImpl::_SerialPortImpl(ISerialPortEventListener& listener) + : __pIpcClient(null) + , __pEventListener(null) +{ + result r = E_SUCCESS; + ArrayList request; + ArrayList response; + + __pIpcClient = new (std::nothrow) _IpcClient(); + SysTryReturnVoidResult(NID_IO, __pIpcClient != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + r = __pIpcClient->Construct(COMMUNICATION_DISPATCHER_IPC_ID, this); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + __pEventListener = &listener; + + r = request.Construct(); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + r = request.Add(ACCESSORY_MANAGER_SERVICE_ID); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + r = request.Add(SERIAL_COMMAND_OPEN); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + r = response.Construct(); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + + unique_ptr pMsg(new (std::nothrow) IoService_Request(request, &response)); + SysTryReturnVoidResult(NID_IO, pMsg != NULL, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); +} + +_SerialPortImpl::~_SerialPortImpl(void) +{ + result r = E_SUCCESS; + ArrayList request; + ArrayList response; + + SysTryReturnVoidResult(NID_IO, __pIpcClient != null, E_SYSTEM, "[E_SYSTEM] IPC client is not ready."); + + r = request.Construct(); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + r = request.Add(ACCESSORY_MANAGER_SERVICE_ID); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + r = request.Add(SERIAL_COMMAND_CLOSE); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + r = response.Construct(); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + + unique_ptr pMsg(new (std::nothrow) IoService_Request(request, &response)); + SysTryReturnVoidResult(NID_IO, pMsg != NULL, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + SysTryReturnVoidResult(NID_IO, r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); +} + +result +_SerialPortImpl::Write(const Tizen::Base::ByteBuffer &byteBuffer) +{ + result r = E_SUCCESS; + ByteBuffer* pByteBuffer = null; + ArrayList request; + ArrayList response; + + SysTryReturnResult(NID_IO, byteBuffer.GetCapacity() < SERIAL_BUFFER_SIZE, E_MAX_EXCEEDED, "[E_MAX_EXCEEDED] The buffer size exceeded a limit of the current device."); + + pByteBuffer = const_cast (&byteBuffer); + + SysTryReturnResult(NID_IO, __pIpcClient != null, E_SYSTEM, "[E_SYSTEM] IPC client is not ready"); + + r = request.Construct(); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Propagated.", GetErrorMessage(r)); + r = request.Add(ACCESSORY_MANAGER_SERVICE_ID); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Propagated.", GetErrorMessage(r)); + r = request.Add(SERIAL_COMMAND_WRITE); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Propagated.", GetErrorMessage(r)); + r = request.Add(*pByteBuffer); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Propagated.", GetErrorMessage(r)); + r = response.Construct(); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Propagated.", GetErrorMessage(r)); + + unique_ptr pMsg(new (std::nothrow) IoService_Request(request, &response)); + SysTryReturnResult(NID_IO, pMsg != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->SendRequest(pMsg.get()); + SysTryReturn(NID_IO, r == E_SUCCESS, r, r, "[%s] Propagated.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +int +_SerialPortImpl::GetWriteBufferSize(void) const +{ + return SERIAL_BUFFER_SIZE; +} + +void +_SerialPortImpl::OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message) +{ + IPC_BEGIN_MESSAGE_MAP(_SerialPortImpl, message) + IPC_MESSAGE_HANDLER_EX(IoService_Data, &client, OnDataReceived) + IPC_END_MESSAGE_MAP_EX() +} + +void +_SerialPortImpl::OnDataReceived(const ArrayList& data) +{ + ByteBuffer* pBuffer = null; + + unique_ptr pCommand((String*)data.GetAt(SERIAL_DATA_HEAD)); + SysTryReturnVoidResult(NID_APP, pCommand != null, E_SYSTEM, "[E_SYSTEM] There is no command"); + + if (pCommand->Equals(SERIAL_COMMAND_DATA, true)) + { + if (__pEventListener != null) + { + pBuffer = (ByteBuffer*)data.GetAt(SERIAL_DATA_BODY); + __pEventListener->OnSerialPortDataReceivedN(*pBuffer); + } + } + else if (pCommand->Equals(SERIAL_COMMAND_ERROR, true)) + { + if (__pEventListener != null) + { + __pEventListener->OnSerialPortErrorOccured(E_SYSTEM); + } + } +} +}} // Tizen::Io + diff --git a/src/io/FIo_SerialPortImpl.h b/src/io/FIo_SerialPortImpl.h new file mode 100644 index 0000000..5badd89 --- /dev/null +++ b/src/io/FIo_SerialPortImpl.h @@ -0,0 +1,63 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://floralicense.org/license/ +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_SerialPortImpl.h + * @brief This is the header file for the %_SerialPortImpl class. + * + * This header file contains the declarations of the %_SerialPortImpl class. + */ + +#ifndef _FIO_INTERNAL_SERIALPORT_IMPL_H_ +#define _FIO_INTERNAL_SERIALPORT_IMPL_H_ + +#include +#include +#include + +namespace Tizen { namespace Base { namespace Collection { +class ArrayList; +}}} + +namespace Tizen { namespace Io +{ + +class _SerialPortImpl + : public _IIpcClientEventListener +{ +public: + _SerialPortImpl(ISerialPortEventListener& listener); + + virtual ~_SerialPortImpl(void); + + result Write(const Tizen::Base::ByteBuffer &byteBuffer); + int GetWriteBufferSize(void) const; + void OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message); + void OnDataReceived(const Tizen::Base::Collection::ArrayList& data); + +private: + _IpcClient* __pIpcClient; + ISerialPortEventListener* __pEventListener; + + _SerialPortImpl(_SerialPortImpl& serialPortImpl); + + _SerialPortImpl& operator =(const _SerialPortImpl& serialPortImpl); +}; + +}} //Tizen::Io + +#endif // _FIO_INTERNAL_SERIALPORT_IMPL_H_ diff --git a/src/io/FIo_ServerChannelImpl.cpp b/src/io/FIo_ServerChannelImpl.cpp new file mode 100644 index 0000000..cb2547d --- /dev/null +++ b/src/io/FIo_ServerChannelImpl.cpp @@ -0,0 +1,203 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ServerChannelImpl.cpp + * @brief This is the implementation file for the _ServerChannelImpl class. + * + */ + +#include + +#include +#include +#include +#include +#include +#include "FIo_ServerChannelImpl.h" +#include "FIo_Channel.h" +#include "FIo_ChannelManager.h" + +using namespace std; +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Io +{ + +_ServerChannelImpl::_ServerChannelImpl(void) + : __pServerChannel(null) + , __pRequestListener(null) + , __pChannel(null) +{ +} + +_ServerChannelImpl::~_ServerChannelImpl(void) +{ +} + +result +_ServerChannelImpl::Construct(ServerChannel* pServerChannel, const Tizen::Base::String& channelName) +{ + const String& appId = _AppInfo::GetAppId(); + const String& appExecutableName = _AppInfo::GetAppExecutableName(); + + String channelId(appId); + channelId.Append(L'.'); + channelId.Append(appExecutableName); + + if (!channelName.IsEmpty()) + { + channelId.Append(L'.'); + channelId.Append(channelName); + } + + // Create a channel + _ChannelManager* pManager = _ChannelManager::GetInstance(); + SysTryReturnResult(NID_IO, pManager != null, E_SYSTEM, "Failed to create a channel manager"); + + _Channel* pChannel = pManager->GetChannel(channelId); + SysTryReturnResult(NID_IO, pChannel != null, E_SYSTEM, "Failed to create a channel: [%ls]", channelId.GetPointer()); + + pChannel->SetChannelRequestEventListener(*this); + + __pServerChannel = pServerChannel; + __pChannel = pChannel; + + return E_SUCCESS; +} + +void +_ServerChannelImpl::SetChannelRequestEventListener(IChannelRequestEventListener* pRequestListener) +{ + __pRequestListener = (IChannelRequestEventListener*) pRequestListener; +} + +result +_ServerChannelImpl::SendResponse(const String& clientChannelId, const IList* pArgs, RequestId reqId) +{ + const int APP_ID_LEN = 10; + + String channelId = clientChannelId; + String execName; + + if (clientChannelId.GetLength() <= APP_ID_LEN) + { + execName = _PackageManagerImpl::GetInstance()->GetDefaultAppExecutableName(clientChannelId); + channelId.Append(L'.'); + channelId.Append(execName); + } + + if (pArgs == null) + { + return __pChannel->SendNullResponse(channelId, reqId); + } + + const ArrayList* pList = dynamic_cast(pArgs); + if (pList == null) + { + unique_ptr pArrayList(new (std::nothrow) ArrayList()); + pArrayList->Construct(*pArgs); + + return __pChannel->SendResponse(channelId, *pArrayList, reqId); + } + + return __pChannel->SendResponse(channelId, *pList, reqId); +} + +void +_ServerChannelImpl::OnChannelRequestReceivedN(RequestId reqId, const String& channelId, IList* pArgs) +{ + SysLog(NID_IO, "Received from [%ls]", channelId.GetPointer()); + + if (__pRequestListener != null) + { + if (_AppInfo::IsOspCompat() == false) + { + __pRequestListener->OnChannelRequestReceivedN(reqId, *__pServerChannel, channelId, pArgs); + } + else + { + String appId; + channelId.SubString(0, 10, appId); + + __pRequestListener->OnChannelRequestReceivedN(reqId, *__pServerChannel, appId, pArgs); + } + } + else + { + pArgs->RemoveAll(true); + delete pArgs; + } +} + + +_ServerChannelImpl* + _ServerChannelImpl::GetInstance(ServerChannel* pChannel) +{ + + result r = E_SUCCESS; + static _ServerChannelImpl* pImpl = null; + if (pImpl == null) + { + unique_ptr<_ServerChannelImpl> p(new (std::nothrow) _ServerChannelImpl); + SysTryReturn(NID_IO, p != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = p->Construct(pChannel); + SysTryReturn(NID_IO, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] Failed to initialize channel."); + + pImpl = p.release(); + } + + return pImpl; +} + +ServerChannel* +_ServerChannelImpl::GetServerChannel(const Tizen::Base::String& channelName) +{ + _ChannelManager* pManager = _ChannelManager::GetInstance(); + SysTryReturn(NID_IO, pManager != null, null, E_SYSTEM, "[E_SYSTEM] Failed to create a _ChannelManager."); + + ServerChannel* pChannel = pManager->GetServerChannel(channelName); + if (pChannel == null) + { + // unique_ptr cannot be used because Dtor is private + pChannel = new (std::nothrow) ServerChannel; + SysTryReturn(NID_IO, pChannel != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + unique_ptr<_ServerChannelImpl> pImpl(new (std::nothrow) _ServerChannelImpl); + SysTryCatch(NID_IO, pImpl != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + result r = pImpl->Construct(pChannel, channelName); + SysTryCatch(NID_IO, r == E_SUCCESS, , E_SYSTEM, "[E_SYSTEM] Failed to initialize channel."); + + pChannel->__pServerChannelImpl = pImpl.release(); + + pManager->AddServerChannel(channelName, pChannel); + } + + return pChannel; + +CATCH: + delete pChannel; + + return null; +} + +} } // Tizen::Io diff --git a/src/io/FIo_ServiceMessage.cpp b/src/io/FIo_ServiceMessage.cpp new file mode 100644 index 0000000..56374ac --- /dev/null +++ b/src/io/FIo_ServiceMessage.cpp @@ -0,0 +1,25 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ServiceMessage.cpp + * @brief This is the implementation file for the ServiceMessage class. + * + */ + +#define IPC_MESSAGE_IMPL +#include "FIo_AppServiceIpcMessages.h" diff --git a/src/io/inc/FIoIChannelEventListener.h b/src/io/inc/FIoIChannelEventListener.h new file mode 100644 index 0000000..593dddc --- /dev/null +++ b/src/io/inc/FIoIChannelEventListener.h @@ -0,0 +1,115 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIoIChannelEventListener.h + * @brief This is the header file for the %IChannelEventListener interface. + * + * This header file contains the declarations of the %IChannelEventListener interface. @n + * If the channel event is generated, a method of this interface will be called. + * So, if the application performs jobs related to the channel event, use methods that belong to this class. + * + */ +#ifndef _FIO_ICHANNEL_EVENT_LISTENER_H_ +#define _FIO_ICHANNEL_EVENT_LISTENER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +/** +* @interface IChannelEventListener +* @brief This interface provides event handlers for the channel creation and deletion. +* +* @since 2.0 +* +* The %IChannelEventListener interface provides event handlers for receiving the channel events. +* +*/ +class IChannelEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~IChannelEventListener(void) {} + + /** + * Called when an application creates the channel. + * + * @since 2.0 + * + * @param[in] appId The application ID that creates the channel + * @param[in] type The type of the channel + * + */ + virtual void OnChannelCreated(const Tizen::App::AppId& appId, ChannelType type){} + + /** + * Called when an application deletes the channel. + * + * @since 2.0 + * + * @param[in] appId The application ID that deletes the channel + * @param[in] type The type of the channel + * + */ + virtual void OnChannelDeleted(const Tizen::App::AppId& appId, ChannelType type){} + + +protected: + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IChannelEventListener_Reserved1(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IChannelEventListener_Reserved2(void) {} + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // This method is reserved and may change its name at any time without prior notice. + // + // @since 2.0 + // + virtual void IChannelEventListener_Reserved3(void) {} +}; + +} } // Tizen::Io + +#endif // _FIO_ICHANNEL_EVENT_LISTENER_H_ + diff --git a/src/io/inc/FIo_AppServiceIpcMessages.h b/src/io/inc/FIo_AppServiceIpcMessages.h new file mode 100644 index 0000000..bbaf626 --- /dev/null +++ b/src/io/inc/FIo_AppServiceIpcMessages.h @@ -0,0 +1,32 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FApp_AppManagerIpcMessage.h + * @brief This is the header file for the AppManagerService Ipc message types. + */ + +#include "ipc/ipc_message_macros.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FIo_IpcMessageStart.h" + +//Start +#define IPC_MESSAGE_START IoServiceStart + +IPC_MESSAGE_CONTROL1(IoService_Data, Tizen::Base::Collection::ArrayList); +IPC_SYNC_MESSAGE_CONTROL1_1(IoService_Request, Tizen::Base::Collection::ArrayList, Tizen::Base::Collection::ArrayList); + diff --git a/src/io/inc/FIo_Channel.h b/src/io/inc/FIo_Channel.h new file mode 100644 index 0000000..036ac84 --- /dev/null +++ b/src/io/inc/FIo_Channel.h @@ -0,0 +1,90 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_Channel.h + * @brief This is the header file for the _Channel class. + * + * This file contains the declarations of _Channel. + */ + + +#ifndef _FIO_INTERNAL_CHANNEL_H_ +#define _FIO_INTERNAL_CHANNEL_H_ + +#include +#include +#include +#include +#include "FIo_IChannelServiceEventListener.h" + +namespace Tizen { namespace Io +{ + +class _ClientChannel; +class _ServerChannel; +class _IChannelService; +class _IChannelRequestEventListener; +class _IChannelResponseEventListener; + +/** +* @class _Channel +* @brief This class provides methods to send a request or response to other application. +* @since 2.1 +* +*/ +class _Channel + : public Tizen::Base::Object + , public Tizen::Io::_IChannelServiceEventListener +{ +public: + + _Channel(void); + + virtual ~_Channel(void); + + result Construct(const Tizen::Base::String& channelId, _IChannelService& channelService); + + result SendRequest(const Tizen::Base::String& channelId, const Tizen::Base::Collection::ArrayList& args, RequestId& reqId); + + result SendNullRequest(const Tizen::Base::String& channelId, RequestId& reqId); + + result SendResponse(const Tizen::Base::String& channelId, const Tizen::Base::Collection::ArrayList& args, RequestId reqId); + + result SendNullResponse(const Tizen::Base::String& channelId, RequestId reqId); + + virtual bool OnChannelRequestReceivedN(const Tizen::Base::String& src, const Tizen::Base::String& dest, int requestId, Tizen::Base::Collection::ArrayList* pArgs); + + virtual bool OnChannelResponseReceivedN(const Tizen::Base::String& src, const Tizen::Base::String& dest, int requestId, Tizen::Base::Collection::ArrayList* pArgs); + + void SetChannelRequestEventListener(const _IChannelRequestEventListener& listener); + + void SetChannelResponseEventListener(const _IChannelResponseEventListener& listener); + +private: + int GetRequestId(void); + + Tizen::Base::String __channelId; + _IChannelService* __pIChannelService; + _IChannelResponseEventListener* __pResponseEventListener; + _IChannelRequestEventListener* __pRequestEventListener; +}; // _Channel + + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_ diff --git a/src/io/inc/FIo_ChannelCAppStub.h b/src/io/inc/FIo_ChannelCAppStub.h new file mode 100644 index 0000000..585c6ed --- /dev/null +++ b/src/io/inc/FIo_ChannelCAppStub.h @@ -0,0 +1,128 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelCAppStub.h + * @brief This is the header file for the _ChannelCAppStub class. + * + * This file contains the declarations of _ChannelCAppStub. + */ + +#ifndef _FIO_INTERNAL_CHANNEL_CAPP_STUB_H_ +#define _FIO_INTERNAL_CHANNEL_CAPP_STUB_H_ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ +class _EventDispatcher; +}}} + +namespace Tizen { namespace Io +{ + +class _IIpcServerEventListener; +class _ChannelServiceStub; + +/** + * @class _ChannelCAppStub + * @brief This class provides methods to handle c-application request messages. + * @since 2.1 + * + */ +class _OSP_EXPORT_ _ChannelCAppStub + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * @since 2.1 + */ + _ChannelCAppStub(void); + + /** + * This is the destructor for this class. + * @since 2.1 + */ + virtual ~_ChannelCAppStub(void); + + result Construct(void); + + void SetChannelService(_ChannelService& service); + + static bool SendResponse(int requestId, void* pGIOChannel, const Tizen::Base::Collection::ArrayList& args); + +private: + _ChannelCAppStub(const _ChannelCAppStub& rhs); + + _ChannelCAppStub& operator =(const _ChannelCAppStub& rhs); + + static gboolean OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data); + + static gboolean OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data); + + gboolean HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data); + + _ChannelService* __pChannelService; + + struct _ClientInfo; + + struct _ChannelInfo + { + _ChannelInfo(void); + ~_ChannelInfo(void); + + struct _ClientInfo* pClientInfo; + GIOChannel* pGIOChannel; + GSource* pGSource; + bool destroySource; + }; + + struct _ClientInfo + { + _ClientInfo(void); + ~_ClientInfo(void); + + int clientId; /**< the client id */ + _ChannelCAppStub* pChannelStub; /**< the pointer to an _ChannelCAppStub */ + std::vector channels; /**< the set of channels associated with a client */ + Tizen::Base::String appId; + //Tizen::Base::String appExecutableName; + }; + + GMainContext* __pGMainContext; + + GSource* __pConnectGSource; + + std::map __clients; // pid of client is used for key + +}; // _ChannelCAppStub + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_CAPP_STUB_H_ + diff --git a/src/io/inc/FIo_ChannelManager.h b/src/io/inc/FIo_ChannelManager.h new file mode 100644 index 0000000..fdf8155 --- /dev/null +++ b/src/io/inc/FIo_ChannelManager.h @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelManager.h + * @brief This is the header file for the _ChannelManager class. + * + * This file contains the declarations of _ChannelManager. + */ + +#ifndef _FIO_INTERNAL_CHANNEL_MANAGER_H_ +#define _FIO_INTERNAL_CHANNEL_MANAGER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class _Channel; +class _IChannelService; +class ClientChannel; +class ServerChannel; + +/** + * @class _ChannelManager + * @brief This class provides methods for managing _Channels + * @since 2.1 + */ + +class _ChannelManager +{ +public: + static _ChannelManager* GetInstance(void); + + _Channel* GetChannel(const Tizen::Base::String& channelId); + + ClientChannel* GetClientChannel(const Tizen::Base::String& channelName); + + ServerChannel* GetServerChannel(const Tizen::Base::String& channelName); + + void AddClientChannel(const Tizen::Base::String& channelName, ClientChannel* pChannel); + + void AddServerChannel(const Tizen::Base::String& channelName, ServerChannel* pChannel); + +private: + _ChannelManager(void); + + ~_ChannelManager(void); + + result Construct(void); + + _ChannelManager(const _ChannelManager& value); + + _ChannelManager& operator =(const _ChannelManager& value); + + class _StringHashProvider + : public Tizen::Base::Collection::IHashCodeProviderT + { + public: + virtual int GetHashCode(const Tizen::Base::String& value) const + { + return value.GetHashCode(); + } + }; + + class _StringComparer + : public Tizen::Base::Collection::IComparerT + { + public: + virtual result Compare(const Tizen::Base::String& string1, const Tizen::Base::String& string2, int& cmp) const + { + cmp = string1.CompareTo(string2); + return E_SUCCESS; + } + }; + + static void InitSingleton(void); + + static void DestroySingleton(void); + +private: + Tizen::Base::Collection::HashMapT __channels; + Tizen::Base::Collection::HashMapT __clientChannels; + Tizen::Base::Collection::HashMapT __serverChannels; + _IChannelService* __pIChannelService; + static _ChannelManager* __pChannelManagerInst; +}; // _ChannelManager + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_MANAGER_H_ diff --git a/src/io/inc/FIo_ChannelMessages.h b/src/io/inc/FIo_ChannelMessages.h new file mode 100644 index 0000000..0e31db0 --- /dev/null +++ b/src/io/inc/FIo_ChannelMessages.h @@ -0,0 +1,38 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelMessages.h + * @brief This is the header file for the channel message types. + */ + +#include "ipc/ipc_message_macros.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FIo_IpcMessageStart.h" + +#define IPC_MESSAGE_START ChannelServiceMsgStart + +IPC_SYNC_MESSAGE_CONTROL1_1(ChannelServiceMsg_register, Tizen::Base::String, int) +IPC_SYNC_MESSAGE_CONTROL4_1(ChannelServiceMsg_sendRequest, Tizen::Base::String, Tizen::Base::String, Tizen::Base::Collection::ArrayList, int, int) +IPC_SYNC_MESSAGE_CONTROL3_1(ChannelServiceMsg_sendNullRequest, Tizen::Base::String, Tizen::Base::String, int, int) +IPC_SYNC_MESSAGE_CONTROL4_1(ChannelServiceMsg_sendResponse, Tizen::Base::String, Tizen::Base::String, Tizen::Base::Collection::ArrayList, int, int) +IPC_SYNC_MESSAGE_CONTROL3_1(ChannelServiceMsg_sendNullResponse, Tizen::Base::String, Tizen::Base::String, int, int) +IPC_MESSAGE_CONTROL4(ChannelServiceMsg_sendRequestAsync, Tizen::Base::String, Tizen::Base::String, Tizen::Base::Collection::ArrayList, int) +IPC_MESSAGE_CONTROL3(ChannelServiceMsg_sendNullRequestAsync, Tizen::Base::String, Tizen::Base::String, int) +IPC_MESSAGE_CONTROL4(ChannelServiceMsg_sendResponseAsync, Tizen::Base::String, Tizen::Base::String, Tizen::Base::Collection::ArrayList, int) +IPC_MESSAGE_CONTROL3(ChannelServiceMsg_sendNullResponseAsync, Tizen::Base::String, Tizen::Base::String, int) +IPC_MESSAGE_CONTROL3(ChannelServiceMsg_sendChannelEvent, Tizen::Base::String, int, int) diff --git a/src/io/inc/FIo_ChannelService.h b/src/io/inc/FIo_ChannelService.h new file mode 100644 index 0000000..d04cf30 --- /dev/null +++ b/src/io/inc/FIo_ChannelService.h @@ -0,0 +1,124 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelService.h + * @brief This is the header file for the _ChannelService class. + * + * This file contains the declarations of _ChannelService. + */ + +#ifndef _FIO_INTERNAL_CHANNEL_SERVICE_H_ +#define _FIO_INTERNAL_CHANNEL_SERVICE_H_ + +#include + +#include +#include +#include +#include +#include +#include "FIo_IChannelService.h" +#include "FIo_IChannelServiceEventListener.h" + +namespace IPC +{ +class Message; +} + +namespace Tizen { namespace Io +{ +class _IChannelServiceStub; +class _ChannelCAppStub; + +enum _ChannelType +{ + OSPAPP_CHANNEL = 0, + CAPP_CHANNEL, + WEBAPP_CHANNEL +}; + +class _OSP_EXPORT_ _ChannelService + : public Tizen::Base::Object + , public Tizen::Io::_IChannelService +{ +public: + _ChannelService(void); + + virtual ~_ChannelService(void); + + virtual result Construct(_IChannelServiceStub& stub); + + // _IChannelService + virtual result RegisterChannel(const Tizen::Base::String& channelId, const _IChannelServiceEventListener& listener); + virtual result UnregisterChannel(const Tizen::Base::String& channelId); + + virtual result SendRequest(const Tizen::Base::String& src, const Tizen::Base::String& dest, const Tizen::Base::Collection::ArrayList& args, int messageId); + virtual result SendNullRequest(const Tizen::Base::String& src, const Tizen::Base::String& dest, int messageId); + + virtual result SendResponse(const Tizen::Base::String& src, const Tizen::Base::String& dest, const Tizen::Base::Collection::ArrayList& args, int messageId); + virtual result SendNullResponse(const Tizen::Base::String& src, const Tizen::Base::String& dest, int messageId); + + + bool IsChannelRegistered(const Tizen::Base::String& channelId); + + result RegisterChannel(const Tizen::Base::String& channelId, int clientId, unsigned int type = OSPAPP_CHANNEL); + + result RegisterChannel(const Tizen::Base::String& channelId, int clientId, void* pGIOChannel); + + result UnregisterChannel(int clientId); + +private: + + struct _ChannelInfo + { + Tizen::Base::String channelId; + int clientId; + void* pGIOChannel; + unsigned int type; + }; + + class _StringHashProvider + : public Tizen::Base::Collection::IHashCodeProviderT + { + public: + virtual int GetHashCode(const Tizen::Base::String& value) const + { + return value.GetHashCode(); + } + }; + + class _StringComparer + : public Tizen::Base::Collection::IComparerT + { + public: + virtual result Compare(const Tizen::Base::String& string1, const Tizen::Base::String& string2, int& cmp) const + { + cmp = string1.CompareTo(string2); + return E_SUCCESS; + } + }; +private: + _IChannelServiceStub* __pIChannelServiceStub; + Tizen::Base::Collection::HashMapT __channels; + +}; // _ChannelService + + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_SERVICE_STUB_H_ diff --git a/src/io/inc/FIo_ChannelServiceManager.h b/src/io/inc/FIo_ChannelServiceManager.h new file mode 100644 index 0000000..8ad3f4a --- /dev/null +++ b/src/io/inc/FIo_ChannelServiceManager.h @@ -0,0 +1,62 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelServiceManager.h + * @brief This is the header file for the _ChannelServiceManager class. + * + * This file contains the declarations of _ChannelServiceManager. + */ + +#ifndef _FIO_INTERNAL_CHANNEL_SERVICE_MANAGER_H_ +#define _FIO_INTERNAL_CHANNEL_SERVICE_MANAGER_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +class _IChannelService; + +class _OSP_EXPORT_ _ChannelServiceManager + : public Tizen::Base::Object +{ +public: + static _ChannelServiceManager* GetInstance(); + + _IChannelService* GetChannelService(void); + + void SetChannelService(_IChannelService* pIChannelService); + +private: + _ChannelServiceManager(void); + + virtual ~_ChannelServiceManager(void); + + _ChannelServiceManager(const _ChannelServiceManager& value); + + _ChannelServiceManager& operator =(const _ChannelServiceManager& value); + +private: + static _ChannelServiceManager* __pChannnelServiceManager; + _IChannelService* __pIChannelService; +}; // Channel + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_SERVICE_MANAGER_H_ diff --git a/src/io/inc/FIo_ChannelServiceProxy.h b/src/io/inc/FIo_ChannelServiceProxy.h new file mode 100644 index 0000000..92002eb --- /dev/null +++ b/src/io/inc/FIo_ChannelServiceProxy.h @@ -0,0 +1,107 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelServiceProxy.h + * @brief This is the header file for the _ChannelServiceProxy class. + * + * This file contains the declarations of _ChannelServiceProxy. + */ + + +#ifndef _FIO_INTERNAL_CHANNEL_SERVICE_PROXY_H_ +#define _FIO_INTERNAL_CHANNEL_SERVICE_PROXY_H_ + +#include +#include +#include +#include +#include "FIo_IChannelService.h" +#include "FIo_IChannelServiceEventListener.h" +#include "FIo_IIpcClientEventListener.h" + +namespace IPC { class Message; } + +namespace Tizen { namespace Io +{ + +class _IpcClient; + +class _ChannelServiceProxy + : public Tizen::Base::Object + , public _IChannelService + , public _IIpcClientEventListener +{ +public: + _ChannelServiceProxy(void); + + virtual ~_ChannelServiceProxy(void); + + virtual result Construct(void); + + virtual void OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message); + + // _IChannelService + virtual result RegisterChannel(const Tizen::Base::String& channelId, const _IChannelServiceEventListener& listener); + virtual result UnregisterChannel(const Tizen::Base::String& channelId); + + virtual result SendRequest(const Tizen::Base::String& src, const Tizen::Base::String& dest, const Tizen::Base::Collection::ArrayList& args, int messageId); + virtual result SendNullRequest(const Tizen::Base::String& src, const Tizen::Base::String& dest, int messageId); + + virtual result SendResponse(const Tizen::Base::String& src, const Tizen::Base::String& dest, const Tizen::Base::Collection::ArrayList& args, int messageId); + virtual result SendNullResponse(const Tizen::Base::String& src, const Tizen::Base::String& dest, int messageId); + + +private: + bool OnSendRequestMessage(const Tizen::Base::String& src, const Tizen::Base::String& dest, const Tizen::Base::Collection::ArrayList& args, int requestId); + bool OnSendNullRequestMessage(const Tizen::Base::String& src, const Tizen::Base::String& dest, int requestId); + + bool OnSendResponseMessage(const Tizen::Base::String& src, const Tizen::Base::String& dest, const Tizen::Base::Collection::ArrayList& args, int requestId); + bool OnSendNullResponseMessage(const Tizen::Base::String& src, const Tizen::Base::String& dest, int requestId); + + +private: + class _StringHashProvider + : public Tizen::Base::Collection::IHashCodeProviderT + { + public: + virtual int GetHashCode(const Tizen::Base::String& value) const + { + return value.GetHashCode(); + } + }; + + class _StringComparer + : public Tizen::Base::Collection::IComparerT + { + public: + virtual result Compare(const Tizen::Base::String& string1, const Tizen::Base::String& string2, int& cmp) const + { + cmp = string1.CompareTo(string2); + return E_SUCCESS; + } + }; + +private: + _IpcClient* __pIpcClient; + Tizen::Base::Collection::HashMapT __listeners; +}; // _ChannelServiceProxy + + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_SERVICE_PROXY_H_ diff --git a/src/io/inc/FIo_ChannelServiceStub.h b/src/io/inc/FIo_ChannelServiceStub.h new file mode 100644 index 0000000..7dd1339 --- /dev/null +++ b/src/io/inc/FIo_ChannelServiceStub.h @@ -0,0 +1,128 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelServiceStub.h + * @brief This is the header file for the _ChannelServiceStub class. + * + * This file contains the declarations of _ChannelServiceStub. + */ + + +#ifndef _FIO_INTERNAL_CHANNEL_SERVICE_STUB_H_ +#define _FIO_INTERNAL_CHANNEL_SERVICE_STUB_H_ + +#include +#include +#include +#include +#include +#include "FIo_IIpcServerEventListener.h" +#include "FIo_IChannelServiceStub.h" + +namespace IPC +{ +class Message; +} + +namespace Tizen { namespace Io +{ + +class _IpcServer; +class _ChannelService; + +class _OSP_EXPORT_ _ChannelServiceStub + : public _IIpcServerEventListener + , public _IChannelServiceStub + , public Tizen::Base::Object +{ +public: + _ChannelServiceStub(void); + + virtual ~_ChannelServiceStub(void); + + virtual result Construct(void); + + // _IChannelServiceStub + virtual result SendRequest(int clientId, const Tizen::Base::String& src, + const Tizen::Base::String& dest, + const Tizen::Base::Collection::ArrayList& args, + int requestId); + + virtual result SendNullRequest(int clientId, const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int requestId); + + virtual result SendResponse(int clientId, const Tizen::Base::String& src, + const Tizen::Base::String& dest, + const Tizen::Base::Collection::ArrayList& args, + int requestId); + + virtual result SendNullResponse(int clientId, const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int requestId); + + virtual void SetChannelService(_ChannelService& service); + + +private: + bool OnRegisterChannelMessage(const Tizen::Base::String& appId, int* pResult); + + bool OnSendRequestMessage(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + const Tizen::Base::Collection::ArrayList& args, + int requestId, + int* pResult); + + bool OnSendNullRequestMessage(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int requestId, + int* pResult); + + bool OnSendResponseMessage(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + const Tizen::Base::Collection::ArrayList& args, + int requestId, + int* pResult); + + bool OnSendNullResponseMessage(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int requestId, + int* pResult); + + virtual void OnIpcRequestReceived(_IpcServer& server, const IPC::Message& message); + + virtual void OnIpcServerStarted(const _IpcServer& server); + + virtual void OnIpcServerStopped(const _IpcServer& server); + + virtual void OnIpcClientConnected(const _IpcServer& server, int clientId); + + virtual void OnIpcClientDisconnected(const _IpcServer& server, int clientId); + + _ChannelServiceStub(const _ChannelServiceStub& value); + _ChannelServiceStub& operator = (const _ChannelServiceStub& value); +private: + _IpcServer* __pIpcServer; + _ChannelService* __pChannelService; + +}; // _ChannelServiceStub + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_SERVICE_STUB_H_ + diff --git a/src/io/inc/FIo_ChannelWebAppStub.h b/src/io/inc/FIo_ChannelWebAppStub.h new file mode 100644 index 0000000..b882bf9 --- /dev/null +++ b/src/io/inc/FIo_ChannelWebAppStub.h @@ -0,0 +1,223 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ChannelWebAppStub.h + * @brief This is the header file for the _ChannelWebAppStub class. + * + * This file contains the declarations of _ChannelWebAppStub. + */ + +#ifndef _FIO_INTERNAL_CHANNEL_WEBAPP_STUB_H_ +#define _FIO_INTERNAL_CHANNEL_WEBAPP_STUB_H_ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ +class _EventDispatcher; +}}} + +namespace Tizen { namespace Io +{ + +enum WebSocketType +{ + WS_NONE, + WS_HYBI00, + WS_HYBI10 +}; + +class _IIpcServerEventListener; +class _ChannelServiceStub; + +/** + * @class _ChannelWebAppStub + * @brief This class provides methods to handle web-application request messages. + * @since 2.1 + * + */ +class _OSP_EXPORT_ _ChannelWebAppStub + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * @since 2.1 + */ + _ChannelWebAppStub(void); + + /** + * This is the destructor for this class. + * @since 2.1 + */ + virtual ~_ChannelWebAppStub(void); + + result Construct(void); + + void SetChannelService(_ChannelService& service); + + static bool SendResponse(int clientId, const Tizen::Base::Collection::ArrayList& args); + +private: + _ChannelWebAppStub(const _ChannelWebAppStub& rhs); + + _ChannelWebAppStub& operator =(const _ChannelWebAppStub& rhs); + + static gboolean OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data); + + static gboolean OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data); + + gboolean HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data); + + static std::string CreateResponseHeader(int appSocket, SoupMessageHeaders *header, const std::string& response); + + static WebSocketType VerifyHttpHeaderType(std::string header, int headerLength); + static std::string MakeHybi00Response(uint32_t first, uint32_t second, unsigned char* third); + static std::string MakeHybi10Response(std::string& secureAccept); + + static bool AppendChallengeNumber(uint32_t number, unsigned char *response); + static unsigned int ExtractChallengeNumber(const char* keyString); + static char* EncodeBase64(unsigned char *string, int len); + + +// struct _ClientInfo; +// +// struct _ChannelInfo +// { +// _ChannelInfo(void); +// ~_ChannelInfo(void); +// +// struct _ClientInfo* pClientInfo; +// GIOChannel* pGIOChannel; +// GSource* pGSource; +// bool destroySource; +// }; +// +// struct _ClientInfo +// { +// _ClientInfo(void); +// ~_ClientInfo(void); +// +// int clientId; // the client id +// _ChannelWebAppStub* pChannelStub; // the pointer to an _ChannelWebAppStub +// //GIOChannel* pReverseChannel; // the channel for sending reverse message +// std::vector channels; // the set of channels associated with a client +// //Tizen::Base::String appId; +// //Tizen::Base::String appExecutableName; +// }; + + class _ClientInfo; + + class _ChannelInfo + { + public: + _ChannelInfo(void); + ~_ChannelInfo(void); + + _ClientInfo* pClientInfo; + + Tizen::App::AppId destAppId; + + GIOChannel* pGIOChannel; + GSource* pGSource; + bool destroySource; + }; + + class _ClientInfo + : public Tizen::Base::Object + { + public: + _ClientInfo(void); + ~_ClientInfo(void); + + Tizen::App::AppId srcAppId; + + //int clientId; + Tizen::Base::String key; // key = srcAppId + srcAppExecName + _ChannelWebAppStub* pChannelStub; + std::vector channels; /**< the set of channels associated with a client */ + }; + + class _WebSocketMessage + { + public: + _WebSocketMessage(void); + ~_WebSocketMessage(void); + + + typedef union + { + struct + { + unsigned int opcode : 4; + unsigned int rsv3 : 1; + unsigned int rsv2 : 1; + unsigned int rsv1 : 1; + unsigned int fin : 1; + unsigned int payloadLen : 7; + unsigned int masked : 1; + } factors; + uint16_t header; + } MiniHeader; + + int ParseHeader(uint8_t* header, int messageLen); + int ParsePayload(uint8_t* payload, int messageLen); + void ConsoleMessage() const; + static size_t CreateMessage(std::string& payload, std::string& message); + + MiniHeader m_header; + uint8_t m_payloadOffset; + uint8_t m_maskingKey[4]; + uint64_t m_payloadLen; + bool m_headerParsed; + uint8_t* m_payload; + + private: + _WebSocketMessage(_WebSocketMessage& webSocketMessage); + + _WebSocketMessage& operator =(const _WebSocketMessage& webSocketMessage); + + }; + + _ChannelService* __pChannelService; + + GMainContext* __pGMainContext; + GSource* __pServerGSource; + GSource* __pClientGSource; + + Tizen::Base::Collection::HashMap* __pClients; + +}; // _ChannelWebAppStub + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_WEBAPP_STUB_H_ + diff --git a/src/io/inc/FIo_ClientChannelImpl.h b/src/io/inc/FIo_ClientChannelImpl.h new file mode 100644 index 0000000..005af44 --- /dev/null +++ b/src/io/inc/FIo_ClientChannelImpl.h @@ -0,0 +1,79 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ClientChannelImpl.h + * @brief This is the header file for the _ClientChannelImpl class. + * + * This file contains the declarations of _ClientChannelImpl + */ + + +#ifndef _FIO_INTERNAL_CLIENT_CHANNEL_IMPL_H_ +#define _FIO_INTERNAL_CLIENT_CHANNEL_IMPL_H_ + +#include +#include +#include +#include +#include +#include +#include "FIo_IChannelResponseEventListener.h" + + +namespace Tizen { namespace Io +{ + +class _Channel; +class ClientChannel; +class IChannelResponseEventListener; + +class _ClientChannelImpl + : public Tizen::Base::Object + , public _IChannelResponseEventListener +{ +public: + _ClientChannelImpl(void); + + virtual ~_ClientChannelImpl(void); + + result Construct(ClientChannel* pClientChannel, const Tizen::Base::String& channelName = L""); + + void SetChannelResponseEventListener(IChannelResponseEventListener* pResponseEventListener); + + result SendRequest(const Tizen::Base::String& serverChannelId, const Tizen::Base::Collection::IList* pArgs, RequestId& reqId); + + void OnChannelResponseReceivedN(RequestId reqId, const Tizen::Base::String& channelId, Tizen::Base::Collection::IList* pArgs); + + static _ClientChannelImpl* GetInstance(ClientChannel* pChannel); + + static ClientChannel* GetClientChannel(const Tizen::Base::String& channelName); + +private: + _ClientChannelImpl(const _ClientChannelImpl& value); + + _ClientChannelImpl& operator =(const _ClientChannelImpl& value); + +private: + ClientChannel* __pClientChannel; + IChannelResponseEventListener* __pResponseListener; + _Channel* __pChannel; +}; // _ClientChannelImpl + +} } // Tizen::Io + +#endif //_FIO_INTERNAL_CLIENT_CHANNEL_IMPL_H_ diff --git a/src/io/inc/FIo_DataControlResultSetEnumerator.h b/src/io/inc/FIo_DataControlResultSetEnumerator.h new file mode 100644 index 0000000..189b6a4 --- /dev/null +++ b/src/io/inc/FIo_DataControlResultSetEnumerator.h @@ -0,0 +1,384 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DataControlResultSetEnumerator.h + * @brief This is the header file for the %_DataControlResultSetEnumerator class. + * + * This header file contains the declarations of the %_DataControlResultSetEnumerator class. + */ + +#ifndef _FIO_INTERNAL_DATACONTROL_RESULTSET_ENUMERATOR_H_ +#define _FIO_INTERNAL_DATACONTROL_RESULTSET_ENUMERATOR_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace App +{ +class _SqlDataControlImpl; +}} + +namespace Tizen { namespace Io +{ + +/** +* @class _DataControlResultSetEnumerator +* @brief This class provides methods for navigating the result set from SQL-type data control query request. +* @since 2.1 +*/ +class _OSP_EXPORT_ _DataControlResultSetEnumerator + : public Tizen::Base::Object + , public Tizen::Io::IDbEnumerator +{ + +public: + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_DataControlResultSetEnumerator(void); + + /** + * Moves the enumerator to the next position. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). + * @exception E_OUT_OF_RANGE The enumerator has reached out of the result set. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result MoveNext(void); + + /** + * Moves the enumerator to the previous position. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). + * @exception E_OUT_OF_RANGE The enumerator has reached out of the result set. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result MovePrevious(void); + + /** + * Moves the enumerator to the first position. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result MoveFirst(void); + + /** + * Moves the enumerator to the last position. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to move the cursor position of the result set that is not activated + * (the query did not yield any result). + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + virtual result MoveLast(void); + + /** + * Resets the calling %DataControlResultSetEnumerator instance back to its initial state. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to reset the enumerator of the result set that is not activated + * (the query did not yield any result). + * @remarks After this method is called, if MoveNext() is called the cursor goes to the first position. + * @see Tizen::Io::DataControlResultSetEnumerator::MoveNext() + */ + virtual result Reset(void); + + /** + * Gets a @c int value from the column whose index is specified. + * + * @since 2.1 + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The integer value obtained from the column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetIntAt(int columnIndex, int& value) const; + + /** + * Gets a @c long @c long value from the column whose index is specified. + * + * @since 2.1 + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The 64-bit integer value obtained from the column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetInt64At(int columnIndex, long long& value) const; + + /** + * Gets a @c double value from the column whose index is specified. + * + * @since 2.1 + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a double + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + */ + virtual result GetDoubleAt(int columnIndex, double& value) const; + + /** + * Gets a @c String value from the column whose index is specified. + * + * @since 2.1 + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a String + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_INVALID_ENCODING_RANGE The string conversion has failed due to invalid encoding range. + */ + virtual result GetStringAt(int columnIndex, Tizen::Base::String& value) const; + + /** + * Gets a byte array value from the column whose index is specified. + * + * @since 2.1 + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The user-provided buffer used to receive the blob data as a stream of type ByteBuffer. @n + * The buffer will be filled from the current position and data copy will be continued + * until buffer limitation is reached or no more blob data remains. @n + * The maximum size available is limited to 100 MByte. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_OUT_OF_RANGE The byte buffer operation has failed. + * @exception E_OVERFLOW The specified @c value of the byte buffer is insufficient to save the data. + */ + virtual result GetBlobAt(int columnIndex, Tizen::Base::ByteBuffer& value) const; + + /** + * Gets a blob data from the column whose index is specified. + * + * @since 2.1 + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] buffer The user-provided buffer used to receive the blob data @n + * The maximum size available is limited to 100 MByte. + * @param[out] size The maximum buffer length in bytes + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range, or the specified @c size is invalid. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_OVERFLOW The specified @c buffer is insufficient to save the data. + */ + virtual result GetBlobAt(int columnIndex, void* buffer, int size) const; + + /** + * Gets a @c DateTime value from the column whose index is specified. + * + * @since 2.1 + * @return An error code + * @param[in] columnIndex The index of the column whose value is required + * @param[in,out] value The value obtained from the column as a DateTime instance + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_TYPE_MISMATCH The operation has attempted to access columns of different types. + * @exception E_INVALID_FORMAT The date is not correctly formatted, or the method is trying to access column of type String. @n + * The date format should be 'mm/dd/yyyy hh:mm:ss'. + * @exception E_OUT_OF_RANGE Either the year(%d), month(%d), day(%d), hour(%d), minute(%d), or second(%d) value is out of range, + * or the method is trying to access a column of type String. + * @remarks Note that the DateTime is constructed inside the method. + */ + virtual result GetDateTimeAt(int columnIndex, Tizen::Base::DateTime& value) const; + + /** + * Gets the number of columns for this enumerator. + * + * @since 2.1 + * @return The number of columns in the calling enumerator, @n + * else @c -1 if an exception occurs + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @remarks This method should be called after MoveNext() or MoveFirst() or MoveLast(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetColumnCount(void) const; + + /** + * Gets the type of the column indicated by the specified index. + * + * @since 2.1 + * @return The type of column @n + * else DB_COLUMNTYPE_UNDEFINED if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @remarks The method should be called after MoveNext() or MoveFirst() or MoveLast(). @n + * Currently, DB_COLUMNTYPE_INT is returned for a 64-bit integer. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual DbColumnType GetColumnType(int columnIndex) const; + + /** + * Gets the name of the column indicated by the specified index. + * + * @since 2.1 + * @return The name of the column, @n + * else an empty string if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @exception E_INVALID_ENCODING_RANGE String conversion failed due to invalid encoding range. @n + * @remarks The method should be called after MoveNext() or MoveFirst() or MoveLast(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual Tizen::Base::String GetColumnName(int columnIndex) const; + + /** + * Gets the size of data in bytes. + * + * @since 2.1 + * @return The size of the data in bytes, @n + * else @c -1 if an exception occurs + * @param[in] columnIndex The index of the destination column + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The method has tried to fetch the column data of a result set that is not activated + * (the query did not yield any result). + * @exception E_INVALID_ARG The specified @c columnIndex is out of range. + * @remarks The method should be called after MoveNext() or MoveFirst() or MoveLast(). @n + * If the destination column is of type %String, this method returns the @c byte length excluding the @c null terminator character. @n + * The specific error code can be accessed using the GetLastResult() method. + */ + virtual int GetColumnSize(int columnIndex) const; + +private: + /** + * This is the default constructor for this class. + * + * @since 2.1 + */ + _DataControlResultSetEnumerator(void); + + /** + * Initializes this instance of _DataControlResultSetEnumerator with the specified parameters. + * + * @since 2.1 + * @return An error code + * @param[in] filePath The path to the file storing the result set. + * @exception E_SUCCESS The method was successful. + */ + result SetPath(const Tizen::Base::String filePath); + + void* __pFile; + + int __rowCount; + + int __columnCount; + + int __columnTypeOffset; + + int __columnNameOffset; + + int __contentOffset; + + int __currentOffset; + + int __currentRowCount; + + Tizen::Base::Collection::LinkedList __rowOffsetList; + + friend class Tizen::App::_SqlDataControlImpl; + +}; // _DataControlResultSetEnumerator + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_DATACONTROL_RESULTSET_ENUMERATOR_H_ + diff --git a/src/io/inc/FIo_DataControlResultSetImpl.h b/src/io/inc/FIo_DataControlResultSetImpl.h new file mode 100644 index 0000000..9c57e48 --- /dev/null +++ b/src/io/inc/FIo_DataControlResultSetImpl.h @@ -0,0 +1,139 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DataControlResultSetImpl.h + * @brief This is the header file for the %_DataControlResultSetImpl class. + * + * This header file contains the declarations of the %_DataControlResultSetImpl class. + */ + +#ifndef _FIO_INTERNAL_DATACONTROL_RESULTSET_IMPL_H_ +#define _FIO_INTERNAL_DATACONTROL_RESULTSET_IMPL_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace App +{ +class _AppImpl; +}} +namespace Tizen { namespace Base +{ +class String; +}} + +namespace Tizen { namespace Io +{ + +class DbEnumerator; + +class _OSP_EXPORT_ _DataControlResultSetImpl + : public Tizen::Base::Object +{ + +public: + /** + * This is the constructor for this class. + * + * @since 2.1 + * @param[in] reqId The request ID @n + * It is identification for data control request to be replied + */ + _DataControlResultSetImpl(RequestId reqId); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_DataControlResultSetImpl(void); + + /** + * Fills result set with the specified @c dbEnumerator. + * + * @since 2.1 + * @return An error code + * @param[in] dbEnumerator %Database enumerator instance + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The specified @c dbEnumerator has already been set. + * @exception E_DATABASE Either of the following conditions has occurred: + * - The database file was closed. + * - The database engine has failed to execute query. + * @exception E_IO Either of the following conditions has occurred: + * - An unexpected device failure has occurred as the media ejected suddenly. + * - Detected corruption of a file. + */ + result FillWith(IDbEnumerator* pDbEnum); + +private: + /** + * This is the default constructor for this class. + * + * @since 2.1 + */ + _DataControlResultSetImpl(void); + + /** + * This is the default copy constructor for this class. + * + * @since 2.1 + */ + _DataControlResultSetImpl(const _DataControlResultSetImpl& rhs); + + /** + * This is the assignment operator for this class. + * + * @since 2.1 + */ + _DataControlResultSetImpl& operator =(const _DataControlResultSetImpl& rhs); + + /** + * Sets the range of a set of data to be added. + * + * @since 2.1 + * @return An error code + * @param[in] pageNo The page number of the data set. @n + * It starts from @c 1. + * @param[in] countPerPage The desired maximum count of the data item on the page. + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_STATE This instance has not been properly constructed yet. + * @exception E_INVALID_ARG Either of the following conditions has occurred: @n + * - The specified @c pageNo parameter is less than @c 1. + * - The specified @c countPerPage parameter is less than @c 1. + */ + result SetCapacity(int pageNo = 1, int countPerPage = 20); + + bool __constructed; + int __pageNo; + int __countPerPage; + result __result; + Tizen::Base::String __tmpPath; + RequestId __reqId; + + friend class Tizen::App::_AppImpl; + +}; // _DataControlResultSetImpl + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_DATACONTROL_RESULTSET_IMPL_H_ + diff --git a/src/io/inc/FIo_DataRouter.h b/src/io/inc/FIo_DataRouter.h new file mode 100644 index 0000000..91565b8 --- /dev/null +++ b/src/io/inc/FIo_DataRouter.h @@ -0,0 +1,67 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DataRouter.h + * @brief This is the header file for the %_DataRouter class. + * + * This header file contains the declarations of the %_DataRouter class. + */ + +#ifndef _FIO_INTERNAL_DATA_ROUTER_H_ +#define _FIO_INTERNAL_DATA_ROUTER_H_ + +#include +#include + +namespace Tizen {namespace Io { + +class _IDataRouterEventListener; //Data Receiver + +enum _DataRouterState +{ + _DATA_ROUTER_STATE_OPENED = 0, + _DATA_ROUTER_STATE_CLOSED +}; +/** + * This class provides communication feature on a datarouter module. The datarouter is a tizen module for USB connection management such as Kies, Debugging, MTP, Internet sharing. + */ +class _OSP_EXPORT_ _DataRouter + : public Tizen::Base::Object +{ + +public: + result Construct(_IDataRouterEventListener& listener); + result Write(const char* data, int length); + void DataReceived(const char* data, int length); + void StateChanged(_DataRouterState state); + + static _DataRouter* GetInstance(void); + static void ReleaseInstance(void); + +private: + _DataRouter(); + ~_DataRouter(); + + _IDataRouterEventListener* __pDataRouterEventListener; + bool __initialized; +}; // _DataRouter + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_DATA_ROUTER_H_ + diff --git a/src/io/inc/FIo_DatabaseImpl.h b/src/io/inc/FIo_DatabaseImpl.h new file mode 100644 index 0000000..2b8daa5 --- /dev/null +++ b/src/io/inc/FIo_DatabaseImpl.h @@ -0,0 +1,172 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIoDatabase.h + * @brief This is the header file for the %_DatabaseImpl class. + * + * This header file contains the declarations of the %_DatabaseImpl class. + */ + +#ifndef _FIO_INTERNAL_DATABASE_IMPL_H_ +#define _FIO_INTERNAL_DATABASE_IMPL_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +namespace Collection +{ +class LinkedList; +} +}} + +namespace Tizen { namespace Io +{ + +class DbStatement; +class DbEnumerator; +class _DbEnumeratorImpl; +class _IDbUserFunctionListener; +class _IDbUserAggregateListener; +class _IDbUserCollationListener; + +typedef struct Mem sqlite3_value; +typedef struct sqlite3_context sqlite3_context; + +class _OSP_EXPORT_ _DatabaseImpl + : public Tizen::Base::Object +{ + +public: + _DatabaseImpl(void); + + virtual ~_DatabaseImpl(void); + + result Construct(const Tizen::Base::String& dbPath, bool createIfNotExist); + + result Construct(const Tizen::Base::String& dbPath, long openMode, const Tizen::Base::ByteBuffer* pSecretKey); + + result Construct(const Tizen::Base::String& dbPath, const char* pOpenMode, const Tizen::Base::ByteBuffer* pSecretKey); + + DbStatement* CreateStatementN(const Tizen::Base::String& statement); + + DbEnumerator* ExecuteStatementN(const DbStatement& statement); + + result ExecuteSql(const Tizen::Base::String& sql, bool autoCommit); + + DbEnumerator* QueryN(const Tizen::Base::String& query); + + result BeginTransaction(void); + + result CommitTransaction(void); + + result RollbackTransaction(void); + + Tizen::Base::String GetName(void) const; + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // Registers the user defined SQL function. + // + // @since 2.1 + // @return An error code + // @param[in] functionName Name of the SQL function. + // @param[in] argumentCount The number of arguments to be used by the SQL function. + // @param[in] pUserData User data if any + // @param[in] pUserFunctionListener A listener invoked when the SQL function is executed. + // @param[in] pUserAggregateListener A listener invoked when the SQL aggregate is executed. + // @exception E_SUCCESS The method was successful. + // @exception E_INVALID_STATE The database was not opened. + // @exception E_INVALID_ARG Either of the following conditions has occurred: @n + // - The length of the specified @c functionName exceeded system limitation. @n + // - The specified @c argumentCount passed was < 0 or > 127. + // - One of the specified @c pUserFunctionListener and the specified @c pUserAggregateListener + // cannot be registered together. + // @exception E_DATABASE Failed to create the user defined SQL function due to its misuse. + // + result RegisterUserFunction(const Tizen::Base::String& functionName, int argumentCount, void* pUserData, _IDbUserFunctionListener* pUserFunctionListener, _IDbUserAggregateListener* pUserAggregateListener); + + // + // This method is for internal use only. + // Using this method can cause behavioral, security-related, and consistency-related issues in the application. + // + // Registers the user defined SQL collation function. + // + // @since 2.1 + // @return An error code + // @param[in] collationName Name of the SQL collating function + // @param[in] pUserData User data if any + // @param[in] pUserCollationListener A listener invoked when the SQL collating function is executed. + // @exception E_SUCCESS The method was successful. + // @exception E_INVALID_STATE The database was not opened. + // @exception E_DATABASE Failed to create the user defined SQL collating function due to its misuse. + // + result RegisterUserCollation(const Tizen::Base::String& collationName, void* pUserData, _IDbUserCollationListener* pUserCollationListener); + + long long GetLastInsertRowId(void) const; + + static result Delete(const Tizen::Base::String& databasePath); + + static bool Exists(const Tizen::Base::String& databasePath); + + static result ConvertToSecureDatabase(const Tizen::Base::String& plainDatabasePath, const Tizen::Base::String& secureDatabasePath, const Tizen::Base::ByteBuffer* pKey = null); + + static _DatabaseImpl* GetInstance(Database& database); + + static const _DatabaseImpl* GetInstance(const Database& database); + +private: + _DatabaseImpl(_DatabaseImpl& databaseImpl); + + _DatabaseImpl& operator =(const _DatabaseImpl& databaseImpl); + + bool IsDirectory(const Tizen::Base::String& databasePath); + + bool VerifyDatabaseOpenMode(const char* pOpenMode, long& legacyMode); + + static void UserFunctionListener(sqlite3_context* pContext, int argumentCount, sqlite3_value** pArgList); + + static void UserFunctionStepListener(sqlite3_context* pContext, int argumentCount, sqlite3_value** pArgList); + + static void UserFunctionFinalListener(sqlite3_context* pContext); + + static int UserCollationListener(void* pContext, int length1, const void* pInput1, int length2, const void* pInput2); + + Tizen::Base::String __dbName; + void* __pDatabase; + bool __transactionGoingOn; + Tizen::Base::Collection::LinkedList __userFunctionContextList; + Tizen::Base::Collection::LinkedList __userCollationContextList; + + friend class DbStatement; + friend class DbEnumerator; + friend class _DbEnumeratorImpl; + +}; // _DatabaseImpl + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_DATABASE_IMPL_H_ + diff --git a/src/io/inc/FIo_DbContextImpl.h b/src/io/inc/FIo_DbContextImpl.h new file mode 100644 index 0000000..22969f9 --- /dev/null +++ b/src/io/inc/FIo_DbContextImpl.h @@ -0,0 +1,208 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// +// This method is for internal use only. The Tizen platform team is not +// responsible for any behavioral correctness, consistency, and +// security-related issues that might arise after using this method. +// +// @file FIo_DbContextImpl.h +// @brief This is the header file for the %_DbContextImpl class. +// +// This header file contains declarations of the %_DbContextImpl class. + +#ifndef _FIO_INTERNAL_DBCONTEXTIMPL_H_ +#define _FIO_INTERNAL_DBCONTEXTIMPL_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +class _IDbUserFunctionListener; +class _IDbUserAggregateListener; +class _IDbUserCollationListener; + +// This method is for internal use only. The Tizen platform team is not +// responsible for any behavioral correctness, consistency, and +// security-related issues that might arise after using this method. +// +// @enum _DbUserListenerErrorCode +// Defines Database error codes used by user listeners. +// +// @since 2.1 +// @see Tizen::Io::_IDbUserFunctionListener, Tizen::Io::_IDbUserAggregateListener, and +// Tizen::Io::_IDbUserCollationListener. + +enum _DbUserListenerErrorCode +{ + DB_USER_LISTENER_OK = 0, /** Successful result */ + DB_USER_LISTENER_ERROR, /** SQL error */ + DB_USER_LISTENER_ABORT, /** Callback routine requested an abort */ + DB_USER_LISTENER_NOMEM, /** Insufficient memory */ +}; + +// This method is for internal use only. The Tizen platform team is not +// responsible for any behavioral correctness, consistency, and +// security-related issues that might arise after using this method. +// +// @class _DbContext +// @brief This class provides methods for managing the user defined SQL function or aggregate. +// @since 2.1 +class _OSP_EXPORT_ _DbContextImpl + : public Tizen::Base::Object +{ + +public: + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // This is the default destructor for this class. + // + // @since 2.1 + virtual ~_DbContextImpl(void); + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Gets the String value from a parameter of the user defined SQL function or aggregate. + // + // @since 2.1 + // @return An error code + // @param[in] argumentIndex The index of the arguments of the user defined SQL function or aggregate. @n + // It starts from @c 0. + // @param[in] value The String value obtained from the argument pointed by the specified @c argumentIndex. + // @exception E_SUCCESS The method was successful. @n + // @exception E_INVALID_STATE This instance has not been properly constructed yet. @n + // @exception E_INVALID_ARG If the specified @c argumentIndex is negative. @n + // @exception E_DATABASE Failed to retrieve the String value. + // + result GetStringAt(int argumentIndex, Tizen::Base::String& value); + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Sets the String value as result to be passsed to database engine. + // + // @since 2.1 + // @return An error code + // @param[in] value String value to be set @n + // @exception E_SUCCESS The method was successful. @n + // @exception E_INVALID_STATE This instance has not been properly constructed yet. @n + // @exception E_DATABASE Failed to set the result. + // + result SetResultString(const Tizen::Base::String& value); + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Sets the integer value as result to be passsed to database engine. + // + // @since 2.1 + // @return An error code. + // @param[in] result Interger value to be set. @n + // @exception E_SUCCESS The method was successful. @n + // @exception E_INVALID_STATE This instance has not been properly constructed yet. @n + // @exception E_DATABASE Failed to set the result. @n + // + result SetResultInt(int value); + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Sets the double value as result to be passsed to database engine. + // + // @since 2.1 + // @return An error code. + // @param[in] result double value to be set. @n + // @exception E_SUCCESS The method was successful. @n + // @exception E_INVALID_STATE This instance has not been properly constructed yet. @n + // @exception E_DATABASE Failed to set the result. @n + // + result SetResultDouble(double value); + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Sets the result error code to be passsed to database engine. + // + // @since 2.1 + // @return An error code. + // @param[in] errorCode SQLite error code. @n + // @exception E_SUCCESS The method was successful. @n + // @exception E_INVALID_STATE This instance has not been properly constructed yet. @n + // @exception E_DATABASE Failed to set the error code. @n + // + result SetResultErrorCode(_DbUserListenerErrorCode errorCode); + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Gets the user data if set any while creating SQL functions or aggregate. + // + // @since 2.1 + // @return user data pointer. + // @exception E_SUCCESS The method was successful. @n + // @exception E_INVALID_STATE This instance has not been properly constructed yet. @n + void* GetUserData(void); + + static void DestroyListener(void* pData); + +private: + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // This is the default constructor for this class. + // + // @since 2.1 + _DbContextImpl(void); + + static int ConvertDbErrorToNativeSqliteError(int errorCode); + + void* __pContext; + + void** __pArgList; + + void* __pUserData; + + _IDbUserFunctionListener* __pUserFunctionListener; + + _IDbUserAggregateListener* __pUserAggregateListener; + + _IDbUserCollationListener* __pUserCollationListener; + + int __argumentCount; + + Tizen::Base::String __functionName; + + Tizen::Base::String __collationName; + + friend class _DatabaseImpl; + +}; // _DbContextImpl + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_DBCONTEXTIMPL_H_ diff --git a/src/io/inc/FIo_DbEnumeratorImpl.h b/src/io/inc/FIo_DbEnumeratorImpl.h new file mode 100644 index 0000000..521c585 --- /dev/null +++ b/src/io/inc/FIo_DbEnumeratorImpl.h @@ -0,0 +1,215 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DbEnumeratorImpl.h + * @brief This is the header file for the %_DbEnumeratorImpl class. + * + * This header file contains declarations of the %_DbEnumeratorImpl class. + */ + +#ifndef _FIO_INTERNAL_DBENUMERATOR_IMPL_H_ +#define _FIO_INTERNAL_DBENUMERATOR_IMPL_H_ + +#include +#include +#include + +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +class DateTime; +}} + +namespace Tizen { namespace Io +{ + +class _DbEnumeratorCache; +class _DbRow; +/** + * @class _DbEnumeratorImpl + * @brief This class implements the DbEnumerator. + * @since 2.1 + * + * @see Tizen::Io::DbEnumerator + */ + +class _OSP_EXPORT_ _DbEnumeratorImpl + : public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. + */ + _DbEnumeratorImpl(void); + + /** + * This is the default destructor for this class. + */ + virtual ~_DbEnumeratorImpl(void); + + /** + * @see DbEnumerator::MoveNext() + */ + result MoveNext(void); + + /** + * @see DbEnumerator::MovePrevious() + */ + result MovePrevious(void); + + /** + * @see DbEnumerator::MoveFirst() + */ + result MoveFirst(void); + + /** + * @see DbEnumerator::MoveLast() + */ + result MoveLast(void); + + /** + * @see DbEnumerator::Reset() + */ + result Reset(void); + + /** + * @see DbEnumerator::GetIntAt() + */ + result GetIntAt(int columnIndex, int& value) const; + + /** + * @see DbEnumerator::GetInt64At() + */ + result GetInt64At(int columnIndex, long long& value) const; + + /** + * @see DbEnumerator::GetDoubleAt() + */ + result GetDoubleAt(int columnIndex, double& value) const; + + /** + * @see DbEnumerator::GetStringAt() + */ + result GetStringAt(int columnIndex, Tizen::Base::String& value) const; + + /** + * @see DbEnumerator::GetBlobAt() + */ + result GetBlobAt(int columnIndex, Tizen::Base::ByteBuffer& value) const; + + /** + * @see DbEnumerator::GetBlobAt() + */ + result GetBlobAt(int columnIndex, void* buffer, int size) const; + + /** + * @see DbEnumerator::GetDateTimeAt() + */ + result GetDateTimeAt(int columnIndex, Tizen::Base::DateTime& value) const; + + /** + * @see DbEnumerator::GetColumnCount() + */ + int GetColumnCount(void) const; + + /** + * @see DbEnumerator::GetColumnType() + */ + DbColumnType GetColumnType(int columnIndex) const; + + /** + * @see DbEnumerator::GetColumnName() + */ + Tizen::Base::String GetColumnName(int columnIndex) const; + + /** + * @see DbEnumerator::GetColumnSize() + */ + int GetColumnSize(int columnIndex) const; + + static _DbEnumeratorImpl* GetInstance(DbEnumerator& dbEnumerator); + + static const _DbEnumeratorImpl* GetInstance(const DbEnumerator& dbEnumerator); + + static DbEnumerator* CreateDbEnumeratorInstanceN(void); + +private: + _DbEnumeratorImpl(_DbEnumeratorImpl& dbEnumeratorImpl); + + _DbEnumeratorImpl& operator =(const _DbEnumeratorImpl& dbEnumeratorImpl); + + /** + * Moves the cursor to the next row and caches the column data. + * + * @since 2.1 + * + * @return An error code + * @param[in] cacheColumnNamesToo Set to @c true to cache the column names, @n + * else @c false to ignore caching column names. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The data cache is not initialized.* + * @exception E_OUT_OF_RANGE The enumerator has reached out of the result set. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result CacheRow(bool cacheColumnNamesToo = false); + + /** + * Moves the cursor to the position specified by @c rowIndex and caches the column data into @c dbRow. + * + * @since 2.1 + * + * @return An error code + * @param[in,out] dbRow The list of values obtained from the result row. + * @param[in] rowIndex The index of a row data to be cached. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_STATE Either of the following conditions has occurred: + * - This instance has not been properly constructed. + * - The data cache is not initialized. + * @exception E_DATABASE The query did not yield any result. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result CacheRow(_DbRow& dbRow, int rowIndex); + + bool __shouldReleaseResource; + + void* __pEnum; + + void* __pDatabase; + + int __columnCount; + + int __rowCount; + + int __currentRowIndex; + + _DbEnumeratorCache* __pDbEnumeratorCache; + + friend class DbEnumerator; + friend class _DatabaseImpl; + +}; // _DbEnumeratorImpl + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_DBENUMERATOR_IMPL_H_ + diff --git a/src/io/inc/FIo_DbStatementImpl.h b/src/io/inc/FIo_DbStatementImpl.h new file mode 100644 index 0000000..43da28b --- /dev/null +++ b/src/io/inc/FIo_DbStatementImpl.h @@ -0,0 +1,105 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DbEnumeratorImpl.h + * @brief This is the header file for the %_DbEnumeratorImpl class. + * + * This header file contains declarations of the %_DbEnumeratorImpl class. + */ + +#ifndef _FIO_INTERNAL_DBSTATEMENT_IMPL_H_ +#define _FIO_INTERNAL_DBSTATEMENT_IMPL_H_ + +#include + +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +class DateTime; +}} + +namespace Tizen { namespace Io +{ + +class _DatabaseImpl; + +/** + * @enum _DbStatementType + * Defines types of statement. + * @since 2.1 + */ +enum _DbStatementType +{ + DB_STATEMENT_TYPE_OTHER = 0, + DB_STATEMENT_TYPE_SELECT = 1 +}; + +/** + * @class _DbStatementImpl + * @brief This class implements the DbStatement. + * @since 2.1 + * + * @see Tizen::Io::DbStatement + */ +class _OSP_EXPORT_ _DbStatementImpl + : public Tizen::Base::Object +{ + +public: + _DbStatementImpl(void); + + virtual ~_DbStatementImpl(void); + + result BindInt(int columnIndex, int value); + + result BindInt64(int columnIndex, long long value); + + result BindDouble(int columnIndex, double value); + + result BindString(int columnIndex, const Tizen::Base::String& value); + + result BindBlob(int columnIndex, const Tizen::Base::ByteBuffer& value); + + result BindBlob(int columnIndex, const void* buffer, int size); + + result BindDateTime(int columnIndex, const Tizen::Base::DateTime& value); + + result BindNull(int columnIndex); + + static _DbStatementImpl* GetInstance(DbStatement& dbStatement); + + static const _DbStatementImpl* GetInstance(const DbStatement& dbStatement); + + static DbStatement* CreateDbStatementInstanceN(void); +private: + bool __shouldReleaseResource; + _DbStatementType __stmtType; + void* __pStmt; + void* __pDatabase; + + friend class _DatabaseImpl; + +}; //_DbStatementImpl + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_DBSTATEMENT_IMPL_H_ + diff --git a/src/io/inc/FIo_DirEntryImpl.h b/src/io/inc/FIo_DirEntryImpl.h new file mode 100644 index 0000000..059bf88 --- /dev/null +++ b/src/io/inc/FIo_DirEntryImpl.h @@ -0,0 +1,96 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DirEntryImpl.h + * @brief This is the header file for the %_DirEntryImpl class. + * + * This header file contains the declarations of the %_DirEntryImpl class. + */ + +#ifndef _FIO_INTERNAL_DIRENTRY_IMPL_H_ +#define _FIO_INTERNAL_DIRENTRY_IMPL_H_ + +#include +#include + +namespace Tizen { namespace Base +{ +class String; +class DateTime; +}} + +namespace Tizen { namespace Io +{ + +class DirEntry; + +class _OSP_EXPORT_ _DirEntryImpl + : public Tizen::Base::Object +{ + +public: + virtual ~_DirEntryImpl(void); + + static _DirEntryImpl* GetInstance(DirEntry* pDirEntry); + + static const _DirEntryImpl* GetInstance(const DirEntry* pDirEntry); + + _DirEntryImpl(const _DirEntryImpl& dirEntry); + + _DirEntryImpl& operator =(const _DirEntryImpl& dirEntry); + + virtual bool Equals(const Object& object) const; + + virtual int GetHashCode(void) const; + + const Tizen::Base::String GetName(void) const; + + unsigned long GetFileSize(void) const; + + bool IsDirectory(void) const; + + bool IsHidden(void) const; + + bool IsReadOnly(void) const; + + Tizen::Base::DateTime GetDateTime(void) const; + + static DirEntry* CreateDirEntryInstanceN(void); + +private: + _DirEntryImpl(void); + + void Set(Tizen::Base::DateTime dateTime, unsigned long fileSize, + Tizen::Base::String name, bool dir, bool readOnly, bool hidden); + + Tizen::Base::DateTime __dateTime; + unsigned long __fileSize; + Tizen::Base::String __name; + bool __directory; + bool __hidden; + bool __readOnly; + + friend class DirEntry; + friend class _DirEnumeratorImpl; + +}; //_DirEntryImpl + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_DIRENTRY_IMPL_H_ + diff --git a/src/io/inc/FIo_DirEnumeratorImpl.h b/src/io/inc/FIo_DirEnumeratorImpl.h new file mode 100644 index 0000000..58c3fe0 --- /dev/null +++ b/src/io/inc/FIo_DirEnumeratorImpl.h @@ -0,0 +1,82 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DirEnumeratorImpl.h + * @brief This is the header file for the _DirEnumeratorImpl class. + * + * This header file contains the declarations of the _DirEnumeratorImpl class. + */ + +#ifndef _FIO_INTERNAL_DIR_ENUMERATOR_IMPL_H_ +#define _FIO_INTERNAL_DIR_ENUMERATOR_IMPL_H_ + +#include +#include +#include + +#include + +namespace Tizen { namespace Io +{ + +class DirEntry; +class _DirectoryImpl; + +class _OSP_EXPORT_ _DirEnumeratorImpl + : public Tizen::Base::Object +{ + +public: + ~_DirEnumeratorImpl(void); + + DirEntry GetCurrentDirEntry(void) const; + + Tizen::Base::Object* GetCurrent(void) const; + + result MoveNext(void); + + result Reset(void); + + static _DirEnumeratorImpl* GetInstance(DirEnumerator& dirEnumerator); + + static const _DirEnumeratorImpl* GetInstance(const DirEnumerator& dirEnumerator); + + static DirEnumerator* CreateDirEnumeratorInstanceN(const Tizen::Base::String& dirPath); + +private: + _DirEnumeratorImpl(void); + + _DirEnumeratorImpl(const _DirEnumeratorImpl& source); + + _DirEnumeratorImpl(const Tizen::Base::String& dirPath); + + _DirEnumeratorImpl& operator =(const _DirEnumeratorImpl& source); + + bool __validAccess; + Tizen::Base::String __absoluteDirPath; + void* __pFileFindInfo; + DirEntry* __pCurDirEntry; + + friend class DirEnumerator; + friend class _DirectoryImpl; +}; + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_DIR_ENUMERATOR_IMPL_H_ + diff --git a/src/io/inc/FIo_DirectoryImpl.h b/src/io/inc/FIo_DirectoryImpl.h new file mode 100644 index 0000000..906014f --- /dev/null +++ b/src/io/inc/FIo_DirectoryImpl.h @@ -0,0 +1,78 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_DirectoryImpl.h + * @brief This is the header file for the %_DirectoryImpl class. + * + * This header file contains the declarations of the %_DirectoryImpl class. + */ + +#ifndef _FIO_INTERNAL_DIRECTORY_IMPL_H_ +#define _FIO_INTERNAL_DIRECTORY_IMPL_H_ + +#include +#include +#include + +namespace Tizen { namespace Base +{ +class String; +}} + +namespace Tizen { namespace Io +{ + +class DirEnumerator; + +class _OSP_EXPORT_ _DirectoryImpl + : public Tizen::Base::Object +{ + +public: + _DirectoryImpl(void); + + virtual ~_DirectoryImpl(void); + + result Construct(const Tizen::Base::String& dirPath); + + DirEnumerator* ReadN(void); + + static result Create(const Tizen::Base::String& dirPath, bool createParentDirectories = false); + + static result Remove(const Tizen::Base::String& dirPath, bool recursive = false); + + static result Rename(const Tizen::Base::String& orgDirPath, const Tizen::Base::String& newDirPath); + + static _DirectoryImpl* GetInstance(Directory& directory); + + static const _DirectoryImpl* GetInstance(const Directory& directory); + +private: + static result RemoveRecursively(char* pDirPath); + + Tizen::Base::String __dirPath; + void* __pDir; + + friend class DirEnumerator; + +}; // _DirectoryImpl + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_DIRECTORY_IMPL_H_ + diff --git a/src/io/inc/FIo_FileAttributesImpl.h b/src/io/inc/FIo_FileAttributesImpl.h new file mode 100644 index 0000000..e1f386e --- /dev/null +++ b/src/io/inc/FIo_FileAttributesImpl.h @@ -0,0 +1,93 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_FileAttributesImpl.h + * @brief This is the header file for the %_FileAttributesImpl class. + * + * This header file contains the declarations of the %_FileAttributesImpl class. + */ + +#ifndef _FIO_INTERNAL_FILEATTRIBUTES_IMPL_H_ +#define _FIO_INTERNAL_FILEATTRIBUTES_IMPL_H_ + +#include + +namespace Tizen {namespace Base +{ +class String; +class ByteBuffer; +}} + +namespace Tizen { namespace Io +{ + +class _FileAttributesImpl + : public Tizen::Base::Object +{ + +public: + _FileAttributesImpl(void); + + virtual ~_FileAttributesImpl(void); + + _FileAttributesImpl(const _FileAttributesImpl& fileAttributesImpl); + + _FileAttributesImpl& operator =(const _FileAttributesImpl& fileAttributesImpl); + + static _FileAttributesImpl* GetInstance(FileAttributes& fileAttributes); + + static const _FileAttributesImpl* GetInstance(const FileAttributes& fileAttributes); + + virtual bool Equals(const Tizen::Base::Object& object) const; + + int GetHashCode(void) const; + + long long GetFileSize(void) const; + + bool IsDirectory(void) const; + + bool IsHidden(void) const; + + bool IsReadOnly(void) const; + + Tizen::Base::DateTime GetDateTime(void) const; + + Tizen::Base::DateTime GetLastModifiedTime(void) const; + +private: + void Set(const Tizen::Base::DateTime& dateTime, const Tizen::Base::DateTime& modifiedTime, long long fileSize, + unsigned long attribute, bool hidden); + +private: + long long __fileSize; + bool __directory; + bool __hidden; + bool __readOnly; + Tizen::Base::DateTime __creationTime; + Tizen::Base::DateTime __lastModifiedTime; + + friend class FileAttributes; + friend class _NormalFile; + friend class _FileUtil; + +}; // _FileAttributesImpl + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_FILEATTRIBUTES_IMPL_H_ + diff --git a/src/io/inc/FIo_FileEventManagerImpl.h b/src/io/inc/FIo_FileEventManagerImpl.h new file mode 100644 index 0000000..1e87910 --- /dev/null +++ b/src/io/inc/FIo_FileEventManagerImpl.h @@ -0,0 +1,88 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_FileEventManagerImpl.h + * @brief This is the header file for the %_FileEventManagerImpl class. + * + * This header file contains the declarations of the %_FileEventManagerImpl class. + */ + +#ifndef _FIO_INTERNAL_FILE_EVENT_MANAGER_IMPL_H_ +#define _FIO_INTERNAL_FILE_EVENT_MANAGER_IMPL_H_ + +#include + +#include +#include +#include + +namespace Tizen { namespace Base +{ +class String; +}} + +namespace Tizen { namespace Io +{ + +class FileEventManager; +class IFileEventListener; + +class _OSP_EXPORT_ _FileEventManagerImpl + : public Tizen::Base::Object +{ + +public: + _FileEventManagerImpl(void); + + virtual ~_FileEventManagerImpl(void); + + result Construct(IFileEventListener& listener); + + result AddPath(const Tizen::Base::String& path, unsigned long eventsToMonitor); + + result RemovePath(const Tizen::Base::String& path); + + result SendEvent(void); + + static _FileEventManagerImpl* GetInstance(FileEventManager& fileEventManager); + + static const _FileEventManagerImpl* GetInstance(const FileEventManager& fileEventManager); + +private: + _FileEventManagerImpl(const _FileEventManagerImpl& source); + + _FileEventManagerImpl& operator =(const _FileEventManagerImpl& source); + + Tizen::Base::String GetRegisteredPath(int fd); + + static gboolean OnFileEventOccured(GIOChannel* source, GIOCondition condition, gpointer data); + + Tizen::Base::Collection::HashMap* __pMonitorFileList; + IFileEventListener* __pFileEventListener; + int __inotifyFd; + GSource* __pGSource; + GIOChannel* __pGIOChannel; + + friend class FileEventManager; + +}; // _FileEventManagerImpl + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_FILE_EVENT_MANAGER_IMPL_H_ + diff --git a/src/io/inc/FIo_FileImpl.h b/src/io/inc/FIo_FileImpl.h new file mode 100644 index 0000000..bba297e --- /dev/null +++ b/src/io/inc/FIo_FileImpl.h @@ -0,0 +1,207 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_FileImpl.h + * @brief This is the header file for the %_FileImpl class. + * + * This header file contains the declarations of the %_FileImpl class. + */ + +#ifndef _FIO_INTERNAL_FILE_IMPL_H_ +#define _FIO_INTERNAL_FILE_IMPL_H_ + +#include +#include +#include +#include + +namespace Tizen {namespace Base +{ +class String; +class ByteBuffer; +}} + +namespace Tizen { namespace Io +{ + +class File; +class FileAttributes; +class _NormalFile; +class _SecureFile; +class _IFileCore; + +#define MAX_FILEPATH_APP 18 +#define MAX_FILEPATH_MEDIA 2 +#define MAX_FILEPATH_SYSTEM 2 + +/** + * @enum _FilePathType + * Defines various file path types supported. + * + * @since 2.1 + */ +enum _FilePathType +{ + FILEPATH_TYPE_INVALID, // invalid case + FILEPATH_TYPE_APP, // for paths like /home, /Res, /Share etc. + FILEPATH_TYPE_MEDIA, // for paths like /Media,/Storagecard/Media, /Media/Images, /Media/xxx etc. + FILEPATH_TYPE_SYSTEM // for paths like /SystemRw, /Tmp etc. +}; + +class _OSP_EXPORT_ _FileImpl + : public Tizen::Base::Object +{ + +public: + _FileImpl(void); + + result Construct(const Tizen::Base::String& filePath, const Tizen::Base::String& openMode, bool createParentDirectories, const Tizen::Base::ByteBuffer* pSecretKey); + + result Construct(const Tizen::Base::String& filePath, const char* pOpenMode, const Tizen::Base::ByteBuffer* pSecretKey); + + virtual ~_FileImpl(void); + + result Read(Tizen::Base::ByteBuffer& buffer); + + int Read(void* buffer, int length); + + result ReadN(char** buffer, int& length); + + result Read(Tizen::Base::String& buffer); + + result Write(const Tizen::Base::ByteBuffer& buffer); + + result Write(const void* buffer, int length); + + result Write(const Tizen::Base::String& buffer); + + result Flush(void); + + int Tell(void) const; + + result Seek(FileSeekPosition position, long offset); + + result Truncate(int length); + + Tizen::Base::String GetName(void) const; + + FILE* GetFilePointer(void) const; + + static result Remove(const Tizen::Base::String& filePath); + + static result Move(const Tizen::Base::String& oldFilePath, const Tizen::Base::String& newFilePath); + + static result Copy(const Tizen::Base::String& srcFilePath, const Tizen::Base::String& destFilePath, bool failIfExist); + + static result GetAttributes(const Tizen::Base::String& filePath, FileAttributes& attribute); + + static Tizen::Base::String GetFileName(const Tizen::Base::String& filePath); + + static Tizen::Base::String GetFileExtension(const Tizen::Base::String& filePath); + + static bool IsFileExist(const Tizen::Base::String& filePath); + + static result ConvertToSecureFile(const Tizen::Base::String& plainFilePath, const Tizen::Base::String& secureFilePath, const Tizen::Base::ByteBuffer& key); + + static bool IsAppPath(const Tizen::Base::String& filePath); + + static bool IsMediaPath(const Tizen::Base::String& filePath); + + static bool IsSystemPath(const Tizen::Base::String& filePath); + + static bool PrepareDataCaging(const Tizen::Base::String& appRootPath, const Tizen::Base::String& pkgId); // for 2.0 app + + static bool FinalizeDataCaging(const Tizen::Base::String& appRootPath); // for 2.0 app + + static bool CreateOspApplicationDirectories(const Tizen::Base::String& appRootpath, const Tizen::Base::String& pkgId); // for 2.1 app + + static int GetAvailableUid(void); + + static bool VerifyFilePathCompatibility(const Tizen::Base::String& filePath, bool ospCompat); + + static _FileImpl* GetInstance(File& file); + + static const _FileImpl* GetInstance(const File& file); + + /** + * Converts the virtual path to the physical path. + * + * @since 2.1 + * @return An error code + * @param[in] virtualPath The path used by applications with API version 2.0 + * @param[out] physicalPath The physical absolute path + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c virtualPath is not valid. + */ + static result ConvertVirtualToPhysicalPath(const Tizen::Base::String& virtualPath, Tizen::Base::String& physicalPath); + + /** + * Converts the physical path to the virtual path. + * + * @since 2.1 + * @return An error code + * @param[in] physicalPath The physical absolute path + * @param[out] virtualPath The path used by applications with API version 2.0 + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified @c physicalPath is not valid. + */ + static result ConvertPhysicalToVirtualPath(const Tizen::Base::String& physicalPath, Tizen::Base::String& virtualPath); + + bool IsReadable(void) const + { + return __read; + } + + bool IsWritable(void) const + { + return __write; + } + +private: + _FileImpl& operator =(const _FileImpl& source); + + _FileImpl(const _FileImpl& source); + + bool VerifyFileOpenMode(const char* pOpenMode); + + static bool VerifyFilePath(const Tizen::Base::String& filePath, _FilePathType pathType); + + static bool CreateOspInternalDirectories(const Tizen::Base::String& pkgId); + + static bool CreateOspExternalDirectories(const Tizen::Base::String& pkgId); + + static bool CreateSlpDirectories(void); + + static bool CreateSymbolicLink(void); + + static bool CleanDirectories(const Tizen::Base::String& appRootPath, const Tizen::Base::String& pkgId); + + _IFileCore* __pCore; + bool __read; + bool __write; + bool __truncate; + bool __append; + + friend class File; + +}; // _FileImpl + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_FILE_IMPL_H_ + diff --git a/src/io/inc/FIo_FileUtil.h b/src/io/inc/FIo_FileUtil.h new file mode 100644 index 0000000..16e247c --- /dev/null +++ b/src/io/inc/FIo_FileUtil.h @@ -0,0 +1,68 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_FileUtil.h + * @brief This is the header file for the _FileUtil class. + * + * This header file contains the declarations of the %_FileUtil class. + */ + +#ifndef _FIO_INTERNAL_FILEUTIL_H_ +#define _FIO_INTERNAL_FILEUTIL_H_ + +#include + +namespace Tizen { namespace Io +{ + +class _FileUtil +{ + +public: + static result Remove(const Tizen::Base::String& filePath); + + static result Move(const Tizen::Base::String& oldFilePath, const Tizen::Base::String& newFilePath); + + static result Copy(const Tizen::Base::String& srcFilePath, const Tizen::Base::String& destFilePath, bool failIfExist); + + static result GetAttributes(const Tizen::Base::String& filePath, Tizen::Io::FileAttributes& attribute); + + static Tizen::Base::String GetFileName(const Tizen::Base::String& filePath); + + static Tizen::Base::String GetFileExtension(const Tizen::Base::String& filePath); + + static bool IsFileExist(const Tizen::Base::String& filePath); + + static bool IsAppPath(const Tizen::Base::String& filePath); + + static bool IsMediaPath(const Tizen::Base::String& filePath); + + static bool IsSystemPath(const Tizen::Base::String& filePath); + + static bool VerifyFilePath(const Tizen::Base::String& filePath, Tizen::Io::_FilePathType pathType); + + static bool VerifyFileOpenMode(const Tizen::Base::String& openMode); + + static result ConvertToSecureFile(const Tizen::Base::String& plainFilePath, const Tizen::Base::String& secureFilePath, const Tizen::Base::ByteBuffer* pKey = null); + +}; // _FileUtil + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_FILEUTIL_H_ + diff --git a/src/io/inc/FIo_IChannelRequestEventListener.h b/src/io/inc/FIo_IChannelRequestEventListener.h new file mode 100644 index 0000000..daec94f --- /dev/null +++ b/src/io/inc/FIo_IChannelRequestEventListener.h @@ -0,0 +1,50 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IChannelRequestEventListener.h + * @brief This is the header file for the _IChannelRequestEventListener class. + * + * This file contains the declarations of _IChannelRequestEventListener. + */ + + +#ifndef _FIO_INTERNAL_ICHANNEL_REQUEST_EVENT_LISTENER_H_ +#define _FIO_INTERNAL_ICHANNEL_REQUEST_EVENT_LISTENER_H_ + +// Includes +#include +#include +#include + +namespace Tizen { namespace Io +{ + +// Forward declarations +class _ServerChannel; + +class _OSP_EXPORT_ _IChannelRequestEventListener + : public Tizen::Base::Runtime::IEventListener +{ +public: + virtual void OnChannelRequestReceivedN(RequestId reqId, const Tizen::Base::String& channelId + , Tizen::Base::Collection::IList* pArgs) = 0; +}; + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_ICHANNEL_RESPONSE_EVENT_LISTENER_H_ diff --git a/src/io/inc/FIo_IChannelResponseEventListener.h b/src/io/inc/FIo_IChannelResponseEventListener.h new file mode 100644 index 0000000..ac6b922 --- /dev/null +++ b/src/io/inc/FIo_IChannelResponseEventListener.h @@ -0,0 +1,49 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IChannelResponseEventListener.h + * @brief This is the header file for the _IChannelResponseEventListener class. + * + * This file contains the declarations of _IChannelResponseEventListener. + */ + +#ifndef _FIO_INTERNAL_ICHANNEL_RESPONSE_EVENT_LISTENER_H_ +#define _FIO_INTERNAL_ICHANNEL_RESPONSE_EVENT_LISTENER_H_ + +// Includes +#include +#include + +namespace Tizen { namespace Io +{ + +class _ClientChannel; + +class _IChannelResponseEventListener + : public Tizen::Base::Runtime::IEventListener +{ +public: + virtual ~_IChannelResponseEventListener(void){} + + virtual void OnChannelResponseReceivedN(RequestId reqId, const Tizen::Base::String& channelId + , Tizen::Base::Collection::IList* pArgs) = 0; +}; + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_ICHANNEL_RESPONSE_EVENT_LISTENER_H_ diff --git a/src/io/inc/FIo_IChannelService.h b/src/io/inc/FIo_IChannelService.h new file mode 100644 index 0000000..692d1a8 --- /dev/null +++ b/src/io/inc/FIo_IChannelService.h @@ -0,0 +1,69 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IChannelService.h + * @brief This is the header file for the _IChannelService class. + * + * This file contains the declarations of _IChannelService. + */ + + +#ifndef _FIO_INTERNAL_ICHANNEL_SERVICE_H_ +#define _FIO_INTERNAL_ICHANNEL_SERVICE_H_ + +#include +#include +#include +#include "FIo_IChannelServiceEventListener.h" + +namespace Tizen { namespace Io +{ + +class _IChannelService +{ +public: + virtual ~_IChannelService(void) {} + + virtual result RegisterChannel(const Tizen::Base::String& channelId, const _IChannelServiceEventListener& listener) = 0; + + virtual result UnregisterChannel(const Tizen::Base::String& channelId) = 0; + + virtual result SendRequest(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + const Tizen::Base::Collection::ArrayList& args, + int messageId) = 0; + + virtual result SendNullRequest(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int messageId) = 0; + + virtual result SendResponse(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + const Tizen::Base::Collection::ArrayList& args, + int messageId) = 0; + + virtual result SendNullResponse(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int messageId) = 0; + +}; // _IChannelService + + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_ICHANNEL_SERVICE_H_ diff --git a/src/io/inc/FIo_IChannelServiceEventListener.h b/src/io/inc/FIo_IChannelServiceEventListener.h new file mode 100644 index 0000000..748b44f --- /dev/null +++ b/src/io/inc/FIo_IChannelServiceEventListener.h @@ -0,0 +1,51 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IChannelServiceEventListener.h + * @brief This is the header file for the _IChannelServiceEventListener class. + * + * This file contains the declarations of _IChannelServiceEventListener. + */ + + +#ifndef _FIO_INTERNAL_ICHANNEL_SERVICE_EVENT_LISTENER_H_ +#define _FIO_INTERNAL_ICHANNEL_SERVICE_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +class _IChannelServiceEventListener +{ +public: + virtual ~_IChannelServiceEventListener(void) {} + + virtual bool OnChannelRequestReceivedN(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int requestId, Tizen::Base::Collection::ArrayList* pArgs) = 0; + + virtual bool OnChannelResponseReceivedN(const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int requestId, Tizen::Base::Collection::ArrayList* pArgs) = 0; +}; + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_ICHANNEL_SERVICE_EVENT_LISTENER_H_ diff --git a/src/io/inc/FIo_IChannelServiceStub.h b/src/io/inc/FIo_IChannelServiceStub.h new file mode 100644 index 0000000..fe53ca7 --- /dev/null +++ b/src/io/inc/FIo_IChannelServiceStub.h @@ -0,0 +1,63 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IChannelServiceStub.h + * @brief This is the header file for the _IChannelServiceStub class. + * + * This file contains the declarations of _IChannelServiceStub. + */ + + +#ifndef _FIO_INTERNAL_ICHANNEL_SERVICE_STUB_H_ +#define _FIO_INTERNAL_ICHANNEL_SERVICE_STUB_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +class _ChannelService; + +class _IChannelServiceStub +{ +public: + virtual ~_IChannelServiceStub(void) {} + + virtual result SendRequest(int clientId, const Tizen::Base::String& src, + const Tizen::Base::String& dest, + const Tizen::Base::Collection::ArrayList& data, int requestId) = 0; + virtual result SendNullRequest(int clientId, const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int requestId) = 0; + + virtual result SendResponse(int clientId, const Tizen::Base::String& src, + const Tizen::Base::String& dest, + const Tizen::Base::Collection::ArrayList& data, int requestId) = 0; + virtual result SendNullResponse(int clientId, const Tizen::Base::String& src, + const Tizen::Base::String& dest, + int requestId) = 0; + + virtual void SetChannelService(_ChannelService& service) = 0; + +}; // _IChannelServiceStub + + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_CHANNEL_SERVICE_STUB_H_ diff --git a/src/io/inc/FIo_IDataRouterEventListener.h b/src/io/inc/FIo_IDataRouterEventListener.h new file mode 100644 index 0000000..526ae7b --- /dev/null +++ b/src/io/inc/FIo_IDataRouterEventListener.h @@ -0,0 +1,54 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IDataRouterEventListener.h + * @brief This is the header file for the %_IDataRouterEventListener class. + * + * This header file contains the declarations of the %_IDataRouterEventListener class. + */ + +#ifndef _FIO_DATAROUTER_EVENT_LISTENER_H_ +#define _FIO_DATAROUTER_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +/** + * @interface _IDataRouterEventListener + * @brief This interface is an event listener used to receive serial port event synchronously. + * + * The listener interface for data router events. + */ + +class _OSP_EXPORT_ _IDataRouterEventListener + : public Tizen::Base::Runtime::IEventListener +{ + +public: + virtual void OnDataRouterDataReceivedN(const char* buffer, int length) = 0; + virtual void OnDataRouterStateChanged(_DataRouterState state) = 0; + +}; // _IDataRouterEventListener + +}} // Tizen::Io + +#endif // _FIO_DATAROUTER_EVENT_LISTENER_H_ + diff --git a/src/io/inc/FIo_IDbUserListener.h b/src/io/inc/FIo_IDbUserListener.h new file mode 100644 index 0000000..f2f13df --- /dev/null +++ b/src/io/inc/FIo_IDbUserListener.h @@ -0,0 +1,227 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// This method is for internal use only. The Tizen platform team is not +// responsible for any behavioral correctness, consistency, and +// security-related issues that might arise after using this method. +// +// @file FIo_IDbUserListener.h +// @brief This is the header file for the %_IDbUserFunctionListener, +// %_IDbUserAggregateListener, and %_IUserCollationCompareListener classes. +// +// This header file contains the declarations of the %_IDbUserFunctionListener +// %_IDbUserAggregateListener, and %_IUserCollationCompareListener classes. + +#ifndef _FIO_INTERNAL_IDB_USER_LISTENER_H_ +#define _FIO_INTERNAL_IDB_USER_LISTENER_H_ + +#include +#include +#include + +namespace Tizen { namespace Io +{ + +// This method is for internal use only. The Tizen platform team is not +// responsible for any behavioral correctness, consistency, and +// security-related issues that might arise after using this method. +// +// @interface _IDbUserFunctionListener +// @brief This interface defines a listener for the user defined SQL function. +// @since 2.1 + +class _OSP_EXPORT_ _IDbUserFunctionListener + : public Tizen::Base::Runtime::IEventListener +{ +public: + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Called when the user defined SQL function is executed. + // + // @since 2.1 + // @param[in] context The database context + // @param[in] argumentCount The number of the user defined SQL function + // @see Tizen::Io::_DbContextImpl + // + virtual void OnDbUserFunction(_DbContextImpl& context, int argumentCount) = 0; + +protected: + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserFunctionListener_Reserverd1(void) {} + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserFunctionListener_Reserverd2(void) {} + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserFunctionListener_Reserverd3(void) {} + +}; // IDbUserFunctionListener + +// This method is for internal use only. The Tizen platform team is not +// responsible for any behavioral correctness, consistency, and +// security-related issues that might arise after using this method. +// +// @interface _IDbUserAggregateListener +// @brief This interface defines a listener for the user defined SQL aggregate. +// @since 2.1 +class _OSP_EXPORT_ _IDbUserAggregateListener + : public Tizen::Base::Runtime::IEventListener +{ +public: + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Called when the user defined SQL aggregate is executed for each row in the result. + // + // @since 2.1 + // @param[in] context The database context + // @param[in] argumentCount The number of the user defined SQL function + // @see Tizen::Io::_DbContextImpl + // + virtual void OnDbUserAggregateStep(_DbContextImpl& context, int argumentCount) = 0; + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Called when the user defined SQL aggregate is executed at the end of the row in the result. + // + // @since 2.1 + // @param[in] context The database context + // @see Tizen::Io::_DbContextImpl + // + virtual void OnDbUserAggregateFinal(_DbContextImpl& context) = 0; + +protected: + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserAggregateListener_Reserved1(void) {} + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserAggregateListener_Reserved2(void) {} + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserAggregateListener_Reserved3(void) {} + +}; // IDbUserAggregateListener + +// This method is for internal use only. The Tizen platform team is not +// responsible for any behavioral correctness, consistency, and +// security-related issues that might arise after using this method. +// +// @interface _IDbUserCollationListener +// @brief This interface defines a listener for the user defined SQL collation. +// @since 2.1 + +class _OSP_EXPORT_ _IDbUserCollationListener + : public Tizen::Base::Runtime::IEventListener +{ +public: + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Called when the user defined SQL collating function is executed. + // + // @since 2.1 + // @return Negative, zero, positive if the first string is less than, equal to, + // or greater than the second string, respectively. + // @param[in] string1 The first Stirng value to be compared + // @param[in] string2 The second String value to be compared + // @param[in] pUserData User data passed from Database::CreateCollation() + virtual int OnDbUserCollation(const Tizen::Base::String& string1, const Tizen::Base::String& string2, void* pUserData) = 0; + +protected: + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserCollationListener_Reserved1(void) {} + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserCollationListener_Reserved2(void) {} + + // This method is for internal use only. The Tizen platform team is not + // responsible for any behavioral correctness, consistency, and + // security-related issues that might arise after using this method. + // + // Following method is reserved and may change its name at any time without prior notice. + // + // @since 2.1 + // + virtual void _IDbUserCollationListener_Reserved3(void) {} + +}; // _IDbUserCollationListener + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_IDB_USER_LISTENER_H_ + diff --git a/src/io/inc/FIo_IFileCore.h b/src/io/inc/FIo_IFileCore.h new file mode 100644 index 0000000..21771ea --- /dev/null +++ b/src/io/inc/FIo_IFileCore.h @@ -0,0 +1,83 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IFileCore.h + * @brief This is the header file for the _IFileCore class. + * + * This header file contains the declarations of the %_IFileCore class. + */ + +#ifndef _FIO_INTERNAL_IFILECORE_H_ +#define _FIO_INTERNAL_IFILECORE_H_ + +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class _IFileCore +{ + +public: + _IFileCore(void) + : _read(false) + , _write(false) + , _truncate(false) + , _append(false) + {} + + virtual ~_IFileCore(void) {} + + virtual result Read(Tizen::Base::ByteBuffer& buffer) = 0; + + virtual int Read(void* buffer, int length) = 0; + + virtual result Read(Tizen::Base::String& buffer) = 0; + + virtual result Write(const Tizen::Base::ByteBuffer& buffer) = 0; + + virtual result Write(const void* buffer, int length) = 0; + + virtual result Write(const Tizen::Base::String& buffer) = 0; + + virtual result Flush(void) = 0; + + virtual int Tell(void) const = 0; + + virtual result Seek(FileSeekPosition position, long offset) = 0; + + virtual result Truncate(int length) = 0; + + virtual Tizen::Base::String GetName(void) = 0; + + virtual FILE* GetFilePointer(void) = 0; + +protected: + bool _read; + bool _write; + bool _truncate; + bool _append; + +}; // _IFileCore + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_IFILECORE_H_ + diff --git a/src/io/inc/FIo_IIpcClientEventListener.h b/src/io/inc/FIo_IIpcClientEventListener.h new file mode 100644 index 0000000..67ae9ed --- /dev/null +++ b/src/io/inc/FIo_IIpcClientEventListener.h @@ -0,0 +1,67 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IIpcClientEventListener.h + * @brief This is the header file for the _IIpcClientEventListener class. + * + * This file contains the declarations of _IIpcClientEventListener. + */ + +#ifndef _FIO_INTERNAL_IIPC_CLIENT_EVENT_LISTENER_H_ +#define _FIO_INTERNAL_IIPC_CLIENT_EVENT_LISTENER_H_ + +#include + +namespace IPC { class Message; } + +namespace Tizen { namespace Io +{ + +class _IpcClient; + +/** + * @interface _IIpcClientEventListener + * @brief This interface provides the listener method for the response from IPC server. + * since 3.0 + */ +class _OSP_EXPORT_ _IIpcClientEventListener + : Tizen::Base::Runtime::IEventListener +{ +public: + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_IIpcClientEventListener(void); + + /** + * Called when an IPC response message received. + * + * @since 2.1 + * @param[in] client The IPC client + * @param[in] message The response message + */ + virtual void OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message) = 0; +}; // _IIpcClientEventListener + + +} } // Tizen::Io + +#endif //_FIO_INTERNAL_IIPC_CLIENT_EVENT_LISTENER_H_ diff --git a/src/io/inc/FIo_IIpcServerEventListener.h b/src/io/inc/FIo_IIpcServerEventListener.h new file mode 100644 index 0000000..9f88a13 --- /dev/null +++ b/src/io/inc/FIo_IIpcServerEventListener.h @@ -0,0 +1,127 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IIpcServerEventListener.h + * @brief This is the header file for the _IIpcServerEventListener class. + * + * This file contains the declarations of _IIpcServerEventListener. + */ + +#include +#include + +#ifndef _FIO_INTERNAL_IIPC_SERVER_EVENT_LISTENER_H_ +#define _FIO_INTERNAL_IIPC_SERVER_EVENT_LISTENER_H_ + +namespace IPC { class Message; } + +namespace Tizen { namespace Io +{ + +class _IpcServer; +/** + * @interface _IIpcServerEventListener + * @brief This interface provides listener method for the request event from an IPC client. + * since 3.0 + */ +class _OSP_EXPORT_ _IIpcServerEventListener + : virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_IIpcServerEventListener(void); + + /** + * Called when an IPC server started. + * + * @since 2.1 + * @param[in] server The IPC server + */ + virtual void OnIpcServerStarted(const _IpcServer& server) = 0; + + /** + * Called when an IPC server stopped. + * + * @since 2.1 + * @param[in] server The IPC server + */ + virtual void OnIpcServerStopped(const _IpcServer& server) = 0; + + /** + * Called when an IPC client connected. + * + * @since 2.1 + * @param[in] server The IPC server + */ + virtual void OnIpcClientConnected(const _IpcServer& server, int clientId) = 0; + + /** + * Called when an IPC client disconnected. + * + * @since 2.1 + * @param[in] server The IPC server + * @param[in] clientId The id of the connected IPC client + */ + virtual void OnIpcClientDisconnected(const _IpcServer& server, int clientId) = 0; + + /** + * Called when an IPC request message received. + * + * @since 2.1 + * @code + * + * bool + * CalculatorStub::OnSumRequested(int a, int b, int* pC) + * { + * *pC = a + b; + * return true; + * } + * + * bool + * CalculatorStub::OnMultiplyRequested(int a, int b, int* pC) + * { + * *pC = a * b; + * return true; + * } + * + * bool + * CalculatorStub::OnIpcRequestReceived(_IpcServer& server, const IPC::Message& message) + * { + * IPC_BEGIN_MESSAGE_MAP(CalculatorStub, message) + * IPC_MESSAGE_HANDLER(My_sum, OnSumRequested, &server) + * IPC_MESSAGE_HANDLER(My_mul, OnMultiplyRequested, &server) + * IPC_END_MESSAGE_MAP() + * + * return true; + * } + * + * @endcode + * @param[in] server The IPC server + * @param[in] message The received message + */ + virtual void OnIpcRequestReceived(_IpcServer& server, const IPC::Message& message) = 0; +}; // _IIpcServerEventListener + + +} } // Tizen::Io + +#endif //_FIO_IIPCSERVEREVENTLISTENER_H_ diff --git a/src/io/inc/FIo_IMessagePortListener.h b/src/io/inc/FIo_IMessagePortListener.h new file mode 100644 index 0000000..fcd61cd --- /dev/null +++ b/src/io/inc/FIo_IMessagePortListener.h @@ -0,0 +1,48 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IMessagePortRequestEventListener.h + * @brief This is the header file for the _IMessagePortRequestEventListener class. + * + * This file contains the declarations of _IMessagePortRequestEventListener. + */ + + +#ifndef _FIO_INTERNAL_IMESSAGE_PORT_LISTENER_H_ +#define _FIO_INTERNAL_IMESSAGE_PORT_LISTENER_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class _OSP_EXPORT_ _IMessagePortListener + : public Tizen::Base::Runtime::IEventListener +{ +public: + virtual void OnMessageReceivedN(Tizen::Base::Collection::IMap* pMap) = 0; + + virtual void OnMessageReceivedN(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remotePort, bool isTrusted, Tizen::Base::Collection::IMap* pMap) = 0; +}; + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_IMESSAGE_PORT_LISTENER_H_ diff --git a/src/io/inc/FIo_IMmcStorageServiceEventListener.h b/src/io/inc/FIo_IMmcStorageServiceEventListener.h new file mode 100644 index 0000000..431e278 --- /dev/null +++ b/src/io/inc/FIo_IMmcStorageServiceEventListener.h @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IMmcStorageServiceEventListener.h + * @brief This is the header file for the _IMmcStorageServiceEventListener class. + */ + +#ifndef _FIO_INTERNAL_IIO_MMC_STORAGE_SERVICE_EVENT_LISTENER_H_ +#define _FIO_INTERNAL_IIO_MMC_STORAGE_SERVICE_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +/** + * @interface _IMmcStorageServiceEventListener + * @brief This interface defines the listener for the events from _MmcStorageManagerService + * @since 2.1 + * + * Application should not implement this interface. + */ +class _OSP_EXPORT_ _IMmcStorageServiceEventListener + : virtual public Tizen::Base::Runtime::IEventListener +{ +public: + + ~_IMmcStorageServiceEventListener(void) {} + + virtual result OnMmcMountResponseReceived(result r) = 0; + + virtual result OnMmcUnmountResponseReceived(result r) = 0; + + virtual result OnMmcFormatResponseReceived(result r) = 0; +}; // _MmcStorageServiceEventListener + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_IIO_MMC_STORAGE_SERVICE_EVENT_LISTENER_H_ diff --git a/src/io/inc/FIo_IpcClient.h b/src/io/inc/FIo_IpcClient.h new file mode 100644 index 0000000..4503a47 --- /dev/null +++ b/src/io/inc/FIo_IpcClient.h @@ -0,0 +1,158 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IpcClient.h + * @brief This is the header file for the _IpcClient class. + * + * This file contains the declarations of _IpcClient. + */ + + +#ifndef _FIO_INTERNAL_IPC_CLIENT_H_ +#define _FIO_INTERNAL_IPC_CLIENT_H_ + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + + +namespace Tizen { namespace Base { namespace Runtime +{ +class Mutex; +}}} +namespace Tizen { namespace Io +{ + +class _IIpcClientEventListener; + +/** + * @class _IpcClient + * @brief This class provides methods for sending a message to an IPC server. + * @since 2.1 + * + */ +class _OSP_EXPORT_ _IpcClient + : Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * @since 2.1 + */ + _IpcClient(void); + + /** + * This is the destructor for this class. + * @since 2.1 + */ + virtual ~_IpcClient(void); + + /** + * Constructs the instance of this class. + * + * @since 2.1 + * + * @return An error code + * @param[in] serverName The name of the server + * @param[in] pListener Set if the client want to handle a message from the IPC server. + * @c null, otherwise. + * @exception E_SUCCESS The method was successful. + * @exception E_OBJ_NOT_FOUND The IPC server was not found. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_SYSTEM A system error occurred. + */ + result Construct(const Tizen::Base::String& serverName, const _IIpcClientEventListener* pListener = null); + + /** + * Sends a request message to an IPC server. + * + * @since 2.1 + * @code + * + * + * int + * CalculatorProxy::Add(int a , int b) + * { + * int c = 0; + * + * My_sum mySum(a, b, &c); + * + * __pIpcClient->SendRequest(mySum); + * + * return c; + * } + * + * @endcode + * @return An error code + * @param[in] message The message to send + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_STATE The instance is in an invalid state. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_SYSTEM A system error occurred. + * + */ + result SendRequest(const IPC::Message& message); + + result SendRequest(IPC::Message* pMessage); + +private: + _IpcClient(const _IpcClient& value); + + _IpcClient& operator =(const _IpcClient& value); + + result Send(IPC::Message* pMessage); + + result SendAsync(IPC::Message* pMessage); + + result SendSync(IPC::Message* pMessage); + + result MakeConnection(bool forReverse = false); + + int AcquireFd(void); + + void ReleaseFd(int fd); + + static gboolean OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data); + + gboolean HandleReceivedMessage(GIOChannel* source, GIOCondition condition); + +private: + GSource* __pReverseSource; + + std::vector __fds; + int __fdCount; + Tizen::Base::Runtime::Mutex* __pFdLock; + Tizen::Base::String __name; + _IIpcClientEventListener* __pListener; + + static const int __MAX_MESSAGE_BUFFER_SIZE = 1024; + char __messageBuffer[__MAX_MESSAGE_BUFFER_SIZE]; + std::string __pending; +}; + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_IPC_CLIENT_H_ diff --git a/src/io/inc/FIo_IpcCommonDataTypes.h b/src/io/inc/FIo_IpcCommonDataTypes.h new file mode 100644 index 0000000..c748e68 --- /dev/null +++ b/src/io/inc/FIo_IpcCommonDataTypes.h @@ -0,0 +1,37 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IpcCommonDataTypes.h + * @brief This is the header file for common data types for IPC. + */ + +#ifndef _FIO_INTERNAL_IPC_COMMON_DATA_TYPES_H +#define _FIO_INTERNAL_IPC_COMMON_DATA_TYPES_H + +namespace Tizen { namespace Io +{ + +typedef struct +{ + int size; + void* pBuffer; +}_IpcBuffer; + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_CLIENT_CHANNEL_H_ diff --git a/src/io/inc/FIo_IpcCommonParamTraits.h b/src/io/inc/FIo_IpcCommonParamTraits.h new file mode 100644 index 0000000..1eafe5e --- /dev/null +++ b/src/io/inc/FIo_IpcCommonParamTraits.h @@ -0,0 +1,334 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IpcCommonParamTraits.h + * @brief This is the header file for common param traits. + */ + +#ifndef _FIO_INTERNAL_IPC_COMMON_PARAM_TRAITS_H_ +#define _FIO_INTERNAL_IPC_COMMON_PARAM_TRAITS_H_ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include "FIo_IpcCommonDataTypes.h" + +namespace IPC +{ + +const static int IPC_OBJECT_TYPE_STRING = 0; +const static int IPC_OBJECT_TYPE_BYTE_BUFFER = 1; + +template<> +struct ParamTraits +{ + typedef Tizen::Base::String param_type; + + static void Write(Message* m, const param_type& p) + { + int len = (p.GetLength() + 1) * sizeof(wchar_t); + m->WriteInt(len); + m->WriteBytes((void*) p.GetPointer(), (p.GetLength() + 1) * sizeof(wchar_t)); + } + + static bool Read(const Message* m, void** iter, param_type* r) + { + const char* pStr = null; + int len = 0; + + if (!m->ReadLength(iter, &len)) + { + return false; + } + + m->ReadBytes(iter, &pStr, len); + r->Clear(); + r->Append((wchar_t*) pStr); + + return true; + } + + static void Log(const param_type& p, std::string* l) + { + } +}; + +template<> +struct ParamTraits +{ + typedef Tizen::Base::ByteBuffer param_type; + + static void Write(Message* m, const param_type& p) + { + int capacity = p.GetCapacity(); + + m->WriteInt(capacity); + m->WriteBytes((void*) p.GetPointer(), capacity); + m->WriteInt(p.GetLimit()); + m->WriteInt(p.GetPosition()); + } + + static bool Read(const Message* m, void** iter, param_type* r) + { + const byte* pByte = null; + int capacity = 0; + int value = 0; + + if (!m->ReadLength(iter, &capacity)) + { + return false; + } + r->Construct(capacity); + + m->ReadBytes(iter, (const char**)&pByte, capacity); + r->SetArray(pByte, 0, capacity); + + m->ReadLength(iter, &value); + if (r->SetLimit(value) != E_SUCCESS) + { + return false; + } + + m->ReadLength(iter, &value); + r->SetPosition(value); + + return true; + } + + static void Log(const param_type& p, std::string* l) + { + } +}; + +template<> +struct ParamTraits +{ + typedef Tizen::Base::Collection::ArrayList param_type; + + static void Write(Message* m, const param_type& p) + { + int count = p.GetCount(); + const Tizen::Base::String* pType = NULL; + + WriteParam(m, count); + + for (int i = 0; i < count; i++) + { + pType = dynamic_cast < const Tizen::Base::String* > (p.GetAt(i)); + if (pType) + { + WriteParam(m, IPC_OBJECT_TYPE_STRING); + WriteParam(m, *pType); + } + else + { + WriteParam(m, IPC_OBJECT_TYPE_BYTE_BUFFER); + WriteParam(m, *(Tizen::Base::ByteBuffer*) p.GetAt(i)); + } + } + } + + static bool Read(const Message* m, void** iter, param_type* r) + { + Tizen::Base::String* pStr = null; + Tizen::Base::ByteBuffer* pBuffer = null; + int count = 0; + int type = 0; + + if (!m->ReadLength(iter, &count)) + { + return false; + } + + r->Construct(count); + + for (int i = 0; i < count; i++) + { + m->ReadLength(iter, &type); + if (type == IPC_OBJECT_TYPE_STRING) + { + pStr = new Tizen::Base::String; + if (!ReadParam(m, iter, pStr)) + { + delete pStr; + return false; + } + r->Add(*pStr); + } + else + { + pBuffer = new Tizen::Base::ByteBuffer; + if (!ReadParam(m, iter, pBuffer)) + { + delete pBuffer; + return false; + } + r->Add(*pBuffer); + } + } + + return true; + } + + static void Log(const param_type& p, std::string* l) + { + } +}; + +template<> +struct ParamTraits +{ + typedef Tizen::Base::Collection::HashMap param_type; + + static void Write(Message* m, const param_type& p) + { + int count = p.GetCount(); + const Tizen::Base::String* pType = NULL; + + Tizen::Base::Collection::IList* pKeys = p.GetKeysN(); + Tizen::Base::Collection::IList* pValues = p.GetValuesN(); + + WriteParam(m, count); + + for (int i = 0; i < count; i++) + { + WriteParam(m, *(Tizen::Base::String*) pKeys->GetAt(i)); + + pType = dynamic_cast < const Tizen::Base::String* > (pValues->GetAt(i)); + if (pType) + { + WriteParam(m, IPC_OBJECT_TYPE_STRING); + WriteParam(m, *pType); + } + else + { + WriteParam(m, IPC_OBJECT_TYPE_BYTE_BUFFER); + WriteParam(m, *(Tizen::Base::ByteBuffer*) pValues->GetAt(i)); + } + } + + delete pKeys; + delete pValues; + } + + static bool Read(const Message* m, void** iter, param_type* r) + { + Tizen::Base::String* pKey = null; + Tizen::Base::String* pStr = null; + Tizen::Base::ByteBuffer* pBuffer = null; + + int count = 0; + int type = 0; + + if (!m->ReadLength(iter, &count)) + { + return false; + } + + r->Construct(count); + + for (int i = 0; i < count; i++) + { + pKey = new Tizen::Base::String(); + + if (!ReadParam(m, iter, pKey)) + { + delete pKey; + return false; + } + + m->ReadLength(iter, &type); + + if (type == IPC_OBJECT_TYPE_STRING) + { + pStr = new Tizen::Base::String(); + if (!ReadParam(m, iter, pStr)) + { + delete pKey; + delete pStr; + return false; + } + + r->Add(*pKey, *pStr); + } + else + { + pBuffer = new Tizen::Base::ByteBuffer(); + if (!ReadParam(m, iter, pBuffer)) + { + delete pKey; + delete pBuffer; + return false; + } + + r->Add(*pKey, *pBuffer); + } + + } + + return true; + } + + static void Log(const param_type& p, std::string* l) + { + } +}; + +template<> +struct ParamTraits +{ + typedef Tizen::Io::_IpcBuffer param_type; + + static void Write(Message* m, const param_type& p) + { + m->WriteInt(p.size); + m->WriteBytes((void*) p.pBuffer, p.size); + } + + static bool Read(const Message* m, void** iter, param_type* r) + { + const char* pBuffer = null; + int len = 0; + if (!m->ReadLength(iter, &len)) + { + return false; + } + + m->ReadBytes(iter, &pBuffer, len); + + r->size = len; + r->pBuffer = (void*) pBuffer; + + + return true; + } + + static void Log(const param_type& p, std::string* l) + { + } +}; + +} + +#endif // _FIO_INTERNAL_CLIENT_CHANNEL_H_ diff --git a/src/io/inc/FIo_IpcMessageStart.h b/src/io/inc/FIo_IpcMessageStart.h new file mode 100644 index 0000000..47d5d13 --- /dev/null +++ b/src/io/inc/FIo_IpcMessageStart.h @@ -0,0 +1,47 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IpcMessageStart.h + * @brief This is the header file for the ipc message. + */ + +#ifndef _FIO_IPC_MESSAGE_START_H_ +#define _FIO_IPC_MESSAGE_START_H_ + +enum IpcMessageStart { + ChannelServiceMsgStart, + MessagePortServiceStart, + AppManagerServiceStart, + ConditionManagerServiceStart, + PackageManagerServiceStart, + NotificationManagerServiceStart, + MmcStorageManagerServiceStart, + IoServiceStart, + LiveboxManagerServiceStart, + PrivilegeManagerMsgStart, + CertMgrServiceStart, + MdmServiceStart, + ConnectivityNetServiceMsgStart, + ConnectivityWifiServiceMsgStart, + ConnectivityBluetoothServiceMsgStart, + ConnectivityNfcServiceMsgStart, + ConnectivityTelephonyServiceMsgStart + //LastIPCMsgStart // Must come last. +}; + +#endif // _FIO_IPC_MESSAGE_START_H_ diff --git a/src/io/inc/FIo_IpcServer.h b/src/io/inc/FIo_IpcServer.h new file mode 100644 index 0000000..9d4b3a5 --- /dev/null +++ b/src/io/inc/FIo_IpcServer.h @@ -0,0 +1,243 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_IpcServer.h + * @brief This is the header file for the _IpcServer class. + * + * This file contains the declarations of _IpcServer. + */ + +#ifndef _FIO_INTERNAL_IPC_SERVER_H_ +#define _FIO_INTERNAL_IPC_SERVER_H_ + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace Tizen { namespace Base { namespace Runtime +{ +class _EventDispatcher; +}}} + +namespace Tizen { namespace Io +{ + +class _IIpcServerEventListener; + +/** + * @class _IpcServer + * @brief This class provides methods to handle IPC request messages. + * @since 2.1 + * + */ +class _OSP_EXPORT_ _IpcServer + : public Tizen::Base::Object +{ +public: + /** + * This is the default constructor for this class. + * @since 2.1 + */ + _IpcServer(void); + + /** + * This is the destructor for this class. + * @since 2.1 + */ + virtual ~_IpcServer(void); + + /** + * Constructs the instance of this class and starts the IPC server. + * + * @since 2.1 + * @return An error code + * @param[in] name The name of IPC server + * @param[in] listener The listener for IPC server + * @param[in] runOnCallerThread Set to @c true, if the server runs on the caller thread + * @c false, if the server runs on its own thread. + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_SYSTEM Occurs when runOnCallerThread is set to true where the caller thread is worker thread. + */ + result Construct(const Tizen::Base::String& name, const _IIpcServerEventListener& listener, bool runOnCallerThread = true); + + /** + * Returns the name of the IPC server. + * + * @since 2.1 + * @return The name of the IPC server. + */ + Tizen::Base::String GetName(void) const; + + /** + * Returns the id the of the client which sent a request message. + * + * @since 2.1 + * @return The id of the IPC client. + * @remark This can be called only in a message handler. + */ + int GetClientId(void) const; + + /** + * Returns the process id of the client which sent a request message. + * + * @since 2.1 + * @return The process id of the IPC client. + * @remark This can be called only in a message handler. + */ + int GetClientProcessId(void) const; + + /** + * Returns the app id of the client which sent a request message. + * + * @since 2.1 + * @return The app id of the IPC client. + * @remark This can be called only in a message handler. + */ + Tizen::App::AppId GetClientAppId(void) const; + + /** + * Returns the executable name of the client which sent a request message. + * + * @since 2.1 + * @return The executable name of the IPC client. + * @remark This can be called only in a message handler. + */ + Tizen::Base::String GetClientAppExecutableName(void) const; + + /** + * Stops the IPC server. + * + * @since 2.1 + * @return An error code + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_STATE The IPC server has not been started. + */ + result Stop(void); + + /** + * Sends a message to an IPC client. + * + * @since 2.1 + * @return An error code + * @param[in] clientId The id of the IPC client + * @param[in] message The message to send + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The message is synchronous. + * @exception E_INVALID_OPERATION The client didn't set a listener. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_SYSTEM A system error occurred. + * + * @remark Only an asychronous message can be sent to an IPC client. + */ + result SendResponse(int clientId, const IPC::Message& message); + + result Start(void); + + result SendResponse(int clientId, IPC::Message* pMessage); + + bool Send(IPC::Message* msg); + +private: + _IpcServer(const _IpcServer& value); + + _IpcServer& operator =(const _IpcServer& value); + + static void* ThreadProc(void* pParam); + + void Run(void* pParam); + + static gboolean OnConnectionRequest(GIOChannel* source, GIOCondition condition, gpointer data); + + static gboolean OnReadMessage(GIOChannel* source, GIOCondition condition, gpointer data); + + gboolean HandleReceivedMessage(GIOChannel* source, GIOCondition condition, gpointer data); + + static const int __MAX_MESSAGE_BUFFER_SIZE = 1024; + + struct _ClientInfo; + + /** + * @struct __ChannelInfo + * @brief This struct represent a channel. + * @since 2.1 + */ + struct _ChannelInfo + { + _ChannelInfo(void); + ~_ChannelInfo(void); + + struct _ClientInfo* pClientInfo; + GIOChannel* pGIOChannel; + GSource* pGSource; + bool destroySource; + }; + + /** + * @struct __ClientInfo + * @brief This struct represent a client connected to this server. + * @since 2.1 + */ + struct _ClientInfo + { + _ClientInfo(void); + ~_ClientInfo(void); + + int clientId; /**< the client id */ + _IpcServer* pIpcServer; /**< the pointer to an _ IpcServer */ + GIOChannel* pReverseChannel; /**< the channel for sending reverse message */ + std::vector channels; /**< the set of channels associated with a client */ + Tizen::Base::String appId; + Tizen::Base::String appExecutableName; + }; + + Tizen::Base::String __name; + bool __runOnCallerThread; + Tizen::Base::Runtime::_EventDispatcher* __pEventDispatcher; + _IIpcServerEventListener* __pListener; + + pthread_t __handlerThread; + GMainContext* __pHandlerGMainContext; + GMainLoop* __pHandlerGMainLoop; + + // handling connection + GSource* __pConnectGSource; + + // handling received message + char __messageBuffer[__MAX_MESSAGE_BUFFER_SIZE]; + std::string __pending; + + // current message handling context + GIOChannel* __pCurrentChannel; + _ClientInfo* __pCurrentClientInfo; + + std::map __clients; // pid of client is used for key +}; // _IpcServer + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_IPC_SERVER_H_ diff --git a/src/io/inc/FIo_LocalMessagePortImpl.h b/src/io/inc/FIo_LocalMessagePortImpl.h new file mode 100644 index 0000000..8823a17 --- /dev/null +++ b/src/io/inc/FIo_LocalMessagePortImpl.h @@ -0,0 +1,86 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_LocalMessagePortImpl.h + * @brief This is the header file for the _LocalMessagePortImpl class. + * + * This file contains the declarations of _LocalMessagePortImpl + */ + + +#ifndef _FIO_LOCAL_MESSAGE_PORT_IMPL_H_ +#define _FIO_LOCAL_MESSAGE_PORT_IMPL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FIo_IMessagePortListener.h" + + +namespace Tizen { namespace Io +{ + +class LocalMessagePort; +class IMessagePortListener; + +class _LocalMessagePortImpl + : public _IMessagePortListener +{ +public: + _LocalMessagePortImpl(void); + + virtual ~_LocalMessagePortImpl(void); + + result Construct(const Tizen::Base::String& port, bool isTrusted = false); + + result AddMessagePortListener(IMessagePortListener& listener); + + result RemoveMessagePortListener(IMessagePortListener& listener); + + Tizen::Base::String GetName(void) const; + + bool IsTrusted(void) const; + + virtual void OnMessageReceivedN(Tizen::Base::Collection::IMap* pMap); + + virtual void OnMessageReceivedN(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remotePort, bool isTrusted, Tizen::Base::Collection::IMap* pMap); + + static LocalMessagePort* GetMessagePort(const Tizen::Base::String& port, bool isTrusted = false); + +private: + _LocalMessagePortImpl(const _LocalMessagePortImpl& value); + + _LocalMessagePortImpl& operator =(const _LocalMessagePortImpl& value); + +private: + Tizen::Base::String __port; + bool __isTrusted; + + Tizen::Base::Runtime::Event* __pEvent; + +}; // _LocalMessagePortImpl + +} } // Tizen::Io + +#endif //_FIO_LOCAL_MESSAGE_PORT_IMPL_H_ diff --git a/src/io/inc/FIo_MessagePortManagerImpl.h b/src/io/inc/FIo_MessagePortManagerImpl.h new file mode 100644 index 0000000..b54bfed --- /dev/null +++ b/src/io/inc/FIo_MessagePortManagerImpl.h @@ -0,0 +1,97 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FIo_MessagePortManagerImpl.h + * @brief This is the header file for the %_MessagePortManagerImpl class. + * + * This header file contains the declarations of the %_MessagePortManagerImpl class. + */ +#ifndef _FIO_INTERNAL_MESSAGE_PORT_MANAGER_H_ +#define _FIO_INTERNAL_MESSAGE_PORT_MANAGER_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class LocalMessagePort; +class RemoteMessagePort; + +class _OSP_EXPORT_ _MessagePortManagerImpl +{ +public: + virtual ~_MessagePortManagerImpl(void); + + static _MessagePortManagerImpl* GetInstance(void); + + LocalMessagePort* RequestLocalMessagePort(const Tizen::Base::String& localPort); + RemoteMessagePort* RequestRemoteMessagePort(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remotePort); + + LocalMessagePort* RequestTrustedLocalMessagePort(const Tizen::Base::String& localPort); + RemoteMessagePort* RequestTrustedRemoteMessagePort(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remotePort); + + RemoteMessagePort* GetRemoteMessagePort(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remotePort, bool isTrusted); + +private: + _MessagePortManagerImpl(void); + _MessagePortManagerImpl(const _MessagePortManagerImpl& channelManagerImpl); + _MessagePortManagerImpl& operator =(const _MessagePortManagerImpl& channelManagerImpl); + + result Construct(void); + + static void InitSingleton(void); + + static void DestroySingleton(void); + +private: + class _StringHashProvider + : public Tizen::Base::Collection::IHashCodeProviderT + { + public: + virtual int GetHashCode(const Tizen::Base::String& value) const + { + return value.GetHashCode(); + } + }; + + class _StringComparer + : public Tizen::Base::Collection::IComparerT + { + public: + virtual result Compare(const Tizen::Base::String& string1, const Tizen::Base::String& string2, int& cmp) const + { + cmp = string1.CompareTo(string2); + return E_SUCCESS; + } + }; + +private: + Tizen::Base::Collection::HashMapT __localPorts; + Tizen::Base::Collection::HashMapT __trustLocalPorts; + Tizen::Base::Collection::HashMapT __remotePorts; + Tizen::Base::Collection::HashMapT __trustRemotePorts; + static _MessagePortManagerImpl* __pMessagePortMgrImplInst; + +}; // _MessagePortManagerImpl + +} } // Tizen::Io + +#endif //_FIO_INTERNAL_MESSAGE_PORT_MANAGER_H_ diff --git a/src/io/inc/FIo_MessagePortMessages.h b/src/io/inc/FIo_MessagePortMessages.h new file mode 100644 index 0000000..9c641d3 --- /dev/null +++ b/src/io/inc/FIo_MessagePortMessages.h @@ -0,0 +1,40 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MessagePortMessages.h + * @brief This is the header file for the message port message types. + */ + +#ifndef _FIO_MESSAGE_PORT_MESSAGES_H_ +#define _FIO_MESSAGE_PORT_MESSAGES_H_ + +#include "ipc/ipc_message_macros.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FIo_IpcMessageStart.h" + +#define IPC_MESSAGE_START MessagePortServiceStart + +IPC_SYNC_MESSAGE_CONTROL3_1(MessagePortService_register, Tizen::Base::String, Tizen::Base::String, bool, int) +IPC_SYNC_MESSAGE_CONTROL3_1(MessagePortService_requestRemotePort, Tizen::Base::String, Tizen::Base::String, bool, int) +IPC_SYNC_MESSAGE_CONTROL4_1(MessagePortService_sendMessage, Tizen::Base::String, Tizen::Base::String, bool, Tizen::Base::Collection::HashMap, int) +IPC_SYNC_MESSAGE_CONTROL6_1(MessagePortService_sendBidirMessage, Tizen::Base::String, Tizen::Base::String, bool, Tizen::Base::String, Tizen::Base::String, Tizen::Base::Collection::HashMap, int) +IPC_SYNC_MESSAGE_CONTROL6_1(MessagePortService_sendTrustedBidirMessage, Tizen::Base::String, Tizen::Base::String, bool, Tizen::Base::String, Tizen::Base::String, Tizen::Base::Collection::HashMap, int) +IPC_MESSAGE_CONTROL3(MessagePortService_sendMessageAsync, Tizen::Base::String, bool, Tizen::Base::Collection::HashMap) +IPC_MESSAGE_CONTROL6(MessagePortService_sendBidirMessageAsync, Tizen::Base::String, bool, Tizen::Base::String, Tizen::Base::String, bool, Tizen::Base::Collection::HashMap) + +#endif diff --git a/src/io/inc/FIo_MessagePortProxy.h b/src/io/inc/FIo_MessagePortProxy.h new file mode 100644 index 0000000..c65a873 --- /dev/null +++ b/src/io/inc/FIo_MessagePortProxy.h @@ -0,0 +1,125 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MessagePortProxy.h + * @brief This is the header file for the _MessagePortProxy class. + * + * This file contains the declarations of _MessagePortProxy. + */ + + +#ifndef _FIO_INTERNAL_MESSAGE_PORT_PROXY_H_ +#define _FIO_INTERNAL_MESSAGE_PORT_PROXY_H_ + +#include +#include +#include +#include +#include +#include +#include "FIo_IMessagePortListener.h" +#include "FIo_IIpcClientEventListener.h" + +namespace IPC { class Message; } + +namespace Tizen { namespace Io +{ + +class _IpcClient; + +class _MessagePortProxy + : public Tizen::Base::Object + , public _IIpcClientEventListener +{ +public: + _MessagePortProxy(void); + + virtual ~_MessagePortProxy(void); + + virtual result Construct(void); + + virtual void OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message); + + + virtual result RegisterMessagePort(const Tizen::Base::String& localPort, + bool isTrusted, + const _IMessagePortListener& listener); + + virtual result RequestRemotePort(const Tizen::App::AppId& remoteAppId, + const Tizen::Base::String& remotePort, + bool isTrusted); + + virtual result SendMessage(const Tizen::App::AppId& remoteAppId, + const Tizen::Base::String& remotePort, + bool isTrusted, + const Tizen::Base::Collection::HashMap* pMap); + + virtual result SendMessage(const Tizen::Base::String& localPort, + bool isTrustedLocal, + const Tizen::App::AppId& remoteAppId, + const Tizen::Base::String& remotePort, + bool isTrustedRemote, + const Tizen::Base::Collection::HashMap* pMap); + + static _MessagePortProxy* GetProxy(void); + +private: + bool OnSendMessage(const Tizen::Base::String& localPort, + bool isTrusted, + const Tizen::Base::Collection::HashMap& map); + + bool OnSendBidirMessage(const Tizen::Base::String& localPort, + bool isTrustedLocal, + const Tizen::App::AppId& remoteAppId, + const Tizen::Base::String& remotePort, + bool isTrustedRemote, + const Tizen::Base::Collection::HashMap& map); + +private: + class _StringHashProvider + : public Tizen::Base::Collection::IHashCodeProviderT + { + public: + virtual int GetHashCode(const Tizen::Base::String& value) const + { + return value.GetHashCode(); + } + }; + + class _StringComparer + : public Tizen::Base::Collection::IComparerT + { + public: + virtual result Compare(const Tizen::Base::String& string1, const Tizen::Base::String& string2, int& cmp) const + { + cmp = string1.CompareTo(string2); + return E_SUCCESS; + } + }; + +private: + Tizen::App::AppId __appId; + _IpcClient* __pIpcClient; + Tizen::Base::Collection::HashMapT __listeners; + Tizen::Base::Collection::HashMapT __trustedListeners; +}; // _MessagePortProxy + + +} } // Tizen::Io + +#endif // _FIO_INTERNAL_MESSAGE_PORT_PROXY_H_ diff --git a/src/io/inc/FIo_MmcStorageManagerImpl.h b/src/io/inc/FIo_MmcStorageManagerImpl.h new file mode 100644 index 0000000..ad376c3 --- /dev/null +++ b/src/io/inc/FIo_MmcStorageManagerImpl.h @@ -0,0 +1,101 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MmcStorageManagerImpl.h + * @brief This is the header file for the %_MmcStorageManagerImpl class. + * + * This header file contains the declarations of the %_MmcStorageManagerImpl class. + */ + +#ifndef _FIO_MMC_STORAGE_MANAGER_IMPL_H_ +#define _FIO_MMC_STORAGE_MANAGER_IMPL_H_ + +#include +#include +#include + +#include + +#include + +/*namespace Tizen { namespace Base +{ +namespace Collection +{ +class LinkedListT; +} +}}*/ + +namespace Tizen { namespace Io +{ + +class MmcStorageManager; +class _MmcStorageManagerProxy; +class IMmcStorageMountListener; +class IMmcStorageFormatListener; + +class _OSP_EXPORT_ _MmcStorageManagerImpl + : public Tizen::Base::Object + , public Tizen::Io::_IMmcStorageServiceEventListener +{ + +public: + _MmcStorageManagerImpl(void); + + ~_MmcStorageManagerImpl(void); + + result Construct(void); + + static _MmcStorageManagerImpl* GetInstance(void); + + result Mount(void); + + result Unmount(void); + + result Format(void); + + result AddMmcStorageMountListener(IMmcStorageMountListener& listener); + + result RemoveMmcStorageMountListener(IMmcStorageMountListener& listener); + + result AddMmcStorageFormatListener(IMmcStorageFormatListener& listener); + + result RemoveMmcStorageFormatListener(IMmcStorageFormatListener& listener); + + virtual result OnMmcMountResponseReceived(result r); + + virtual result OnMmcUnmountResponseReceived(result r); + + virtual result OnMmcFormatResponseReceived(result r); + +private: + _MmcStorageManagerImpl& operator =(const _MmcStorageManagerImpl& source); + + _MmcStorageManagerImpl(const _MmcStorageManagerImpl& source); + +private: + _MmcStorageManagerProxy* __pMmcStorageManagerProxy; + Tizen::Base::Collection::LinkedListT __pMmcMountListener; + Tizen::Base::Collection::LinkedListT __pMmcFormatListener; + +}; // _MmcStorageManagerImpl + +}} // Tizen::Io + +#endif // _FIO_MMC_STORAGE_MANAGER_IMPL_H_ + diff --git a/src/io/inc/FIo_MmcStorageManagerIpcMessages.h b/src/io/inc/FIo_MmcStorageManagerIpcMessages.h new file mode 100644 index 0000000..61ae145 --- /dev/null +++ b/src/io/inc/FIo_MmcStorageManagerIpcMessages.h @@ -0,0 +1,34 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MmcStorageManagerIpcMessages.h + * @brief This is the header file for the MmcStorageManager Ipc message types. + */ + +#include "ipc/ipc_message_macros.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FIo_IpcMessageStart.h" + +#define IPC_MESSAGE_START MmcStorageManagerServiceStart + +IPC_SYNC_MESSAGE_CONTROL0_1(MmcStorageManager_Mount, result) +IPC_SYNC_MESSAGE_CONTROL0_1(MmcStorageManager_Unmount, result) +IPC_SYNC_MESSAGE_CONTROL0_1(MmcStorageManager_Format, result) +IPC_MESSAGE_CONTROL1(MmcStorageManager_MountReceived, result) +IPC_MESSAGE_CONTROL1(MmcStorageManager_UnmountReceived, result) +IPC_MESSAGE_CONTROL1(MmcStorageManager_FormatReceived, result) diff --git a/src/io/inc/FIo_MmcStorageManagerProxy.h b/src/io/inc/FIo_MmcStorageManagerProxy.h new file mode 100644 index 0000000..e2606d6 --- /dev/null +++ b/src/io/inc/FIo_MmcStorageManagerProxy.h @@ -0,0 +1,76 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_MmcStorageManagerProxy.h + * @brief This is the header file of the _MmcStorageManagerProxy class. + */ + +#ifndef _FIO_INTERNAL_MMC_STORAGE_MANAGER_PROXY_H_ +#define _FIO_INTERNAL_MMC_STORAGE_MANAGER_PROXY_H_ + +#include +#include +#include + +#include + +namespace Tizen { namespace Io +{ + +class _IMmcStorageServiceEventListener; +class _IpcClient; + +/** + * @class _MmcStorageManagerProxy + * @brief + * @since 2.1 + */ +class _MmcStorageManagerProxy + : public Tizen::Io::_IIpcClientEventListener + , public Tizen::Base::Object +{ +public: + _MmcStorageManagerProxy(void); + virtual ~_MmcStorageManagerProxy(void); + + result Construct(_IMmcStorageServiceEventListener* pImpl); + + result Mount(void); + result Unmount(void); + result Format(void); + + virtual void OnIpcResponseReceived(Tizen::Io::_IpcClient& client, const IPC::Message& message); + + void MountResponseReceived(result r); + void UnmountResponseReceived(result r); + void FormatResponseReceived(result r); + +private: + _MmcStorageManagerProxy(const _MmcStorageManagerProxy& rhs); + + _MmcStorageManagerProxy& operator =(const _MmcStorageManagerProxy& rhs); + +private: + _IpcClient* __pIpcClient; + static _IMmcStorageServiceEventListener* __pImpl; + +}; // _MmcStorageManagerProxy + +} } // Tizen::App + +#endif // _FIO_INTERNAL_MMC_STORAGE_MANAGER_PROXY_H_ diff --git a/src/io/inc/FIo_NormalFile.h b/src/io/inc/FIo_NormalFile.h new file mode 100644 index 0000000..0ff6da2 --- /dev/null +++ b/src/io/inc/FIo_NormalFile.h @@ -0,0 +1,93 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_NormalFile.h + * @brief This is the header file for the _NormalFile class. + * + * This header file contains the declarations of the %_NormalFile class. + */ + +#ifndef _FIO_INTERNAL_NORMALFILE_H_ +#define _FIO_INTERNAL_NORMALFILE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace Tizen { namespace Io +{ + +class _NormalFile + : public Tizen::Base::Object + , public _IFileCore +{ + +public: + _NormalFile(void); + + result Construct(const Tizen::Base::String& filePath, const char* pOpenMode); + + virtual ~_NormalFile(void); + + result Read(Tizen::Base::ByteBuffer& buffer); + + int Read(void* buffer, int length); + + result Read(Tizen::Base::String& buffer); + + result ReadN(char** buffer, int& length); + + result Write(const Tizen::Base::ByteBuffer& buffer); + + result Write(const void* buffer, int length); + + result Write(const Tizen::Base::String& buffer); + + result Flush(void); + + int Tell(void) const; + + result Seek(FileSeekPosition position, long offset); + + result Truncate(int length); + + Tizen::Base::String GetName(void); + + virtual FILE* GetFilePointer(void) + { + return __pFile; + } + +private: + Tizen::Base::String __filePath; + + FILE* __pFile; + +}; // _NormalFile + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_NORMALFILE_H_ + diff --git a/src/io/inc/FIo_NormalRegistry.h b/src/io/inc/FIo_NormalRegistry.h new file mode 100644 index 0000000..a4dcd17 --- /dev/null +++ b/src/io/inc/FIo_NormalRegistry.h @@ -0,0 +1,71 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_NormalRegistry.h + * @brief This is the header file for the %_NormalRegistry class. + */ + +#ifndef _FIO_INTERNAL_NORMALREGISTRY_H_ +#define _FIO_INTERNAL_NORMALREGISTRY_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace Tizen { namespace Io +{ + +class File; +class _FileImpl; +class _SecureRegistry; + +class _NormalRegistry + : public _RegistryCore +{ + +public: + _NormalRegistry(void); + + virtual ~_NormalRegistry(void); + + result Construct(const Tizen::Base::String& regPath, const char* pOpenMode); + + result Flush(void); + +private: + _NormalRegistry(const _NormalRegistry& rhs); + + _NormalRegistry& operator =(const _NormalRegistry& rhs); + + friend class Registry; + friend class _SecureRegistry; + +}; // _NormalRegistry + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_NORMALREGISTRY_H_ + diff --git a/src/io/inc/FIo_RegistryCore.h b/src/io/inc/FIo_RegistryCore.h new file mode 100644 index 0000000..ca20a1c --- /dev/null +++ b/src/io/inc/FIo_RegistryCore.h @@ -0,0 +1,138 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_RegistryCore.h + * @brief This is the header file for the %_RegistryCore class. + */ + +#ifndef _FIO_INTERNAL_REGISTRYCORE_H_ +#define _FIO_INTERNAL_REGISTRYCORE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Io +{ + +class _RegistryCore + : public Tizen::Base::Object +{ +public: + _RegistryCore(void); + + virtual ~_RegistryCore(void); + + virtual result Flush(void); + + bool VerifyRegistryOpenMode(const char* pOpenMode); + + result Parse(void); + + result Load(const Tizen::Base::String& regPath, const char* pOpenMode); + + result AddSection(const Tizen::Base::String& SectionName); + + result RemoveSection(const Tizen::Base::String& SectionName); + + result GetSectionListN(Tizen::Base::Collection::IList** pRetList); + + result GetEntryListN(const Tizen::Base::String& sectionName, Tizen::Base::Collection::HashMap** pRetList); + + Tizen::Base::Collection::IMap* GetAllEntriesN(const Tizen::Base::String& sectionName); + + Tizen::Base::Collection::IList* GetAllEntryNamesN(const Tizen::Base::String& sectionName); + + result GetEntryList(const Tizen::Base::String& sectionName, Tizen::Base::Collection::HashMap& retMap); + + result GetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, Tizen::Base::String& valStr); + + result AddValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::String& valStr); + + result SetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::String& valStr); + + result RemoveValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName); + + result PrepareToWrite(void); + + result Write(void); + + int GetSectionIndex(const Tizen::Base::String& sectionName); + + Tizen::Base::String GetSectionName(int sectionIndex); + + int GetEntryIndex(int sectionIndex, const Tizen::Base::String& entryName); + + Tizen::Base::String GetEntryName(int sectionIndex, int entryIndex); + + void Removekey(const Tizen::Base::String& sectionName, const Tizen::Base::String& keyName); + + int GetAllSectionCount(void); + + int GetAllEntryCount(int sectionIndex); + + void RemoveEntry(int sectionIndex, int entryIndex); + + void GetEntryValue(int sectionIndex, int entryIndex, _RegValueType type, void* pValue, int* pSize); + + void ModifyEntryValue(int sectionIndex, int entryIndex, _RegValueType type, const void* pValue, int size); + + void* GetSectionByIndex(int sectionIndex); + + static result ConvertToSecureRegistry(const Tizen::Base::String& plainRegPath, const Tizen::Base::String& secureRegPath, const Tizen::Base::ByteBuffer* key = null); + +protected: + static result AddSection(Tizen::Base::Collection::LinkedList& sectionList, const Tizen::Base::String& sectionName); + + static result AddValue(Tizen::Base::Collection::LinkedList& sectionList, const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::String& valStr); + + static bool CheckSectionName(char* pSectionName); + + static bool CheckEntryName(char* pEntryName); + + static bool CheckEntryValue(char* pEntryVal); + +private: + _RegistryCore(const _RegistryCore& rhs); + + _RegistryCore& operator =(const _RegistryCore& rhs); + + void DecodeData(const Tizen::Base::String& strValueEncoded, _RegValueType type, void* pValue, int* pSize); + +protected: + bool _constructed; + Tizen::Base::String _regPath; + bool _read; + bool _write; + bool _truncate; + bool _append; + Tizen::Base::Collection::LinkedList _sectionList; // > + byte* _pBuffer; + int _length; + +}; // _RegistryCore + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_REGISTRYCORE_H_ + diff --git a/src/io/inc/FIo_RegistryImpl.h b/src/io/inc/FIo_RegistryImpl.h new file mode 100644 index 0000000..986ba7c --- /dev/null +++ b/src/io/inc/FIo_RegistryImpl.h @@ -0,0 +1,162 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_RegistryImpl.h + * @brief This is the header file for the %_RegistryImpl class. + * + * This header file contains the declarations of the %_RegistryImpl class. + */ + +#ifndef _FIO_INTERNAL_REGISTRY_IMPL_H_ +#define _FIO_INTERNAL_REGISTRY_IMPL_H_ + +#include +#include + +namespace Tizen {namespace Base +{ +class String; +class ByteBuffer; +namespace Collection +{ +class HashMap; +class IList; +class IMap; +} +}} + +namespace Tizen { namespace Io +{ + +class Registry; +class _RegistryCore; + +// @enum %Registry value Type +enum _RegValueType +{ + REG_VALUE_TYPE_INT = 1, // Integer type + REG_VALUE_TYPE_REAL, // Real type + REG_VALUE_TYPE_STRING, // String type + REG_VALUE_TYPE_BINARY, // Binary type + REG_VALUE_TYPE_UUID, // UUID type + REG_VALUE_TYPE_UUIDSET, // UUIDSET type + REG_VALUE_TYPE_MAX +}; + +class _OSP_EXPORT_ _RegistryImpl + : public Tizen::Base::Object +{ + +public: + _RegistryImpl(void); + + virtual ~_RegistryImpl(void); + + result Construct(const Tizen::Base::String& regPath, long openMode, const Tizen::Base::ByteBuffer* pKey = null); + + result Construct(const Tizen::Base::String& regPath, const char* pOpenMode, const Tizen::Base::ByteBuffer* pSecretKey); + + static result Remove(const Tizen::Base::String& regPath); + + result AddSection(const Tizen::Base::String& SectionName); + + result RemoveSection(const Tizen::Base::String& SectionName); + + result GetSectionListN(Tizen::Base::Collection::IList** pRetList); + + result GetEntryListN(const Tizen::Base::String& sectionName, Tizen::Base::Collection::HashMap** pRetList); + + /** + * Gets all entries in the specified section of the registry. + * + * @since 2.1 + * @return A map of entries @n + * If this method fails, @c null value is returned. @n + * When there are no entries at all, the method returns an empty map instance. + * Use the GetCount() method to check the number of element in the map. + * @param sectionName The section name + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_STATE This instance has not been constructed yet. + * @exception E_SECTION_NOT_FOUND The specified @c sectionName was not found within the registry. + * @exception E_OUT_OF_MEMORY The memory was insufficient. + * @exception E_IO The system error has occurred. + * @remarks Do not forget to delete not only the returned IMap instance, but also its + * contents by invoking IMap::RemoveAll(). @n + * The specific error code can be accessed using the GetLastResult() method. + */ + Tizen::Base::Collection::IMap* GetAllEntriesN(const Tizen::Base::String& sectionName) const; + + Tizen::Base::Collection::IList* GetAllEntryNamesN(const Tizen::Base::String& sectionName) const; + + result GetEntryList(const Tizen::Base::String& sectionName, Tizen::Base::Collection::HashMap& retMap); + + result GetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, Tizen::Base::String& valStr); + + result AddValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::String& valStr); + + result SetValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName, const Tizen::Base::String& valStr); + + result RemoveValue(const Tizen::Base::String& sectionName, const Tizen::Base::String& entryName); + + result Flush(void); + + int GetSectionIndex(const Tizen::Base::String& sectionName); + + Tizen::Base::String GetSectionName(int sectionIndex); + + int GetEntryIndex(int sectionIndex, const Tizen::Base::String& entryName); + + Tizen::Base::String GetEntryName(int sectionIndex, int entryIndex); + + void Removekey(const Tizen::Base::String& sectionName, const Tizen::Base::String& keyName); + + int GetAllSectionCount(void); + + int GetAllEntryCount(int sectionIndex); + + void RemoveEntry(int sectionIndex, int entryIndex); + + void GetEntryValue(int sectionIndex, int entryIndex, _RegValueType type, void* pValue, int* pSize); + + void ModifyEntryValue(int sectionIndex, int entryIndex, _RegValueType type, const void* pValue, int size); + + static result ConvertToSecureRegistry(const Tizen::Base::String& plainRegPath, const Tizen::Base::String& secureRegPath, const Tizen::Base::ByteBuffer* key = null); + + static _RegistryImpl* GetInstance(Registry& registry); + + static const _RegistryImpl* GetInstance(const Registry& registry); + +private: + _RegistryImpl(const _RegistryImpl& source); + + _RegistryImpl& operator =(const _RegistryImpl& source); + + void* GetSectionByIndex(int sectionIndex); + + static bool ConvertRegistryOpenMode(long legacyMode, char* pOpenMode); + + static result CheckOpenMode(const Tizen::Base::String& openMode); + + _RegistryCore* __pRegistryCore; + +}; // _RegistryImpl + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_REGISTRY_IMPL_H_ + diff --git a/src/io/inc/FIo_RemoteMessagePortImpl.h b/src/io/inc/FIo_RemoteMessagePortImpl.h new file mode 100644 index 0000000..da8326e --- /dev/null +++ b/src/io/inc/FIo_RemoteMessagePortImpl.h @@ -0,0 +1,83 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_RemoteMessagePortImpl.h + * @brief This is the header file for the _RemoteMessagePortImpl class. + * + * This file contains the declarations of _RemoteMessagePortImpl + */ + + +#ifndef _FIO_REMOTE_MESSAGE_PORT_IMPL_H_ +#define _FIO_REMOTE_MESSAGE_PORT_IMPL_H_ + +#include +#include +#include +#include +#include +#include +#include + + +namespace Tizen { namespace Io +{ + +class RemoteMessagePort; +class IMessagePortListener; + +class _RemoteMessagePortImpl +{ +public: + _RemoteMessagePortImpl(void); + + virtual ~_RemoteMessagePortImpl(void); + + result Construct(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remotePort, bool isTrusted = false); + + Tizen::Base::String GetName(void) const; + + Tizen::App::AppId GetAppId(void) const; + + bool IsTrusted(void) const; + + result SendMessage(const Tizen::Base::Collection::IMap* pMessage); + + result SendMessage(const LocalMessagePort* pLocalMessagePort, const Tizen::Base::Collection::IMap* pMessage); + + static RemoteMessagePort* GetMessagePort(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remotePort, bool isTrusted = false); + + static RemoteMessagePort* GetMessagePortOnly(const Tizen::App::AppId& remoteAppId, const Tizen::Base::String& remotePort, bool isTrusted = false); + +private: + _RemoteMessagePortImpl(const _RemoteMessagePortImpl& value); + + _RemoteMessagePortImpl& operator =(const _RemoteMessagePortImpl& value); + + bool CheckMessageType(const Tizen::Base::Collection::IMap* pMessage); + +private: + Tizen::App::AppId __remoteAppId; + Tizen::Base::String __remotePort; + bool __isTrusted; + +}; // _RemoteMessagePortImpl + +} } // Tizen::Io + +#endif //_FIO_REMOTE_MESSAGE_PORT_IMPL_H_ diff --git a/src/io/inc/FIo_SecureFile.h b/src/io/inc/FIo_SecureFile.h new file mode 100644 index 0000000..757397a --- /dev/null +++ b/src/io/inc/FIo_SecureFile.h @@ -0,0 +1,99 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_SecureFile.h + * @brief This is the header file for the _SecureFile class. + * + * This header file contains the declarations of the _SecureFile class. + */ + +#ifndef _FIO_INTERNAL_SECURE_FILE_IMPL_H_ +#define _FIO_INTERNAL_SECURE_FILE_IMPL_H_ + +#include + +#include +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +}} + +namespace Tizen { namespace Io +{ + +class _SecureFile + : public Tizen::Base::Object + , public _IFileCore +{ + +public: + _SecureFile(bool read, bool write, bool truncate, bool append); + + result Construct(const Tizen::Base::String& filePath, const char* pOpenMode, const Tizen::Base::ByteBuffer* pSecretKey); + + virtual ~_SecureFile(void); + + result Read(Tizen::Base::ByteBuffer& buffer); + + int Read(void* buffer, int length); + + result Read(Tizen::Base::String& buffer); + + result Write(const Tizen::Base::ByteBuffer& buffer); + + result Write(const void* buffer, int length); + + result Write(const Tizen::Base::String& buffer); + + result Flush(void); + + int Tell(void) const; + + result Seek(FileSeekPosition position, long offset); + + result Truncate(int length); + + Tizen::Base::String GetName(void); + + virtual FILE* GetFilePointer(void) + { + return __pNormalFile->GetFilePointer(); + } + +private: + _SecureFile(void); + + _SecureFile(const _SecureFile& source); + + _SecureFile& operator =(const _SecureFile& source); + + Tizen::Base::String __filePath; + _NormalFile* __pNormalFile; + bool __constructed; + long __virtualFilePointer; + Tizen::Base::ByteBuffer* __pKey; + +}; // _SecureFile + +}} // Tizen::Io + +#endif // _FIO_INTERNAL_SECURE_FILE_IMPL_H_ + diff --git a/src/io/inc/FIo_SecureIoUtil.h b/src/io/inc/FIo_SecureIoUtil.h new file mode 100644 index 0000000..7af6b62 --- /dev/null +++ b/src/io/inc/FIo_SecureIoUtil.h @@ -0,0 +1,151 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_SecureIoUtil.h + * @brief This is the header file for the %_SecureIoUilt class. + * + * This header file contains the declarations of the %_SeureIoUtil class. + */ + +#ifndef _FIO_INTERNAL_SECUREIOUTIL_H_ +#define _FIO_INTERNAL_SECUREIOUTIL_H_ + +#include +#include +#include + +namespace Tizen { namespace Io +{ + +extern const char SECURE_FILE_HEADER_STRING[]; +extern const char SECURE_REG_HEADER_STRING[]; + +const int FIO_LEN_4K = 4096; +const int CIPHER_BLOCK_SIZE = 400*1024; +const int CIPHER_BLOCK_HEADER_SIZE = 3; +const int SECURE_FILE_HEADER_STRING_SIZE = 16; +const int SECURE_REG_HEADER_STRING_SIZE = 20; +const int SECURE_FILE_HEADER_SIZE_V1 = 34; +const int SECURE_REG_HEADER_SIZE_V1 = 38; +const int MAX_BLOCK_INDEX_LEN = 3; +const int ONE_BLOCK_SIZE = 16; +const int ENCRYPT_KEY_LEN = 16; +const int SECURE_IO_STATIC_BIN_LEN = 8; +const int SECURE_IO_FLAG_SIZE = 1; +const int SECURE_IO_INDEX_SIZE = 1; +const int SECURE_IO_LOF_SIZE = 4; +const int SECURE_IO_2_BYTES = 2; +const int SECURE_IO_10_BYTES = 10; +const int SECURE_IO_12_BYTES = 12; +const int SQLITE_HEADER_SIZE = 16; +const int SQLITE_FORMAT_STR_SIZE = 15; +const int SECURE_IO_HEX_64 = 0x64; +const int SECURE_IO_MAGIC_NUMBER_SIZE = 4; + + +enum _DataFormat +{ + DATA_FORMAT_UNDEFINED = 0, + DATA_FORMAT_BYTE, + DATA_FORMAT_STRING +}; + +enum _FlagState +{ + FLAG_STATE_NONE = 0, + FLAG_STATE_CVF, + FLAG_STATE_CTF, + FLAG_STATE_CVF_CTF +}; + +enum _DatabaseMode +{ + DATABASE_MODE_NONE = 0, + DATABASE_MODE_NORMAL, + DATABASE_MODE_SECURE, + DATABASE_MODE_ERROR, +}; + +class _SecureIoUtil +{ + +public: + + static result SaveLengthOfFile(_NormalFile* pNormalFile); + + static result InsertSecureFileHeader(_NormalFile* pNormalFile); + + static result SelectCipherBlock(_NormalFile* pNormalFile, long virtualFilePointer, int* pPosition); + + static result MakeCipherBlock(byte* pData, int dataSize, byte** ppEncryptedData, int* pEncryptedDataSize, const Tizen::Base::ByteBuffer& key); + + static result WriteDataInCipherBlock(_NormalFile* pNormalFile, int dataPosition, bool eofSet, int dataSize, byte* pData, const Tizen::Base::ByteBuffer& key); + + static result ReadDataFromCipherBlock(_NormalFile* pNormalFile, int dataPosition, int bufferSize, byte* pData, _DataFormat dataMode, int* readItems, const Tizen::Base::ByteBuffer& key); + + static result GetDataLengh(_NormalFile* pNormalFile, long* dataLength); + + static result CheckSecureFileHeader(const Tizen::Base::String& filePath, const Tizen::Base::ByteBuffer* pSecretKey); + + static result CheckSecureRegistryHeader(byte** pSecureRegistryHeader, int* pHeaderLen, const Tizen::Base::String strFilePathPath, bool secureMode); + + static result MakeCipherBlockReplica(_NormalFile* pNormalFile, const Tizen::Base::String filePath, int dataPosition, int dataSize); + + static result RestoreCorruptBlock(_NormalFile* pNormalFile, const Tizen::Base::String filePath); + + static result DeleteBlockReplica(_NormalFile* pNormalFile, const Tizen::Base::String filePath); + + static result SetFlag(_NormalFile* pNormalFile, _FlagState flag); + + static result SetRegistryFlag(void* pFileSecure, _FlagState flag); + + static result CheckFlag(_NormalFile* pNormalFile, _FlagState* pFlag); + + static _FlagState CheckRegistryFlag(byte* pHeader); + + static const Tizen::Base::String MakeRegistryReplica(const Tizen::Base::String filePath, byte* pNameIndex); + + static result DeleteRegistryReplica(byte *pHeader, const Tizen::Base::String filePath); + + static result LoadRegistryReplica(byte** pHeader, int* pHeaderLen, const Tizen::Base::String filePath); + + static bool IsEmpty(char* pPath); + + static bool DetectNewLine(byte* pData, int readSize, int preReadSize, int* pTerminationCur, int* newLineSize); + + static bool IsNormalDatabase(_DatabaseMode mode); + + static bool IsSecureDatabase(_DatabaseMode mode); + + static bool IsEndOfFile(_NormalFile* pNormalFile); + + static _DatabaseMode GetDatabaseMode(char* pStrPhysicalDbPath); + + static byte* GenerateDatabaseKeyN(const Tizen::Base::ByteBuffer* pUserKey); + + static bool IsEmpty(const Tizen::Base::String& filePath); + + static Tizen::Base::ByteBuffer* GetSecureKeyN(const Tizen::Base::ByteBuffer* pKey = null); + + static Tizen::Base::ByteBuffer* DoCipherAesN(const Tizen::Base::String transformation, const Tizen::Base::ByteBuffer& input,const Tizen::Base::ByteBuffer& key, Tizen::Security::Crypto::CipherOperation encMode); +}; + +}} //Tizen::Io + +#endif //_FIO_INTERNAL_SECUREIOUTIL_H_ + diff --git a/src/io/inc/FIo_SecureRegistry.h b/src/io/inc/FIo_SecureRegistry.h new file mode 100644 index 0000000..a4ecac5 --- /dev/null +++ b/src/io/inc/FIo_SecureRegistry.h @@ -0,0 +1,57 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_SecureRegistry.h + * @brief This is the header file for the %_SecureRegistry class. + */ + +#ifndef _FIO_INTERNAL_SECUREREGISTRY_H_ +#define _FIO_INTERNAL_SECUREREGISTRY_H_ + +#include +#include + +namespace Tizen { namespace Io +{ + +class _SecureRegistry + : public _RegistryCore +{ + +public: + _SecureRegistry(void); + + virtual ~_SecureRegistry(void); + + result Construct(const Tizen::Base::String& regPath, const char* pOpenMode, const Tizen::Base::ByteBuffer* pSecretKey); + + result Flush(void); + +private: + _SecureRegistry(const _SecureRegistry& rhs); + + _SecureRegistry& operator =(const _SecureRegistry& rhs); + + Tizen::Base::ByteBuffer* __pSecretKey; + +}; // _SecureRegistry + +}} // Tizen::Io + +#endif //_FIO_INTERNAL_SECUREREGISTRY_H_ + diff --git a/src/io/inc/FIo_ServerChannelImpl.h b/src/io/inc/FIo_ServerChannelImpl.h new file mode 100644 index 0000000..33b8934 --- /dev/null +++ b/src/io/inc/FIo_ServerChannelImpl.h @@ -0,0 +1,77 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FIo_ServerChannelImpl.h + * @brief This is the header file for the _ServerChannelImpl class. + * + * This file contains the declarations of _ServerChannelImpl. + */ + +#ifndef _FIO_INTERNAL_SERVER_CHANNEL_IMPL_H_ +#define _FIO_INTERNAL_SERVER_CHANNEL_IMPL_H_ + +#include +#include +#include +#include +#include "FIo_IChannelRequestEventListener.h" +#include "FIo_Channel.h" + +namespace Tizen { namespace Io +{ + +class _ServerChannel; +class ServerChannel; +class IChannelRequestEventListener; + +class _OSP_EXPORT_ _ServerChannelImpl + : public Tizen::Base::Object + , public _IChannelRequestEventListener +{ +public: + _ServerChannelImpl(void); + + virtual ~_ServerChannelImpl(void); + + result Construct(ServerChannel* pServerChannel, const Tizen::Base::String& channelName = L""); + + result SendResponse(const Tizen::Base::String& clientChannelId, const Tizen::Base::Collection::IList* pArgs, RequestId reqId); + + void SetChannelRequestEventListener(IChannelRequestEventListener* pRequestListener); + + void OnChannelRequestReceivedN(RequestId reqId, const Tizen::Base::String& channelId, Tizen::Base::Collection::IList* pArgs); + + static _ServerChannelImpl* GetInstance(ServerChannel* pChannel); + + static ServerChannel* GetServerChannel(const Tizen::Base::String& channelName); + +private: + _ServerChannelImpl(const _ServerChannelImpl& serverChannelImpl); + + _ServerChannelImpl& operator =(const _ServerChannelImpl& serverChannelImpl); + +private: + ServerChannel* __pServerChannel; + IChannelRequestEventListener* __pRequestListener; + _Channel* __pChannel; +}; //_ServerChannelImpl + + +} } // Tizen::Io + +#endif //_FIO_CHANNEL_H_ diff --git a/src/locales/CMakeLists.txt b/src/locales/CMakeLists.txt new file mode 100755 index 0000000..28d556d --- /dev/null +++ b/src/locales/CMakeLists.txt @@ -0,0 +1,50 @@ +SET (this_target locales) + +INCLUDE_DIRECTORIES( + ${SLP_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/inc + inc + ${CMAKE_SOURCE_DIR}/src/base/inc + ${CMAKE_SOURCE_DIR}/src/app/inc +) + +SET (${this_target}_SOURCE_FILES + FLcl_LocaleImpl.cpp + FLcl_TimeZoneImpl.cpp + + FLcl_IcuCalendarImpl.cpp + FLcl_CalendarImpl.cpp + FLcl_LocaleData.cpp + FLcl_LocaleManagerImpl.cpp + FLcl_NumberSymbolsImpl.cpp + FLcl_DateTimeSymbolsImpl.cpp + FLcl_NumberFormatterImpl.cpp + FLcl_DateTimeFormatterImpl.cpp + FLcl_CurrencyImpl.cpp + FLclCurrency.cpp + FLclTimeZone.cpp + FLclLocale.cpp + FLclLocaleManager.cpp + FLclTimeRule.cpp + FLclCalendar.cpp + FLclGregorianCalendar.cpp + FLclDateTimeSymbols.cpp + FLclDateTimeFormatter.cpp + FLclNumberSymbols.cpp + FLclNumberFormatter.cpp + FLcl_FieldPosition.cpp +) + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") + +## SET EXTRA COMPILER FLAGS +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fPIC" ) + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} STATIC ${${this_target}_SOURCE_FILES}) diff --git a/src/locales/FLclCalendar.cpp b/src/locales/FLclCalendar.cpp new file mode 100644 index 0000000..3768edc --- /dev/null +++ b/src/locales/FLclCalendar.cpp @@ -0,0 +1,379 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FLclCalendar.cpp +* @brief This is the implementation file for Calendar class. +*/ +#include +#include +#include +#include +#include +#include + +#include "FLcl_CalendarImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +Calendar::Calendar(void) + : _time(0) + , _timeZone() + , _isTimeSet(false) + , _areFieldsSet(false) + , _areAllFieldsSet(false) + , _nextStamp(0) + , _isLenient(true) + , _isConstructed(false) + , _pCalendarImpl(null) +{ + for (int i = 0; i < TIME_FIELD_FIELD_COUNT; i++) + { + _timeFields[i] = 0; + _stamp[i] = UNSET; + _isSet[i] = false; + } +} + +result +Calendar::Construct(void) +{ + return Construct(TimeZone::GetGmtTimeZone(), Locale(LANGUAGE_ENG, COUNTRY_GB)); +} + +result +Calendar::Construct(const Calendar& other) +{ + // Object is not allowed to construct twice + SysAssertf(_isConstructed == false, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + for (int i = 0; i < TIME_FIELD_FIELD_COUNT; i++) + { + _timeFields[i] = other._timeFields[i]; + _stamp[i] = other._stamp[i]; + _isSet[i] = other._isSet[i]; + } + + _time = other._time; + _timeZone = other._timeZone; + _isTimeSet = other._isTimeSet; + _areFieldsSet = other._areFieldsSet; + _areAllFieldsSet = other._areAllFieldsSet; + _nextStamp = other._nextStamp; + _isLenient = other._isLenient; + _isConstructed = true; + + return E_SUCCESS; +} + +result +Calendar::Construct(const TimeZone& timezone, const Locale& locale) +{ + // Object is not allowed to construct twice + SysAssertf(_isConstructed == false, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + result r = E_INVALID_ARG; + + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_UNSUPPORTED_OPERATION; + } + + SysTryReturnResult(NID_LCL, locale.GetLanguageCode() != LANGUAGE_INVALID, + r, "Invalid argument is used. Language code is invalid. Given locale is not supported"); + + SysTryReturnResult(NID_LCL, locale.GetCountryCode() != COUNTRY_INVALID, + r, "Invalid argument is used. Country code is invalid. Given locale is not supported"); + + _timeZone = timezone; + _nextStamp = MINIMUM_USER_STAMP; + _isLenient = true; + _isConstructed = true; + return E_SUCCESS; +} + +Calendar::~Calendar(void) +{ +} + +Calendar* +Calendar::CreateInstanceN(CalendarType calendarType) +{ + return _CalendarImpl::CreateCalendarInstanceN(calendarType); +} + +Calendar* +Calendar::CreateInstanceN(const TimeZone& timeZone, CalendarType calendarType) +{ + return _CalendarImpl::CreateCalendarInstanceN(timeZone, calendarType); +} + +Calendar* +Calendar::CreateInstanceN(const Locale& locale, CalendarType calendarType) +{ + return _CalendarImpl::CreateCalendarInstanceN(locale, calendarType); +} + +Calendar* +Calendar::CreateInstanceN(const TimeZone& timeZone, const Locale& locale, CalendarType calendarType) +{ + return _CalendarImpl::CreateCalendarInstanceN(timeZone, locale, calendarType); +} + +result +Calendar::After(const Calendar& otherCalendar, bool& after) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = E_INVALID_ARG; + + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_INVALID_STATE; + } + SysTryReturnResult(NID_LCL, otherCalendar._pCalendarImpl, r, "Invalid argument is used. otherCalendar instance is invalid"); + return _pCalendarImpl->After(*otherCalendar._pCalendarImpl, after); +} + +result +Calendar::Before(const Calendar& otherCalendar, bool& before) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = E_INVALID_ARG; + + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_INVALID_STATE; + } + SysTryReturnResult(NID_LCL, otherCalendar._pCalendarImpl, r, "Invalid argument is used. otherCalendar instance is invalid"); + return _pCalendarImpl->Before(*otherCalendar._pCalendarImpl, before); +} + +result +Calendar::Clear(void) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->ClearImpl(); +} + +result +Calendar::Clear(TimeField field) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->ClearImpl(field); +} + +bool +Calendar::Equals(const Object& obj) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + + const Calendar* pOtherInstance = dynamic_cast< const Calendar* >(&obj); + if ((pOtherInstance == null) || (pOtherInstance->_pCalendarImpl == null)) + { + return false; + } + + return _pCalendarImpl->Equals(*pOtherInstance->_pCalendarImpl); +} + +int +Calendar::GetHashCode(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetHashCode(); +} + +int +Calendar::GetActualMaxTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetActualMaxTimeField(field); +} + +int +Calendar::GetActualMinTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetActualMinTimeField(field); +} + +int +Calendar::GetFirstDayOfWeek(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetFirstDayOfWeekImpl(); +} + +int +Calendar::GetGreatestMinTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetGreatestMinTimeField(field); +} + +int +Calendar::GetLeastMaxTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetLeastMaxTimeField(field); +} + +int +Calendar::GetMaxTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetMaxTimeField(field); +} + +int +Calendar::GetMinTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetMinTimeField(field); +} + +int +Calendar::GetMinDaysInFirstWeek(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetMinDaysInFirstWeekImpl(); +} + +DateTime +Calendar::GetTime(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetTimeImpl(); +} + +int +Calendar::GetTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetTimeFieldImpl(field); +} + +TimeZone +Calendar::GetTimeZone(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetTimeZoneImpl(); +} + +bool +Calendar::IsLenient(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->IsLenientImpl(); +} + +bool +Calendar::IsSet(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->IsSetImpl(field); +} + +result +Calendar::Roll(TimeField field, int amount) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->Roll(field, amount); +} + +result +Calendar::SetTime(const DateTime& dateTime) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->SetTimeImpl(dateTime); +} + +result +Calendar::SetTime(int year, int month, int day, int hour, int minute, int second) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->SetTimeImpl(year, month, day, hour, minute, second); +} + +result +Calendar::SetTimeField(TimeField field, int value) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->SetTimeFieldImpl(field, value); +} + +result +Calendar::SetFirstDayOfWeek(DayOfWeek dayOfWeek) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->SetFirstDayOfWeekImpl(dayOfWeek); +} + +result +Calendar::SetLenient(bool lenient) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->SetLenientImpl(lenient); +} + +result +Calendar::SetMinDaysInFirstWeek(short value) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->SetMinDaysInFirstWeekImpl(value); +} + +result +Calendar::SetTimeZone(const TimeZone& timeZone) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->SetTimeZoneImpl(timeZone); +} + +result +Calendar::GetTimeInMillisec(long long& millisec) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetTimeInMillisecImpl(millisec); +} + +result +Calendar::SetTimeInMillisec(long long millisec) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->SetTimeInMillisecImpl(millisec); +} + +bool +Calendar::IsEquivalentTo(const Calendar& calendar) const +{ + bool isEquivalent = ((_isLenient == calendar.IsLenient()) && + (GetFirstDayOfWeek() == calendar.GetFirstDayOfWeek()) && + (GetMinDaysInFirstWeek() == calendar.GetMinDaysInFirstWeek()) && + (_timeZone == calendar.GetTimeZone())); + return isEquivalent; +} + +}; +}; // Tizen::Locales diff --git a/src/locales/FLclCurrency.cpp b/src/locales/FLclCurrency.cpp new file mode 100644 index 0000000..48dd48c --- /dev/null +++ b/src/locales/FLclCurrency.cpp @@ -0,0 +1,148 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclCurrency.cpp + * @brief This is the implementation file for Currency class. + */ + +// Includes +#include +#include +#include +#include +#include "FLcl_LocaleData.h" +#include "FLcl_CurrencyImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Locales +{ + + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Currency class Lifecycle + +Currency::Currency(void) + : __currencyCodeSymbol() + , __pCurrencyImpl(null) +{ +} + + +Currency::~Currency(void) +{ +} + + +result +Currency::Construct(const Locale& locale) +{ + result r = _CurrencyImpl::GetCurrencyCodeSymbol(locale, __currencyCodeSymbol); + if (IsFailed(r)) + { + r = (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) ? E_UNSUPPORTED_OPERATION : E_INVALID_ARG; + } + return r; +} + + +result +Currency::Construct(const String& currencyCode) +{ + result r = (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) ? E_UNSUPPORTED_OPERATION : E_INVALID_ARG; + SysTryReturnResult(NID_LCL, !currencyCode.IsEmpty(), r, "Currency code is empty"); + + r = _CurrencyImpl::GetCurrencyCodeSymbol(currencyCode, __currencyCodeSymbol); + if (IsFailed(r)) + { + r = (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) ? E_UNSUPPORTED_OPERATION : E_INVALID_ARG; + } + return r; +} + + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Currency class operations + +String +Currency::GetCurrencyCode(void) const +{ + int index = 0; + String retStr; + + // if __currencyCodeSymbol is valid, will be in _ format + if (!__currencyCodeSymbol.IsEmpty()) + { + result r = __currencyCodeSymbol.IndexOf(L'_', 0, index); // get index till '_' + if (r != E_OBJ_NOT_FOUND) + { + __currencyCodeSymbol.SubString(0, index, retStr); // get string till index, it will be Currency Code + } + } + + return retStr; +} + + +String +Currency::GetSymbol(void) const +{ + int index = 0; + String retStr; + + // if __currencyCodeSymbol is valid, will be in _ format + if (!__currencyCodeSymbol.IsEmpty()) + { + result r = __currencyCodeSymbol.IndexOf(L'_', 0, index); // get index till '_' + if (r != E_OBJ_NOT_FOUND) + { + __currencyCodeSymbol.SubString(index + 1, retStr); // get string after index, it will be Currency symbol + } + } + + return retStr; +} + +bool +Currency::Equals(const Object& obj) const +{ + const Currency* pOtherCurrency = dynamic_cast< const Currency* >(&obj); + if (pOtherCurrency) + { + return __currencyCodeSymbol.Equals(pOtherCurrency->__currencyCodeSymbol, true); + } + return false; +} + +int +Currency::GetHashCode(void) const +{ + return __currencyCodeSymbol.GetHashCode(); +} + +IList* +Currency::GetAvailableCurrenciesN(void) +{ + return _CurrencyImpl::GetAvailableCurrenciesN(); +} + + +}; +}; // Tizen::Locales + diff --git a/src/locales/FLclDateTimeFormatter.cpp b/src/locales/FLclDateTimeFormatter.cpp new file mode 100644 index 0000000..cdbd249 --- /dev/null +++ b/src/locales/FLclDateTimeFormatter.cpp @@ -0,0 +1,182 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclDateTimeFormatter.cpp + * @brief This is the implementation file for DateTimeFormatter class. + */ + +// Includes +#include +#include +#include +#include "FLcl_DateTimeFormatterImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +namespace Tizen { namespace Locales +{ +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Static Methods + +DateTimeFormatter::DateTimeFormatter(void) + : __pNumberFormat(null) + , __pCalendar(null) + , __pDateTimeFormatterImpl(null) +{ +} + +DateTimeFormatter::~DateTimeFormatter(void) +{ + delete __pDateTimeFormatterImpl; +} + +DateTimeFormatter* +DateTimeFormatter::CreateDateFormatterN(DateTimeStyle style) +{ + if (style == DATE_TIME_STYLE_NONE) + { + style = DATE_TIME_STYLE_DEFAULT; + } + + return _DateTimeFormatterImpl::CreateInstanceN(style, DATE_TIME_STYLE_NONE); +} + + +DateTimeFormatter* +DateTimeFormatter::CreateDateFormatterN(const Locale& locale, DateTimeStyle style) +{ + if (style == DATE_TIME_STYLE_NONE) + { + style = DATE_TIME_STYLE_DEFAULT; + } + + return _DateTimeFormatterImpl::CreateInstanceN(locale, style, DATE_TIME_STYLE_NONE); +} + + +DateTimeFormatter* +DateTimeFormatter::CreateTimeFormatterN(DateTimeStyle style) +{ + if (style == DATE_TIME_STYLE_NONE) + { + style = DATE_TIME_STYLE_DEFAULT; + } + + return _DateTimeFormatterImpl::CreateInstanceN(DATE_TIME_STYLE_NONE, style); +} + + +DateTimeFormatter* +DateTimeFormatter::CreateTimeFormatterN(const Locale& locale, DateTimeStyle style) +{ + if (style == DATE_TIME_STYLE_NONE) + { + style = DATE_TIME_STYLE_DEFAULT; + } + + return _DateTimeFormatterImpl::CreateInstanceN(locale, DATE_TIME_STYLE_NONE, style); +} + + +DateTimeFormatter* +DateTimeFormatter::CreateDateTimeFormatterN(DateTimeStyle dateStyle, DateTimeStyle timeStyle) +{ + if (dateStyle == DATE_TIME_STYLE_NONE) + { + dateStyle = DATE_TIME_STYLE_DEFAULT; + } + + if (timeStyle == DATE_TIME_STYLE_NONE) + { + timeStyle = DATE_TIME_STYLE_DEFAULT; + } + + return _DateTimeFormatterImpl::CreateInstanceN(dateStyle, timeStyle); +} + + +DateTimeFormatter* +DateTimeFormatter::CreateDateTimeFormatterN(const Locale& locale, DateTimeStyle dateStyle, DateTimeStyle timeStyle) +{ + if (dateStyle == DATE_TIME_STYLE_NONE) + { + dateStyle = DATE_TIME_STYLE_DEFAULT; + } + + if (timeStyle == DATE_TIME_STYLE_NONE) + { + timeStyle = DATE_TIME_STYLE_DEFAULT; + } + + return _DateTimeFormatterImpl::CreateInstanceN(locale, dateStyle, timeStyle); +} + + +result +DateTimeFormatter::Format(const DateTime& date, String& strBuf) const +{ + SysAssertf(__pDateTimeFormatterImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeFormatterImpl->Format(date, strBuf); +} + +result +DateTimeFormatter::Format(const Calendar& calendar, String& strBuf) const +{ + SysAssertf(__pDateTimeFormatterImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeFormatterImpl->Format(calendar, strBuf); +} + +result +DateTimeFormatter::ApplyPattern(const String& pattern) +{ + SysAssertf(__pDateTimeFormatterImpl != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_LCL, !pattern.IsEmpty(), E_INVALID_ARG, "Invalid argument is used. Input pattern is empty"); + + return __pDateTimeFormatterImpl->ApplyPattern(pattern); +} + + +String +DateTimeFormatter::GetPattern(void) const +{ + SysAssertf(__pDateTimeFormatterImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeFormatterImpl->GetPattern(); +} + + +const DateTimeSymbols* +DateTimeFormatter::GetDateTimeSymbols(void) const +{ + SysAssertf(__pDateTimeFormatterImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeFormatterImpl->GetDateTimeSymbols(); +} + + +void +DateTimeFormatter::SetDateTimeSymbols(const DateTimeSymbols& newSymbols) +{ + SysAssertf(__pDateTimeFormatterImpl != null, "Not yet constructed! Construct() should be called before use."); + __pDateTimeFormatterImpl->SetDateTimeSymbols(newSymbols); +} + + +}; +}; // Tizen::Locales + diff --git a/src/locales/FLclDateTimeSymbols.cpp b/src/locales/FLclDateTimeSymbols.cpp new file mode 100644 index 0000000..ddf2eaf --- /dev/null +++ b/src/locales/FLclDateTimeSymbols.cpp @@ -0,0 +1,239 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclDateTimeSymbols.cpp + * @brief This is the implementation file for DateTimeSymbols class. + */ + +#include + +#include +#include +#include +#include "FLcl_DateTimeSymbolsImpl.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +namespace Tizen { namespace Locales +{ + + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Public Methods + +DateTimeSymbols::DateTimeSymbols(void) + : __pDateTimeSymbolsImpl(null) +{ +} + +DateTimeSymbols::~DateTimeSymbols(void) +{ + delete __pDateTimeSymbolsImpl; + __pDateTimeSymbolsImpl = null; +} + +result +DateTimeSymbols::AddTimeZoneName(const Tizen::Base::String& timeZoneId, const Tizen::Base::String& concatenatedTimeZoneName) +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + + return __pDateTimeSymbolsImpl->AddTimeZoneName(timeZoneId, concatenatedTimeZoneName); +} + + +result +DateTimeSymbols::Construct(const Locale& locale, CalendarType calendarType) +{ + SysAssertf(__pDateTimeSymbolsImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + std::unique_ptr< _DateTimeSymbolsImpl > pDateTimeSymbolsImpl(new (std::nothrow) _DateTimeSymbolsImpl); + SysTryReturnResult(NID_LCL, pDateTimeSymbolsImpl != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + result r = pDateTimeSymbolsImpl->Initialize(locale, calendarType); + if (IsFailed(r)) + { + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + return E_UNSUPPORTED_OPERATION; + } + return E_INVALID_ARG; + } + + __pDateTimeSymbolsImpl = pDateTimeSymbolsImpl.release(); + return E_SUCCESS; +} + + +result +DateTimeSymbols::Construct(CalendarType calendarType) +{ + // Object is not allowed to construct twice + SysAssertf(__pDateTimeSymbolsImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + std::unique_ptr< _DateTimeSymbolsImpl > pDateTimeSymbolsImpl(new (std::nothrow) _DateTimeSymbolsImpl); + SysTryReturnResult(NID_LCL, pDateTimeSymbolsImpl != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + result r = pDateTimeSymbolsImpl->Initialize(calendarType); + if (IsFailed(r)) + { + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + return E_UNSUPPORTED_OPERATION; + } + return E_INVALID_ARG; + } + + __pDateTimeSymbolsImpl = pDateTimeSymbolsImpl.release(); + return E_SUCCESS; +} + + +result +DateTimeSymbols::Construct(const DateTimeSymbols& other) +{ + SysAssertf(__pDateTimeSymbolsImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + if (other.__pDateTimeSymbolsImpl) + { + __pDateTimeSymbolsImpl = new (std::nothrow) _DateTimeSymbolsImpl; + SysTryReturnResult(NID_LCL, __pDateTimeSymbolsImpl != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + __pDateTimeSymbolsImpl->Set(other.__pDateTimeSymbolsImpl); + } + + return E_SUCCESS; +} + +const IList* +DateTimeSymbols::GetAmPm(void) const +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->GetAmPm(); +} + +result +DateTimeSymbols::SetAmPm(const String& amPm) +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->SetAmPm(amPm); +} + +const IList* +DateTimeSymbols::GetEras(void) const +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->GetEras(); +} + +result +DateTimeSymbols::SetEras(const String& eras) +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->SetEras(eras); +} + +const IList* +DateTimeSymbols::GetMonths(void) const +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->GetMonths(); +} + +result +DateTimeSymbols::SetMonths(const String& months) +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->SetMonths(months); +} + +const IList* +DateTimeSymbols::GetShortMonths(void) const +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use.");; + return __pDateTimeSymbolsImpl->GetShortMonths(); +} + +result +DateTimeSymbols::SetShortMonths(const String& shortMonths) +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->SetShortMonths(shortMonths); +} + +const IList* +DateTimeSymbols::GetWeekdays(void) const +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->GetWeekdays(); +} + +result +DateTimeSymbols::SetWeekdays(const String& weekdays) +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->SetWeekdays(weekdays); +} + + +const IList* +DateTimeSymbols::GetShortWeekdays(void) const +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->GetShortWeekdays(); +} + +result +DateTimeSymbols::SetShortWeekdays(const String& shortWeekdays) +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->SetShortWeekdays(shortWeekdays); +} + + +String +DateTimeSymbols::GetTimeZoneName(Tizen::Base::String& timeZoneId, int timeZoneStyle) const +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pDateTimeSymbolsImpl->GetTimeZoneName(timeZoneId, timeZoneStyle); +} + + +result +DateTimeSymbols::SetTimeZoneName(const Tizen::Base::String& timeZoneId, const Tizen::Base::String& concatenatedTimeZoneName) +{ + SysAssertf(__pDateTimeSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + + return __pDateTimeSymbolsImpl->SetTimeZoneName(timeZoneId, concatenatedTimeZoneName); +} + +WcharBuffer* +DateTimeSymbols::GetNonLocalizedDateTimePatternN(void) +{ + ClearLastResult(); + return _DateTimeSymbolsImpl::GetNonLocalizedDateTimePatternN(); // Get Non Localized DateTime Pattern, fixed pattern +} + +}; +}; // Tizen::Locales + diff --git a/src/locales/FLclGregorianCalendar.cpp b/src/locales/FLclGregorianCalendar.cpp new file mode 100644 index 0000000..c96814a --- /dev/null +++ b/src/locales/FLclGregorianCalendar.cpp @@ -0,0 +1,377 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FLclGregorianCalendar.cpp +* @brief This is the implementation file for GregorianCalendar class. +*/ + +#include + +#include +#include +#include +#include "FLcl_CalendarImpl.h" +#include "FLcl_LocaleManagerImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +////////////////////////////////////////////////////////////////////////////////// +// Set monthLength[] +const int GregorianCalendar::MONTH_LENGTH[24] = +{ + 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, // Days in month in normal year + 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 // Days in month in leap year +}; + +// Set cumulative number of days at first day of month +const int GregorianCalendar::NUM_DAYS[24] = +{ + 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, // Cumulative number of days at first day of month in normal year + 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 // Cumulative number of days at first day of month in leap year +}; + +GregorianCalendar::GregorianCalendar(void) + : __normalizedGregorianCutover(DEFAULT_GREGORIAN_CUTOVER) + , __gregorianCutoverYear(1582) + , __cutoverJulianDay(GregorianCalendar::CUTOVER_JULIAN_DAY) + , __pGregorianCalendarImpl(null) +{ +} + +GregorianCalendar::~GregorianCalendar(void) +{ + delete _pCalendarImpl; + _pCalendarImpl = null; +} + +// This method is copy constructor +result +GregorianCalendar::Construct(const GregorianCalendar& gc) +{ + // Object is not allowed to construct twice + SysAssertf(_pCalendarImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + if (gc._pCalendarImpl != null) + { + std::unique_ptr< Calendar > pCalendar(gc._pCalendarImpl->CloneN()); + SysTryReturnResult(NID_LCL, pCalendar != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + _pCalendarImpl = dynamic_cast< _CalendarImpl* >(pCalendar.get()); + if (_pCalendarImpl != null) + { + pCalendar.release(); + + __cutoverJulianDay = gc.__cutoverJulianDay; + __normalizedGregorianCutover = gc.__normalizedGregorianCutover; + __gregorianCutoverYear = gc.__gregorianCutoverYear; + } + } + + return E_SUCCESS; +} + +result +GregorianCalendar::Construct(void) +{ + return Construct(TimeZone::GetGmtTimeZone(), _LocaleManagerImpl::GetSystemLocale()); +} + +result +GregorianCalendar::Construct(const TimeZone& timezone) +{ + return Construct(timezone, _LocaleManagerImpl::GetSystemLocale()); +} + +result +GregorianCalendar::Construct(const Locale& locale) +{ + return Construct(TimeZone::GetGmtTimeZone(), locale); +} + +result +GregorianCalendar::Construct(const TimeZone& timezone, const Locale& locale) +{ + // Object is not allowed to construct twice + SysAssertf(_pCalendarImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + std::unique_ptr< _CalendarImpl > pCalendarImpl(new (std::nothrow) _CalendarImpl); + SysTryReturnResult(NID_LCL, pCalendarImpl != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + result r = pCalendarImpl->Construct(timezone, locale); + if (!IsFailed(r)) + { + _pCalendarImpl = pCalendarImpl.release(); + + SetGregorianChange(GetGregorianChange()); + return E_SUCCESS; + } + + return r; +} + +result +GregorianCalendar::Construct(int year, int month, int day, int hourOfDay, int minute, int second) +{ + result r = Construct(TimeZone::GetGmtTimeZone(), _LocaleManagerImpl::GetSystemLocale()); + if (!IsFailed(r)) + { + r = SetTime(year, month, day, hourOfDay, minute, second); + } + return r; +} + +result +GregorianCalendar::Construct(const DateTime& dateTime) +{ + return Construct(dateTime.GetYear(), + dateTime.GetMonth(), + dateTime.GetDay(), + dateTime.GetHour(), + dateTime.GetMinute(), + dateTime.GetSecond()); +} + +result +GregorianCalendar::AddTimeField(TimeField field, int amount) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->AddTimeField(field, amount); +} + +void +GregorianCalendar::DayToFields(int day, int& year, int& month, int& dayOfMonth, int& dayOfWeek, int& dayOfYear) +{ + _CalendarImpl calImpl; + result r = calImpl.Construct(); + if (!IsFailed(r)) + { + r = calImpl.SetJulianDay(day + GregorianCalendar::EPOCH_START_AS_JULIAN_DAY); + if (!IsFailed(r)) + { + year = calImpl.GetTimeField(TIME_FIELD_YEAR); + month = calImpl.GetTimeField(TIME_FIELD_MONTH); + dayOfMonth = calImpl.GetTimeField(TIME_FIELD_DAY_OF_MONTH); + dayOfWeek = calImpl.GetTimeField(TIME_FIELD_DAY_OF_WEEK); + dayOfYear = calImpl.GetTimeField(TIME_FIELD_DAY_OF_YEAR); + } + } +} + +// This method gets the actual minimum value that a given field could have. +// For Gregorian calendar, it is the same as GetMinTimeField() and GetGreatestMinimum() +int +GregorianCalendar::GetActualMinTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetActualMinTimeField(field); +} + +// +// This method gets the actual maximum value that this field could have, given the current date. +// This method has a limitation (also GetActualMinimum). It will not behave properly at the extreme limits of Gregorian calendar's +// representable range. +// For calendars with the default Gregorian cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun +// Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT zones. +// As a result, if the calendar is set to Aug 1 292278994 AD, the actual maximum of DAY_OF_MONTH is 17, not 30. +// +int +GregorianCalendar::GetActualMaxTimeField(TimeField field) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetActualMaxTimeField(field); +} + +//This method returns the Gregorian cutover. +long long +GregorianCalendar::GetGregorianChange(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->GetGregorianChange(); +} + +CalendarType +GregorianCalendar::GetType(void) const +{ + return CALENDAR_GREGORIAN; +} + +result +GregorianCalendar::IsInDst(bool& isInDst) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->IsInDst(isInDst); +} + +bool +GregorianCalendar::IsLeapYear(int year) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->IsLeapYear(year); +} + +result +GregorianCalendar::Roll(TimeField field, int amount) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pCalendarImpl->Roll(field, amount); +} + +result +GregorianCalendar::SetGregorianChange(long long change) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + + result r = E_SUCCESS; + if (_pCalendarImpl->GetGregorianChange() != change) + { + r = _pCalendarImpl->SetGregorianChange(change); + } + + std::unique_ptr< Calendar > pCalendar(_pCalendarImpl->CloneN()); + SysTryReturnResult(NID_LCL, pCalendar != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + _CalendarImpl* pCalImpl = dynamic_cast< _CalendarImpl* >(pCalendar.get()); + if (pCalImpl != null) + { + DateTime dt; + dt.SetValue(change); + pCalImpl->SetTime(dt); + + __cutoverJulianDay = pCalImpl->GetJulianDay(); + // __normalizedGregorianCutover = change * Calendar::ONE_DAY_IN_MILLISEC; + + __gregorianCutoverYear = pCalImpl->GetTimeField(TIME_FIELD_YEAR); + if (pCalImpl->GetTimeField(TIME_FIELD_ERA) == GREGORIAN_CALENDAR_BC) + { + __gregorianCutoverYear = 1 - __gregorianCutoverYear; // update __gregorianCutoverYear for BC, 0 based + } + + long long julianDayFromEpoch = __cutoverJulianDay - GregorianCalendar::EPOCH_START_AS_JULIAN_DAY; + __normalizedGregorianCutover = julianDayFromEpoch * Calendar::ONE_DAY_IN_MILLISEC; + + // Handle the rare case of numeric overflow + if (julianDayFromEpoch < 0 && __normalizedGregorianCutover > 0) + { + __normalizedGregorianCutover = (julianDayFromEpoch + 1) * Calendar::ONE_DAY_IN_MILLISEC; + } + } + + return r; +} + +bool +GregorianCalendar::IsGregorian(void) const +{ + return true; +} + +long long +GregorianCalendar::GetNormalizedGregorianCutover(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return __normalizedGregorianCutover; +} + +int +GregorianCalendar::GetGregorianCutoverYear(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return __gregorianCutoverYear; +} + +int +GregorianCalendar::GetCutoverJulianDay(void) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + return __cutoverJulianDay; +} + +result +GregorianCalendar::GetTimeInMillisecFromEpoch(long long& millisec) const +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + result r = _pCalendarImpl->GetTimeInMillisec(millisec); + if (!IsFailed(r)) + { + millisec -= GregorianCalendar::EPOCH_OFFSET_IN_MILLISEC; + } + return r; +} + +result +GregorianCalendar::SetTimeInMillisecFromEpoch(long long millisec) +{ + SysAssertf(_pCalendarImpl != null, "Not yet constructed! Construct() should be called before use."); + + millisec += GregorianCalendar::EPOCH_OFFSET_IN_MILLISEC; + return _pCalendarImpl->SetTimeInMillisec(millisec); +} + +// added for backward compatibility +result +GregorianCalendar::RollWithSingleUnit(TimeField field, bool up) +{ + return E_UNSUPPORTED_OPERATION; +} + +// added for backward compatibility +result +GregorianCalendar::ComputeTimeFields(void) +{ + return E_UNSUPPORTED_OPERATION; +} + +// added for backward compatibility +result +GregorianCalendar::ComputeTime(void) +{ + return E_UNSUPPORTED_OPERATION; +} + +// added for backward compatibility +int +GregorianCalendar::GetMonthLength(int extendedYear, int month) const +{ + SetLastResult(E_UNSUPPORTED_OPERATION); + return -1; +} + +// added for backward compatibility +int +GregorianCalendar::HandleGetLimit(TimeField field, CalendarLimitType limitType) const +{ + SetLastResult(E_UNSUPPORTED_OPERATION); + return -1; +} + +// added for backward compatibility +Calendar* +GregorianCalendar::CloneN(void) const +{ + SetLastResult(E_UNSUPPORTED_OPERATION); + return null; +} + + +}; +}; // Tizen::Locales diff --git a/src/locales/FLclLocale.cpp b/src/locales/FLclLocale.cpp new file mode 100644 index 0000000..be3ced3 --- /dev/null +++ b/src/locales/FLclLocale.cpp @@ -0,0 +1,1072 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclLocale.cpp + * @brief This is the implementation file for Locale class. + */ + +#include + +#include +#include "FBase_StringConverter.h" +#include + +#include "FLcl_LocaleImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +static const char* LanguageCodeString3LetterArray[LANGUAGE_MAX] = +{ + "aar", /**< Afar */ + "abk", /**< Abkhazian */ + "ace", /**< Achinese */ + "ach", /**< Acoli */ + "ada", /**< Adangme */ + "ady", /**< Adyghe; Adygei */ + "afa", /**< Afro-Asiatic languages */ + "afh", /**< Afrihili */ + "afr", /**< Afrikaans */ + "ain", /**< Ainu */ + "aka", /**< Akan */ + "akk", /**< Akkadian */ + "sqi", /**< Albanian */ + "ale", /**< Aleut */ + "alg", /**< Algonquian languages */ + "alt", /**< Southern Altai */ + "amh", /**< Amharic */ + "ang", /**< English, Old (ca.450-1100) */ + "anp", /**< Angika */ + "apa", /**< Apache languages */ + "ara", /**< Arabic */ + "arc", /**< Official Aramaic (700-300 BCE); Imperial Aramaic (700-300 BCE) */ + "arg", /**< Aragonese */ + "hye", /**< Armenian */ + "arn", /**< Mapudungun; Mapuche */ + "arp", /**< Arapaho */ + "art", /**< Artificial languages */ + "arw", /**< Arawak */ + "asm", /**< Assamese */ + "ast", /**< Asturian; Bable; Leonese; Asturleonese */ + "ath", /**< Athapascan languages */ + "aus", /**< Australian languages */ + "ava", /**< Avaric */ + "ave", /**< Avestan */ + "awa", /**< Awadhi */ + "aym", /**< Aymara */ + "aze", /**< Azerbaijani */ + "aze-arab", /**< Azerbaijani (Arabic) */ + "aze-cyrl", /**< Azerbaijani (Cyrillic) */ + "aze-latn", /**< Azerbaijani (Latin) */ + "bad", /**< Banda languages */ + "bai", /**< Bamileke languages */ + "bak", /**< Bashkir */ + "bal", /**< Baluchi */ + "bam", /**< Bambara */ + "ban", /**< Balinese */ + "eus", /**< Basque */ + "bas", /**< Basa */ + "bat", /**< Baltic languages */ + "bej", /**< Beja; Bedawiyet */ + "bel", /**< Belarusian */ + "bem", /**< Bemba */ + "ben", /**< Bengali */ + "ber", /**< Berber languages */ + "bho", /**< Bhojpuri */ + "bih", /**< Bihari */ + "bik", /**< Bikol */ + "bin", /**< Bini; Edo */ + "bis", /**< Bislama */ + "bla", /**< Siksika */ + "bnt", /**< Bantu (Other) */ + "bos", /**< Bosnian */ + "bra", /**< Braj */ + "bre", /**< Breton */ + "btk", /**< Batak languages */ + "bua", /**< Buriat */ + "bug", /**< Buginese */ + "bul", /**< Bulgarian */ + "mya", /**< Burmese */ + "byn", /**< Blin; Bilin */ + "cad", /**< Caddo */ + "cai", /**< Central American Indian languages */ + "car", /**< Galibi Carib */ + "cat", /**< Catalan; Valencian */ + "cau", /**< Caucasian languages */ + "ceb", /**< Cebuano */ + "cel", /**< Celtic languages */ + "cha", /**< Chamorro */ + "chb", /**< Chibcha */ + "che", /**< Chechen */ + "chg", /**< Chagatai */ + "zho", /**< Chinese */ + "zho-hans", /**< Chinese (Simplified) */ + "zho-hant", /**< Chinese (Traditional) */ + "chk", /**< Chuukese */ + "chm", /**< Mari */ + "chn", /**< Chinook jargon */ + "cho", /**< Choctaw */ + "chp", /**< Chipewyan; Dene Suline */ + "chr", /**< Cherokee */ + "chu", /**< Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic */ + "chv", /**< Chuvash */ + "chy", /**< Cheyenne */ + "cmc", /**< Chamic languages */ + "cop", /**< Coptic */ + "cor", /**< Cornish */ + "cos", /**< Corsican */ + "cpe", /**< Creoles and pidgins, English based */ + "cpf", /**< Creoles and pidgins, French-based */ + "cpp", /**< Creoles and pidgins, Portuguese-based */ + "cre", /**< Cree */ + "crh", /**< Crimean Tatar; Crimean Turkish */ + "crp", /**< Creoles and pidgins */ + "csb", /**< Kashubian */ + "cus", /**< Cushitic languages */ + "ces", /**< Czech */ + "dak", /**< Dakota */ + "dan", /**< Danish */ + "dar", /**< Dargwa */ + "day", /**< Land Dayak languages */ + "del", /**< Delaware */ + "den", /**< Slave (Athapascan) */ + "dgr", /**< Dogrib */ + "din", /**< Dinka */ + "div", /**< Divehi; Dhivehi; Maldivian */ + "doi", /**< Dogri */ + "dra", /**< Dravidian languages */ + "dsb", /**< Lower Sorbian */ + "dua", /**< Duala */ + "dum", /**< Dutch, Middle (ca.1050-1350) */ + "nld", /**< Dutch; Flemish */ + "dyu", /**< Dyula */ + "dzo", /**< Dzongkha */ + "efi", /**< Efik */ + "egy", /**< Egyptian (Ancient) */ + "eka", /**< Ekajuk */ + "elx", /**< Elamite */ + "eng", /**< English */ + "enm", /**< English, Middle (1100-1500) */ + "epo", /**< Esperanto */ + "est", /**< Estonian */ + "ewe", /**< Ewe */ + "ewo", /**< Ewondo */ + "fan", /**< Fang */ + "fao", /**< Faroese */ + "fat", /**< Fanti */ + "fij", /**< Fijian */ + "fil", /**< Filipino; Pilipino */ + "fin", /**< Finnish */ + "fiu", /**< Finno-Ugrian languages */ + "fon", /**< Fon */ + "fra", /**< French */ + "frm", /**< French, Middle (ca.1400-1600) */ + "fro", /**< French, Old (842-ca.1400) */ + "frr", /**< Northern Frisian */ + "frs", /**< Eastern Frisian */ + "fry", /**< Western Frisian */ + "ful", /**< Fulah */ + "fur", /**< Friulian */ + "gaa", /**< Ga */ + "gay", /**< Gayo */ + "gba", /**< Gbaya */ + "gem", /**< Germanic languages */ + "kat", /**< Georgian */ + "deu", /**< German */ + "gez", /**< Geez */ + "gil", /**< Gilbertese */ + "gla", /**< Gaelic; Scottish Gaelic */ + "gle", /**< Irish */ + "glg", /**< Galician */ + "glv", /**< Manx */ + "gmh", /**< German, Middle High (ca.1050-1500) */ + "goh", /**< German, Old High (ca.750-1050) */ + "gon", /**< Gondi */ + "gor", /**< Gorontalo */ + "got", /**< Gothic */ + "grb", /**< Grebo */ + "grc", /**< Greek, Ancient (to 1453) */ + "ell", /**< Greek, Modern (1453-) */ + "grn", /**< Guarani */ + "gsw", /**< Swiss German; Alemannic; Alsatian */ + "guj", /**< Gujarati */ + "gwi", /**< Gwich'in */ + "hai", /**< Haida */ + "hat", /**< Haitian; Haitian Creole */ + "hau", /**< Hausa */ + "hau-latn", /**< Hausa (Latin) */ + "haw", /**< Hawaiian */ + "heb", /**< Hebrew */ + "her", /**< Herero */ + "hil", /**< Hiligaynon */ + "him", /**< Himachali */ + "hin", /**< Hindi */ + "hit", /**< Hittite */ + "hmn", /**< Hmong */ + "hmo", /**< Hiri Motu */ + "hrv", /**< Croatian */ + "hsb", /**< Upper Sorbian */ + "hun", /**< Hungarian */ + "hup", /**< Hupa */ + "iba", /**< Iban */ + "ibo", /**< Igbo */ + "isl", /**< Icelandic */ + "ido", /**< Ido */ + "iii", /**< Sichuan Yi; Nuosu */ + "ijo", /**< Ijo languages */ + "iku", /**< Inuktitut */ + "ile", /**< Interlingue; Occidental */ + "ilo", /**< Iloko */ + "ina", /**< Interlingua (International Auxiliary Language Association) */ + "inc", /**< Indic languages */ + "ind", /**< Indonesian */ + "ine", /**< Indo-European languages */ + "inh", /**< Ingush */ + "ipk", /**< Inupiaq */ + "ira", /**< Iranian languages */ + "iro", /**< Iroquoian languages */ + "ita", /**< Italian */ + "jav", /**< Javanese */ + "jbo", /**< Lojban */ + "jpn", /**< Japanese */ + "jpr", /**< Judeo-Persian */ + "jrb", /**< Judeo-Arabic */ + "kaa", /**< Kara-Kalpak */ + "kab", /**< Kabyle */ + "kac", /**< Kachin; Jingpho */ + "kal", /**< Kalaallisut; Greenlandic */ + "kam", /**< Kamba */ + "kan", /**< Kannada */ + "kar", /**< Karen languages */ + "kas", /**< Kashmiri */ + "kau", /**< Kanuri */ + "kaw", /**< Kawi */ + "kaz", /**< Kazakh */ + "kaz-cyrl", /**< Kazakh (Cyrillic) */ + "kbd", /**< Kabardian */ + "kha", /**< Khasi */ + "khi", /**< Khoisan languages */ + "khm", /**< Central Khmer */ + "kho", /**< Khotanese; Sakan */ + "kik", /**< Kikuyu; Gikuyu */ + "kin", /**< Kinyarwanda */ + "kir", /**< Kirghiz; Kyrgyz */ + "kmb", /**< Kimbundu */ + "kok", /**< Konkani */ + "kom", /**< Komi */ + "kon", /**< Kongo */ + "kor", /**< Korean */ + "kos", /**< Kosraean */ + "kpe", /**< Kpelle */ + "krc", /**< Karachay-Balkar */ + "krl", /**< Karelian */ + "kro", /**< Kru languages */ + "kru", /**< Kurukh */ + "kua", /**< Kuanyama; Kwanyama */ + "kum", /**< Kumyk */ + "kur", /**< Kurdish */ + "kut", /**< Kutenai */ + "lad", /**< Ladino */ + "lah", /**< Lahnda */ + "lam", /**< Lamba */ + "lao", /**< Lao */ + "lat", /**< Latin */ + "lav", /**< Latvian */ + "lez", /**< Lezghian */ + "lim", /**< Limburgan; Limburger; Limburgish */ + "lin", /**< Lingala */ + "lit", /**< Lithuanian */ + "lol", /**< Mongo */ + "loz", /**< Lozi */ + "ltz", /**< Luxembourgish; Letzeburgesch */ + "lua", /**< Luba-Lulua */ + "lub", /**< Luba-Katanga */ + "lug", /**< Ganda */ + "lui", /**< Luiseno */ + "lun", /**< Lunda */ + "luo", /**< Luo (Kenya and Tanzania) */ + "lus", /**< Lushai */ + "mkd", /**< Macedonian */ + "mad", /**< Madurese */ + "mag", /**< Magahi */ + "mah", /**< Marshallese */ + "mai", /**< Maithili */ + "mak", /**< Makasar */ + "mal", /**< Malayalam */ + "man", /**< Mandingo */ + "mri", /**< Maori */ + "map", /**< Austronesian languages */ + "mar", /**< Marathi */ + "mas", /**< Masai */ + "msa", /**< Malay */ + "mdf", /**< Moksha */ + "mdr", /**< Mandar */ + "men", /**< Mende */ + "mga", /**< Irish, Middle (900-1200) */ + "mic", /**< Mi'kmaq; Micmac */ + "min", /**< Minangkabau */ + "mis", /**< Uncoded languages */ + "mkh", /**< Mon-Khmer languages */ + "mlg", /**< Malagasy */ + "mlt", /**< Maltese */ + "mnc", /**< Manchu */ + "mni", /**< Manipuri */ + "mno", /**< Manobo languages */ + "moh", /**< Mohawk */ + "mon", /**< Mongolian */ + "mos", /**< Mossi */ + "mul", /**< Multiple languages */ + "mun", /**< Munda languages */ + "mus", /**< Creek */ + "mwl", /**< Mirandese */ + "mwr", /**< Marwari */ + "myn", /**< Mayan languages */ + "myv", /**< Erzya */ + "nah", /**< Nahuatl languages */ + "nai", /**< North American Indian languages */ + "nap", /**< Neapolitan */ + "nau", /**< Nauru */ + "nav", /**< Navajo; Navaho */ + "nbl", /**< Ndebele, South; South Ndebele */ + "nde", /**< Ndebele, North; North Ndebele */ + "ndo", /**< Ndonga */ + "nds", /**< Low German; Low Saxon; German, Low; Saxon, Low */ + "nep", /**< Nepali */ + "new", /**< Nepal Bhasa; Newari */ + "nia", /**< Nias */ + "nic", /**< Niger-Kordofanian languages */ + "niu", /**< Niuean */ + "nno", /**< Norwegian Nynorsk; Nynorsk, Norwegian */ + "nob", /**< Bokmal, Norwegian; Norwegian Bokmal */ + "nog", /**< Nogai */ + "non", /**< Norse, Old */ + "nor", /**< Norwegian */ + "nqo", /**< N'Ko */ + "nso", /**< Pedi; Sepedi; Northern Sotho */ + "nub", /**< Nubian languages */ + "nwc", /**< Classical Newari; Old Newari; Classical Nepal Bhasa */ + "nya", /**< Chichewa; Chewa; Nyanja */ + "nym", /**< Nyamwezi */ + "nyn", /**< Nyankole */ + "nyo", /**< Nyoro */ + "nzi", /**< Nzima */ + "oci", /**< Occitan (post 1500); Provencal */ + "oji", /**< Ojibwa */ + "ori", /**< Oriya */ + "orm", /**< Oromo */ + "osa", /**< Osage */ + "oss", /**< Ossetian; Ossetic */ + "ota", /**< Turkish, Ottoman (1500-1928) */ + "oto", /**< Otomian languages */ + "paa", /**< Papuan languages */ + "pag", /**< Pangasinan */ + "pal", /**< Pahlavi */ + "pam", /**< Pampanga; Kapampangan */ + "pan", /**< Panjabi; Punjabi */ + "pan-arab", /**< Panjabi; Punjabi (Arabic) */ + "pan-guru", /**< Panjabi; Punjabi (Gurmukhi) */ + "pap", /**< Papiamento */ + "pau", /**< Palauan */ + "peo", /**< Persian, Old (ca.600-400 B.C.) */ + "fas", /**< Persian */ + "phi", /**< Philippine languages */ + "phn", /**< Phoenician */ + "pli", /**< Pali */ + "pol", /**< Polish */ + "pon", /**< Pohnpeian */ + "por", /**< Portuguese */ + "pra", /**< Prakrit languages */ + "pro", /**< Provencal, Old (to 1500) */ + "pus", /**< Pushto; Pashto */ + "qaa-qtz", /**< Reserved for local use */ + "que", /**< Quechua */ + "raj", /**< Rajasthani */ + "rap", /**< Rapanui */ + "rar", /**< Rarotongan; Cook Islands Maori */ + "roa", /**< Romance languages */ + "roh", /**< Romansh */ + "rom", /**< Romany */ + "ron", /**< Romanian; Moldavian; Moldovan */ + "run", /**< Rundi */ + "rup", /**< Aromanian; Arumanian; Macedo-Romanian */ + "rus", /**< Russian */ + "sad", /**< Sandawe */ + "sag", /**< Sango */ + "sah", /**< Yakut */ + "sai", /**< South American Indian (Other) */ + "sal", /**< Salishan languages */ + "sam", /**< Samaritan Aramaic */ + "san", /**< Sanskrit */ + "sas", /**< Sasak */ + "sat", /**< Santali */ + "scn", /**< Sicilian */ + "sco", /**< Scots */ + "sel", /**< Selkup */ + "sem", /**< Semitic languages */ + "sga", /**< Irish, Old (to 900) */ + "sgn", /**< Sign Languages */ + "shn", /**< Shan */ + "sid", /**< Sidamo */ + "sin", /**< Sinhala; Sinhalese */ + "sio", /**< Siouan languages */ + "sit", /**< Sino-Tibetan languages */ + "sla", /**< Slavic languages */ + "slk", /**< Slovak */ + "slv", /**< Slovenian */ + "sma", /**< Southern Sami */ + "sme", /**< Northern Sami */ + "smi", /**< Sami languages */ + "smj", /**< Lule Sami */ + "smn", /**< Inari Sami */ + "smo", /**< Samoan */ + "sms", /**< Skolt Sami */ + "sna", /**< Shona */ + "snd", /**< Sindhi */ + "snk", /**< Soninke */ + "sog", /**< Sogdian */ + "som", /**< Somali */ + "son", /**< Songhai languages */ + "sot", /**< Sotho, Southern */ + "spa", /**< Spanish; Castilian */ + "srd", /**< Sardinian */ + "srn", /**< Sranan Tongo */ + "srp", /**< Serbian */ + "srp-cyrl", /**< Serbian (Cyrillic) */ + "srp-latn", /**< Serbian (Latin) */ + "srr", /**< Serer */ + "ssa", /**< Nilo-Saharan languages */ + "ssw", /**< Swati */ + "suk", /**< Sukuma */ + "sun", /**< Sundanese */ + "sus", /**< Susu */ + "sux", /**< Sumerian */ + "swa", /**< Swahili */ + "swe", /**< Swedish */ + "syc", /**< Classical Syriac */ + "syr", /**< Syriac */ + "tah", /**< Tahitian */ + "tai", /**< Tai languages */ + "tam", /**< Tamil */ + "tat", /**< Tatar */ + "tel", /**< Telugu */ + "tem", /**< Timne */ + "ter", /**< Tereno */ + "tet", /**< Tetum */ + "tgk", /**< Tajik */ + "tgl", /**< Tagalog */ + "tha", /**< Thai */ + "bod", /**< Tibetan */ + "tig", /**< Tigre */ + "tir", /**< Tigrinya */ + "tiv", /**< Tiv */ + "tkl", /**< Tokelau */ + "tlh", /**< Klingon; tlhIngan-Hol */ + "tli", /**< Tlingit */ + "tmh", /**< Tamashek */ + "tog", /**< Tonga (Nyasa) */ + "ton", /**< Tonga (Tonga Islands) */ + "tpi", /**< Tok Pisin */ + "tsi", /**< Tsimshian */ + "tsn", /**< Tswana */ + "tso", /**< Tsonga */ + "tuk", /**< Turkmen */ + "tuk-cyrl", /**< Turkmen (Cyrillic) */ + "tuk-latn", /**< Turkmen (Latin) */ + "tum", /**< Tumbuka */ + "tup", /**< Tupi languages */ + "tur", /**< Turkish */ + "tut", /**< Altaic languages */ + "tvl", /**< Tuvalu */ + "twi", /**< Twi */ + "tyv", /**< Tuvinian */ + "udm", /**< Udmurt */ + "uga", /**< Ugaritic */ + "uig", /**< Uighur; Uyghur */ + "ukr", /**< Ukrainian */ + "umb", /**< Umbundu */ + "und", /**< Undetermined */ + "urd", /**< Urdu */ + "uzb", /**< Uzbek */ + "uzb-arab", /**< Uzbek (Arabic) */ + "uzb-cyrl", /**< Uzbek (Cyrillic) */ + "uzb-latn", /**< Uzbek (Latin) */ + "vai", /**< Vai */ + "ven", /**< Venda */ + "vie", /**< Vietnamese */ + "vls", /**< Vlaams; Flemish */ + "vol", /**< Volapuk */ + "vot", /**< Votic */ + "wak", /**< Wakashan languages */ + "wal", /**< Walamo */ + "war", /**< Waray */ + "was", /**< Washo */ + "cym", /**< Welsh */ + "wen", /**< Sorbian languages */ + "wln", /**< Walloon */ + "wol", /**< Wolof */ + "xal", /**< Kalmyk; Oirat */ + "xho", /**< Xhosa */ + "yao", /**< Yao */ + "yap", /**< Yapese */ + "yid", /**< Yiddish */ + "yor", /**< Yoruba */ + "ypk", /**< Yupik languages */ + "zap", /**< Zapotec */ + "zbl", /**< Blissymbols; Blissymbolics; Bliss */ + "zen", /**< Zenaga */ + "zha", /**< Zhuang; Chuang */ + "znd", /**< Zande languages */ + "zul", /**< Zulu */ + "zun", /**< Zuni */ + "zxx", /**< No linguistic content; Not applicable */ + "zza", /**< Zaza; Dimili; Dimli; Kirdki; Kirmanjki; Zazaki */ +}; + + +static const char CountryCodeString2LetterArray[COUNTRY_MAX][4] = +{ + "AF", /**< AFGHANISTAN */ + "AX", /**< ALAND ISLANDS */ + "AL", /**< ALBANIA */ + "DZ", /**< ALGERIA */ + "AS", /**< AMERICAN SAMOA */ + "AD", /**< ANDORRA */ + "AO", /**< ANGOLA */ + "AI", /**< ANGUILLA */ + "AQ", /**< ANTARCTICA */ + "AG", /**< ANTIGUA AND BARBUDA */ + "AR", /**< ARGENTINA */ + "AM", /**< ARMENIA */ + "AW", /**< ARUBA */ + "AU", /**< AUSTRALIA */ + "AT", /**< AUSTRIA */ + "AZ", /**< AZERBAIJAN */ + "BS", /**< BAHAMAS */ + "BH", /**< BAHRAIN */ + "BD", /**< BANGLADESH */ + "BB", /**< BARBADOS */ + "BY", /**< BELARUS */ + "BE", /**< BELGIUM */ + "BZ", /**< BELIZE */ + "BJ", /**< BENIN */ + "BM", /**< BERMUDA */ + "BT", /**< BHUTAN */ + "BO", /**< BOLIVIA */ + "BA", /**< BOSNIA AND HERZEGOVINA */ + "BW", /**< BOTSWANA */ + "BV", /**< BOUVET ISLAND */ + "BR", /**< BRAZIL */ + "IO", /**< BRITISH INDIAN OCEAN TERRITORY */ + "BN", /**< BRUNEI DARUSSALAM */ + "BG", /**< BULGARIA */ + "BF", /**< BURKINA FASO */ + "BI", /**< BURUNDI */ + "KH", /**< CAMBODIA */ + "CM", /**< CAMEROON */ + "CA", /**< CANADA */ + "CV", /**< CAPE VERDE */ + "KY", /**< CAYMAN ISLANDS */ + "CF", /**< CENTRAL AFRICAN REPUBLIC */ + "TD", /**< CHAD */ + "CL", /**< CHILE */ + "CN", /**< CHINA */ + "CX", /**< CHRISTMAS ISLAND */ + "CC", /**< COCOS (KEELING) ISLANDS */ + "CO", /**< COLOMBIA */ + "KM", /**< COMOROS */ + "CG", /**< CONGO */ + "CD", /**< CONGO, THE DEMOCRATIC REPUBLIC OF THE */ + "CK", /**< COOK ISLANDS */ + "CR", /**< COSTA RICA */ + "CI", /**< COTE D'IVOIRE */ + "HR", /**< CROATIA */ + "CU", /**< CUBA */ + "CY", /**< CYPRUS */ + "CZ", /**< CZECH REPUBLIC */ + "DK", /**< DENMARK */ + "DJ", /**< DJIBOUTI */ + "DM", /**< DOMINICA */ + "DO", /**< DOMINICAN REPUBLIC */ + "EC", /**< ECUADOR */ + "EG", /**< EGYPT */ + "SV", /**< EL SALVADOR */ + "GQ", /**< EQUATORIAL GUINEA */ + "ER", /**< ERITREA */ + "EE", /**< ESTONIA */ + "ET", /**< ETHIOPIA */ + "FK", /**< FALKLAND ISLANDS (MALVINAS) */ + "FO", /**< FAROE ISLANDS */ + "FJ", /**< FIJI */ + "FI", /**< FINLAND */ + "FR", /**< FRANCE */ + "GF", /**< FRENCH GUIANA */ + "PF", /**< FRENCH POLYNESIA */ + "TF", /**< FRENCH SOUTHERN TERRITORIES */ + "GA", /**< GABON */ + "GM", /**< GAMBIA */ + "GE", /**< GEORGIA */ + "DE", /**< GERMANY */ + "GH", /**< GHANA */ + "GI", /**< GIBRALTAR */ + "GR", /**< GREECE */ + "GL", /**< GREENLAND */ + "GD", /**< GRENADA */ + "GP", /**< GUADELOUPE */ + "GU", /**< GUAM */ + "GT", /**< GUATEMALA */ + "GN", /**< GUINEA */ + "GW", /**< GUINEA-BISSAU */ + "GY", /**< GUYANA */ + "HT", /**< HAITI */ + "HM", /**< HEARD ISLAND AND MCDONALD ISLANDS */ + "VA", /**< HOLY SEE (VATICAN CITY STATE) */ + "HN", /**< HONDURAS */ + "HK", /**< HONG KONG */ + "HU", /**< HUNGARY */ + "IS", /**< ICELAND */ + "IN", /**< INDIA */ + "ID", /**< INDONESIA */ + "IR", /**< IRAN, ISLAMIC REPUBLIC OF */ + "IQ", /**< IRAQ */ + "IE", /**< IRELAND */ + "IL", /**< ISRAEL */ + "IT", /**< ITALY */ + "JM", /**< JAMAICA */ + "JP", /**< JAPAN */ + "JO", /**< JORDAN */ + "KZ", /**< KAZAKHSTAN */ + "KE", /**< KENYA */ + "KI", /**< KIRIBATI */ + "KP", /**< KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF */ + "KR", /**< KOREA, REPUBLIC OF */ + "KW", /**< KUWAIT */ + "KG", /**< KYRGYZSTAN */ + "LA", /**< LAO PEOPLE'S DEMOCRATIC REPUBLIC */ + "LV", /**< LATVIA */ + "LB", /**< LEBANON */ + "LS", /**< LESOTHO */ + "LR", /**< LIBERIA */ + "LY", /**< LIBYAN ARAB JAMAHIRIYA */ + "LI", /**< LIECHTENSTEIN */ + "LT", /**< LITHUANIA */ + "LU", /**< LUXEMBOURG */ + "MO", /**< MACAO */ + "MK", /**< MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF */ + "MG", /**< MADAGASCAR */ + "MW", /**< MALAWI */ + "MY", /**< MALAYSIA */ + "MV", /**< MALDIVES */ + "ML", /**< MALI */ + "MT", /**< MALTA */ + "MH", /**< MARSHALL ISLANDS */ + "MQ", /**< MARTINIQUE */ + "MR", /**< MAURITANIA */ + "MU", /**< MAURITIUS */ + "YT", /**< MAYOTTE */ + "MX", /**< MEXICO */ + "FM", /**< MICRONESIA, FEDERATED STATES OF */ + "MD", /**< MOLDOVA, REPUBLIC OF */ + "MC", /**< MONACO */ + "MN", /**< MONGOLIA */ + "MS", /**< MONTSERRAT */ + "MA", /**< MOROCCO */ + "MZ", /**< MOZAMBIQUE */ + "MM", /**< MYANMAR */ + "NA", /**< NAMIBIA */ + "NR", /**< NAURU */ + "NP", /**< NEPAL */ + "NL", /**< NETHERLANDS */ + "AN", /**< NETHERLANDS ANTILLES */ + "NC", /**< NEW CALEDONIA */ + "NZ", /**< NEW ZEALAND */ + "NI", /**< NICARAGUA */ + "NE", /**< NIGER */ + "NG", /**< NIGERIA */ + "NU", /**< NIUE */ + "NF", /**< NORFOLK ISLAND */ + "MP", /**< NORTHERN MARIANA ISLANDS */ + "NO", /**< NORWAY */ + "OM", /**< OMAN */ + "PK", /**< PAKISTAN */ + "PW", /**< PALAU */ + "PS", /**< PALESTINIAN TERRITORY, OCCUPIED */ + "PA", /**< PANAMA */ + "PG", /**< PAPUA NEW GUINEA */ + "PY", /**< PARAGUAY */ + "PE", /**< PERU */ + "PH", /**< PHILIPPINES */ + "PN", /**< PITCAIRN */ + "PL", /**< POLAND */ + "PT", /**< PORTUGAL */ + "PR", /**< PUERTO RICO */ + "QA", /**< QATAR */ + "RE", /**< REUNION */ + "RO", /**< ROMANIA */ + "RU", /**< RUSSIAN FEDERATION */ + "RW", /**< RWANDA */ + "SH", /**< SAINT HELENA */ + "KN", /**< SAINT KITTS AND NEVIS */ + "LC", /**< SAINT LUCIA */ + "PM", /**< SAINT PIERRE AND MIQUELON */ + "VC", /**< SAINT VINCENT AND THE GRENADINES */ + "WS", /**< SAMOA */ + "SM", /**< SAN MARINO */ + "ST", /**< SAO TOME AND PRINCIPE */ + "SA", /**< SAUDI ARABIA */ + "SN", /**< SENEGAL */ + "SC", /**< SEYCHELLES */ + "SL", /**< SIERRA LEONE */ + "SG", /**< SINGAPORE */ + "SK", /**< SLOVAKIA */ + "SI", /**< SLOVENIA */ + "SB", /**< SOLOMON ISLANDS */ + "SO", /**< SOMALIA */ + "ZA", /**< SOUTH AFRICA */ + "GS", /**< SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS */ + "ES", /**< SPAIN */ + "LK", /**< SRI LANKA */ + "SD", /**< SUDAN */ + "SR", /**< SURINAME */ + "SJ", /**< SVALBARD AND JAN MAYEN */ + "SZ", /**< SWAZILAND */ + "SE", /**< SWEDEN */ + "CH", /**< SWITZERLAND */ + "SY", /**< SYRIAN ARAB REPUBLIC */ + "TW", /**< TAIWAN, PROVINCE OF CHINA */ + "TJ", /**< TAJIKISTAN */ + "TZ", /**< TANZANIA, UNITED REPUBLIC OF */ + "TH", /**< THAILAND */ + "TL", /**< TIMOR-LESTE */ + "TG", /**< TOGO */ + "TK", /**< TOKELAU */ + "TO", /**< TONGA */ + "TT", /**< TRINIDAD AND TOBAGO */ + "TN", /**< TUNISIA */ + "TR", /**< TURKEY */ + "TM", /**< TURKMENISTAN */ + "TC", /**< TURKS AND CAICOS ISLANDS */ + "TV", /**< TUVALU */ + "UG", /**< UGANDA */ + "UA", /**< UKRAINE */ + "AE", /**< UNITED ARAB EMIRATES */ + "GB", /**< UNITED KINGDOM */ + "US", /**< UNITED STATES */ + "UM", /**< UNITED STATES MINOR OUTLYING ISLANDS */ + "UY", /**< URUGUAY */ + "UZ", /**< UZBEKISTAN */ + "VU", /**< VANUATU */ + "VE", /**< VENEZUELA */ + "VN", /**< VIET NAM */ + "VG", /**< VIRGIN ISLANDS, BRITISH */ + "VI", /**< VIRGIN ISLANDS, U.S. */ + "WF", /**< WALLIS AND FUTUNA */ + "EH", /**< WESTERN SAHARA */ + "YE", /**< YEMEN */ + "ZM", /**< ZAMBIA */ + "ZW", /**< ZIMBABWE */ + "RS", /**< SERBIA */ + "ME" /**< MONTENEGRO */ +}; + + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Public Method + +Locale::Locale(const Locale& other) + : __languageCode(other.__languageCode) + , __countryCode(other.__countryCode) + , __pLocaleImpl(other.__pLocaleImpl->CloneN()) +{ + SysAssert(__pLocaleImpl); +} + + +Locale::Locale(LanguageCode languageCode, CountryCode countryCode, const String* pVariantCodeString) + : __languageCode((languageCode < LANGUAGE_MAX)? languageCode : LANGUAGE_INVALID) + , __countryCode((countryCode < COUNTRY_MAX) ? countryCode : COUNTRY_INVALID) + , __pLocaleImpl(null) +{ + const char* pLanguage = (languageCode != LANGUAGE_INVALID) ? LanguageCodeString3LetterArray[__languageCode] : null; + const char* pCountry = (countryCode != COUNTRY_INVALID) ? CountryCodeString2LetterArray[__countryCode] : null; + + std::unique_ptr pVariantCode (null); + if (pVariantCodeString) + { + pVariantCode.reset(_StringConverter::CopyToCharArrayN(*pVariantCodeString)); + } + + __pLocaleImpl = new (std::nothrow) _LocaleImpl(pLanguage, pCountry, pVariantCode.get()); + SysAssert(__pLocaleImpl); +} + + +Locale& +Locale::operator =(const Locale& other) +{ + if (&other != this) + { + __languageCode = other.__languageCode; + __countryCode = other.__countryCode; + + delete __pLocaleImpl; + __pLocaleImpl = other.__pLocaleImpl->CloneN(); + } + return *this; +} + + +Locale::~Locale(void) +{ + delete __pLocaleImpl; + __pLocaleImpl = null; +} + + +void +Locale::SetVariantCodeString(const String* pVariantCode) +{ + std::unique_ptr pVariant (null); + if (pVariantCode) + { + pVariant.reset(_StringConverter::CopyToCharArrayN(*pVariantCode)); + } + __pLocaleImpl->SetVariantCodeString(pVariant.get()); +} + + +// Access +LanguageCode +Locale::GetLanguageCode(void) const +{ + return __languageCode; +} + + +CountryCode +Locale::GetCountryCode(void) const +{ + return __countryCode; +} + + +String +Locale::GetLanguageCodeString(void) const +{ + return __pLocaleImpl->GetLanguageCodeString(false); +} + + +String +Locale::GetCountryCodeString(void) const +{ + return __pLocaleImpl->Get2LetterCountryCodeString(); +} + + +String +Locale::GetVariantCodeString(void) const +{ + return __pLocaleImpl->GetVariantCodeString(); +} + + +String +Locale::GetLocaleCodeString(void) const +{ + String lclCode(__pLocaleImpl->GetLanguageCodeString(false)); + if (!lclCode.IsEmpty()) + { + lclCode.Append(L"_"); + lclCode.Append(GetCountryCodeString()); + + String varCode(__pLocaleImpl->GetVariantCodeString()); + if (!varCode.IsEmpty()) + { + lclCode.Append(L"_"); + lclCode.Append(varCode); + } + } + return lclCode; +} + + +result +Locale::GetCountryName(String& countryName) const +{ + return __pLocaleImpl->GetCountryName(countryName); +} + + +result +Locale::GetCountryName(const Locale& otherLocale, String& countryName) const +{ + return __pLocaleImpl->GetCountryName(*otherLocale.__pLocaleImpl, countryName); +} + + +result +Locale::GetLanguageName(String& languageName) const +{ + return __pLocaleImpl->GetLanguageName(languageName); +} + + +result +Locale::GetLanguageName(const Locale& otherLocale, String& languageName) const +{ + return __pLocaleImpl->GetLanguageName(*otherLocale.__pLocaleImpl, languageName); +} + +bool +Locale::operator ==(const Locale& other) const +{ + bool isEqual = ((this->GetCountryCode() == other.GetCountryCode()) + && (this->GetLanguageCode() == other.GetLanguageCode()) + && (this->GetVariantCodeString() == other.GetVariantCodeString())); + return isEqual; +} + +bool +Locale::operator !=(const Locale& other) const +{ + return !(*this == other); +} + +bool +Locale::Equals(const Object& obj) const +{ + const Locale* pOtherLocale = dynamic_cast< const Locale* >(&obj); + if (pOtherLocale) + { + return *this == *pOtherLocale; + } + return false; +} + +int +Locale::GetHashCode(void) const +{ + return __pLocaleImpl->GetHashCode(); +} + + +LanguageCode +Locale::StringToLanguageCode(const String& languageCodeString) +{ + for (int i = 0; i < LANGUAGE_MAX; i++) + { + if (languageCodeString == LanguageCodeString3LetterArray[i]) + { + return (LanguageCode) i; + } + } + SysTryReturn(NID_LCL, false,LANGUAGE_INVALID, E_INVALID_ARG, "languageCodeStirng [%ls] is invalid", languageCodeString.GetPointer()); + return LANGUAGE_INVALID; +} + + +CountryCode +Locale::StringToCountryCode(const String& countryCodeString) +{ + for (int i = 0; i < COUNTRY_MAX; i++) + { + if (countryCodeString == CountryCodeString2LetterArray[i]) + { + return (CountryCode) i; + } + } + SysTryReturn (NID_LCL, false, COUNTRY_INVALID, E_INVALID_ARG , "countryCodeString [%ls] is invalid", countryCodeString.GetPointer()); + return COUNTRY_INVALID; +} + + +String +Locale::LanguageCodeToString(LanguageCode languageCode) +{ + return (languageCode < LANGUAGE_MAX) + ? LanguageCodeString3LetterArray[languageCode] + : String(); +} + + +String +Locale::CountryCodeToString(CountryCode countryCode) +{ + return (countryCode < COUNTRY_MAX) + ? CountryCodeString2LetterArray[countryCode] + : String(); +} + + +String +Locale::LanguageCodeToTwoLetterLanguageCodeString(LanguageCode languageCode) +{ + return (languageCode < LANGUAGE_MAX) + ? _LocaleImpl::Get2LetterLanguageCodeString(LanguageCodeString3LetterArray[languageCode]) + : String(); +} + + +LanguageCode +Locale::TwoLetterLanguageCodeStringToLanguageCode(const String& languageCodeString) +{ + int index = -1; + + languageCodeString.IndexOf(L"-", 0, index); + + if (languageCodeString.GetLength() == 2 || index == 2) + { + std::unique_ptr pLangStr (_StringConverter::CopyToCharArrayN(languageCodeString)); + return StringToLanguageCode(_LocaleImpl::Get3LetterLanguageCodeString(pLangStr.get())); + } + return LANGUAGE_INVALID; +} + + +String +Locale::CountryCodeToThreeLetterCountryCodeString(CountryCode countryCode) +{ + return (countryCode < COUNTRY_MAX) + ? _LocaleImpl::Get3LetterCountryCodeString(CountryCodeString2LetterArray[countryCode]) + : String(); +} + + +CountryCode +Locale::ThreeLetterCountryCodeStringToCountryCode(const String& countryCodeString) +{ + if (countryCodeString.GetLength() == 3) + { + for (int i = 0; i < COUNTRY_MAX; i++) + { + String countryCode(_LocaleImpl::Get3LetterCountryCodeString(CountryCodeString2LetterArray[i])); + if (countryCodeString.Equals(countryCode, false)) + { + return static_cast (i); + } + } + } + + return COUNTRY_INVALID; +} + + +}; +}; // Tizen::Locales diff --git a/src/locales/FLclLocaleManager.cpp b/src/locales/FLclLocaleManager.cpp new file mode 100644 index 0000000..8983096 --- /dev/null +++ b/src/locales/FLclLocaleManager.cpp @@ -0,0 +1,126 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclLocaleManager.cpp + * @brief This is the implementation file for LocaleManager class. + */ + +// Includes +#include +#include +#include +#include "FLcl_LocaleManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +namespace Tizen { namespace Locales +{ + +LocaleManager::LocaleManager(void) + : __pLocaleManagerImpl(null) +{ +} + + +LocaleManager::~LocaleManager(void) +{ +} + + +result +LocaleManager::Construct(void) +{ + return E_SUCCESS; +} + + +Locale +LocaleManager::GetSystemLocale(void) const +{ + ClearLastResult(); + return _LocaleManagerImpl::GetSystemLocale(); +} + + +IList* +LocaleManager::GetAvailableLocalesN(void) const +{ + ClearLastResult(); + return _LocaleManagerImpl::GetAvailableLocalesN(); +} + + +String +LocaleManager::GetSelectedLanguage(void) const +{ + ClearLastResult(); + return _LocaleManagerImpl::GetSelectedLanguage(); +} + + +IList* +LocaleManager::GetAvailableLanguagesN(void) const +{ + ClearLastResult(); + + return _LocaleManagerImpl::GetAvailableLanguagesN(); +} + + +IList* +LocaleManager::GetAvailableTimeZonesN(void) const +{ + ClearLastResult(); + IMap* pTimeZoneMap = _LocaleManagerImpl::GetAvailableTimeZonesN(); + IList* pTimeZoneList = pTimeZoneMap->GetKeysN(); + pTimeZoneMap->RemoveAll(); + delete pTimeZoneMap; + return pTimeZoneList; +} + + +IList* +LocaleManager::GetAvailableTimeZonesN(int rawOffset) const +{ + ClearLastResult(); + IMap* pTimeZoneMap =_LocaleManagerImpl::GetAvailableTimeZonesN(rawOffset); + IList* pTimeZoneList = pTimeZoneMap->GetKeysN(); + pTimeZoneMap->RemoveAll(); + delete pTimeZoneMap; + return pTimeZoneList; +} + +TimeZone +LocaleManager::GetSystemTimeZone(void) const +{ + ClearLastResult(); + return _LocaleManagerImpl::GetSystemTimeZone(); +} + +result +LocaleManager::IsSupportedLocale(const Locale& locale, bool& isSupportedLocale) +{ + ClearLastResult(); + return _LocaleManagerImpl::IsSupportedLocale(locale, isSupportedLocale); +} + + +}; +}; // Tizen::Locales diff --git a/src/locales/FLclNumberFormatter.cpp b/src/locales/FLclNumberFormatter.cpp new file mode 100644 index 0000000..911b04b --- /dev/null +++ b/src/locales/FLclNumberFormatter.cpp @@ -0,0 +1,330 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclNumberFormatter.cpp + * @brief This is the implementation file for NumberFormatter class. + */ + +// Includes +#include +#include +#include "FLcl_NumberFormatterImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Locales +{ + +NumberFormatter* +NumberFormatter::CreateNumberFormatterN(void) +{ + NumberFormatter* pNumberFormatter = _NumberFormatterImpl::CreateNumberFormatterN(NUM_FORMATTER_STYLE_NUMBER); + if (GetLastResult() == E_INVALID_ARG) + { + SetLastResult( E_UNSUPPORTED_OPERATION ); + return null; + } + return pNumberFormatter; +} + + +NumberFormatter* +NumberFormatter::CreateNumberFormatterN(const Locale& locale) +{ + return _NumberFormatterImpl::CreateNumberFormatterN(locale, NUM_FORMATTER_STYLE_NUMBER); +} + + +NumberFormatter* +NumberFormatter::CreateCurrencyFormatterN(void) +{ + NumberFormatter* pNumberFormatter = _NumberFormatterImpl::CreateNumberFormatterN(NUM_FORMATTER_STYLE_CURRENCY); + if (GetLastResult() == E_INVALID_ARG) + { + SetLastResult( E_UNSUPPORTED_OPERATION ); + return null; + } + return pNumberFormatter; +} + + +NumberFormatter* +NumberFormatter::CreateCurrencyFormatterN(const Locale& locale) +{ + return _NumberFormatterImpl::CreateNumberFormatterN(locale, NUM_FORMATTER_STYLE_CURRENCY); +} + + +NumberFormatter* +NumberFormatter::CreatePercentFormatterN(void) +{ + NumberFormatter* pNumberFormatter = _NumberFormatterImpl::CreateNumberFormatterN(NUM_FORMATTER_STYLE_PERCENT); + if (GetLastResult() == E_INVALID_ARG) + { + SetLastResult( E_UNSUPPORTED_OPERATION ); + return null; + } + return pNumberFormatter; +} + + +NumberFormatter* +NumberFormatter::CreatePercentFormatterN(const Locale& locale) +{ + return _NumberFormatterImpl::CreateNumberFormatterN(locale, NUM_FORMATTER_STYLE_PERCENT); +} + +NumberFormatter::~NumberFormatter(void) +{ + delete __pNumberFormatterImpl; +} + +const Currency* +NumberFormatter::GetCurrency(void) const +{ + return __pNumberFormatterImpl->GetCurrency(); +} + + +void +NumberFormatter::SetCurrency(const Currency& currency) +{ + __pNumberFormatterImpl->SetCurrency(currency); +} + + +int +NumberFormatter::GetMaxIntegerDigits(void) const +{ + return __pNumberFormatterImpl->GetMaxIntegerDigits(); +} + + +void +NumberFormatter::SetMaxIntegerDigits(int newValue) +{ + __pNumberFormatterImpl->SetMaxIntegerDigits(newValue); +} + + +int +NumberFormatter::GetMinIntegerDigits(void) const +{ + return __pNumberFormatterImpl->GetMinIntegerDigits(); +} + + +void +NumberFormatter::SetMinIntegerDigits(int newValue) +{ + __pNumberFormatterImpl->SetMinIntegerDigits(newValue); +} + + +int +NumberFormatter::GetMaxFractionDigits(void) const +{ + return __pNumberFormatterImpl->GetMaxFractionDigits(); +} + + +void +NumberFormatter::SetMaxFractionDigits(int newValue) +{ + __pNumberFormatterImpl->SetMaxFractionDigits(newValue); +} + + +int +NumberFormatter::GetMinFractionDigits(void) const +{ + return __pNumberFormatterImpl->GetMinFractionDigits(); +} + + +void +NumberFormatter::SetMinFractionDigits(int newValue) +{ + __pNumberFormatterImpl->SetMinFractionDigits(newValue); +} + + +bool +NumberFormatter::IsGroupingUsed(void) const +{ + return __pNumberFormatterImpl->IsGroupingUsed(); +} + + +void +NumberFormatter::SetGroupingUsed(bool newValue) +{ + __pNumberFormatterImpl->SetGroupingUsed(newValue); +} + +NumberFormatter::NumberFormatter(void) + : __pNumberFormatterImpl(null) +{ +} + +result +NumberFormatter::ApplyPattern(const Tizen::Base::String& pattern, bool localized) +{ + SysTryReturnResult(NID_LCL, pattern.GetLength() > 0, E_INVALID_ARG, "Invalid argument is used. Length of the pattern is 0"); + return __pNumberFormatterImpl->ApplyPattern(pattern, localized); // Try to set pattern to ICU number formatter +} + + +result +NumberFormatter::Format(long number, Tizen::Base::String& strBuf) const +{ + return __pNumberFormatterImpl->Format(number, strBuf); +} + + +result +NumberFormatter::Format(double number, Tizen::Base::String& strBuf) const +{ + return __pNumberFormatterImpl->Format(number, strBuf); +} + + +String +NumberFormatter::GetPositivePrefix(void) const +{ + return __pNumberFormatterImpl->GetPositivePrefix(); +} + + +void +NumberFormatter::SetPositivePrefix(const Tizen::Base::String& newValue) +{ + __pNumberFormatterImpl->SetPositivePrefix(newValue); +} + + +String +NumberFormatter::GetNegativePrefix(void) const +{ + return __pNumberFormatterImpl->GetNegativePrefix(); +} + + +void +NumberFormatter::SetNegativePrefix(const Tizen::Base::String& newValue) +{ + __pNumberFormatterImpl->SetNegativePrefix(newValue); +} + + +String +NumberFormatter::GetPositiveSuffix(void) const +{ + return __pNumberFormatterImpl->GetPositiveSuffix(); +} + + +void +NumberFormatter::SetPositiveSuffix(const Tizen::Base::String& newValue) +{ + __pNumberFormatterImpl->SetPositiveSuffix(newValue); +} + + +String +NumberFormatter::GetNegativeSuffix(void) const +{ + return __pNumberFormatterImpl->GetNegativeSuffix(); +} + + +void +NumberFormatter::SetNegativeSuffix(const Tizen::Base::String& newValue) +{ + __pNumberFormatterImpl->SetNegativeSuffix(newValue); +} + + +int +NumberFormatter::GetMultiplier(void) const +{ + return __pNumberFormatterImpl->GetMultiplier(); +} + + +result +NumberFormatter::SetMultiplier(int newValue) +{ + SysTryReturnResult(NID_LCL, 0 < newValue, E_INVALID_ARG, + "Invalid argument is used. newvalue(%d) is not a positive value.", newValue); + + __pNumberFormatterImpl->SetMultiplier(newValue); + return E_SUCCESS; +} + + +int +NumberFormatter::GetGroupingSize(void) const +{ + return __pNumberFormatterImpl->GetGroupingSize(); +} + + +result +NumberFormatter::SetGroupingSize(int newValue) +{ + SysTryReturnResult(NID_LCL, 0 < newValue, E_INVALID_ARG, + "Invalid argument is used. newvalue(%d) is not a positive value.", newValue); + + __pNumberFormatterImpl->SetGroupingSize(newValue); + return E_SUCCESS; +} + + +bool +NumberFormatter::IsDecimalSeparatorAlwaysShown(void) const +{ + return __pNumberFormatterImpl->IsDecimalSeparatorAlwaysShown(); +} + + +void +NumberFormatter::SetDecimalSeparatorAlwaysShown(bool newValue) +{ + __pNumberFormatterImpl->SetDecimalSeparatorAlwaysShown(newValue); +} + + +bool +NumberFormatter::IsPositiveSignAlwaysShown(void) const +{ + return __pNumberFormatterImpl->IsPositiveSignAlwaysShown(); +} + + +void +NumberFormatter::SetPositiveSignAlwaysShown(bool newValue) +{ + __pNumberFormatterImpl->SetPositiveSignAlwaysShown(newValue); +} + + +}; +}; // Tizen::Locales + diff --git a/src/locales/FLclNumberSymbols.cpp b/src/locales/FLclNumberSymbols.cpp new file mode 100644 index 0000000..dca4052 --- /dev/null +++ b/src/locales/FLclNumberSymbols.cpp @@ -0,0 +1,110 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclNumberSymbols.cpp + * @brief This is the implementation file for NumberSymbols class. + */ + +// Includes +#include +#include +#include +#include +#include +#include "FLcl_NumberSymbolsImpl.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Public Method + +NumberSymbols::NumberSymbols(void) + : __pNumberSymbolsImpl(null) +{ +} + +NumberSymbols::~NumberSymbols(void) +{ + delete __pNumberSymbolsImpl; + __pNumberSymbolsImpl = null; +} + +result +NumberSymbols::Construct(const Locale& locale) +{ + // Object is not allowed to construct twice + SysAssertf(__pNumberSymbolsImpl == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + result r = E_INVALID_ARG; + + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_UNSUPPORTED_OPERATION; + } + // validating locale + TryReturn(locale.GetCountryCode() != COUNTRY_INVALID, r, + "[%s] Country code is invalid. Given locale is not supported", GetErrorMessage(r)); + TryReturn(locale.GetLanguageCode() != LANGUAGE_INVALID, r, + "[%s] Language code is invalid. Given locale is not supported", GetErrorMessage(r)); + + __pNumberSymbolsImpl = new (std::nothrow) _NumberSymbolsImpl; + SysTryReturnResult(NID_LCL, __pNumberSymbolsImpl != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + r = __pNumberSymbolsImpl->Construct(locale); + if (IsFailed(r)) + { + delete __pNumberSymbolsImpl; + __pNumberSymbolsImpl = null; + } + return r; +} + + +String +NumberSymbols::GetNumberSymbol(NumberSymbol symbol) const +{ + SysAssertf(__pNumberSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pNumberSymbolsImpl->GetNumberSymbol(symbol); +} + + +result +NumberSymbols::SetNumberSymbol(const NumberSymbol symbol, const String& str) +{ + SysAssertf(__pNumberSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pNumberSymbolsImpl->SetNumberSymbol(symbol, str); +} + + +const Locale* +NumberSymbols::GetLocale(void) const +{ + SysAssertf(__pNumberSymbolsImpl != null, "Not yet constructed! Construct() should be called before use."); + return __pNumberSymbolsImpl->GetLocale(); +} + + +}; +}; // Tizen::Locales + diff --git a/src/locales/FLclTimeRule.cpp b/src/locales/FLclTimeRule.cpp new file mode 100644 index 0000000..56d0207 --- /dev/null +++ b/src/locales/FLclTimeRule.cpp @@ -0,0 +1,232 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclTimeRule.cpp + * @brief This file contains implementation of TimeRule class + */ + +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Locales; +using namespace Tizen::System; + +namespace Tizen { namespace Locales +{ + +/** + * @enum DstRuleMode + * Possible DST rule mode + */ +enum DstRuleMode +{ + EXACT_DAY = 0, + DAY_OF_WEEK_IN_MONTH, + AFTER_THE_SPECIFIED_DAY, + BEFORE_THE_SPECIFIED_DAY, + BACKWARD_FROM_END_OF_MONTH +}; + +TimeRule::TimeRule(const TimeRule& timeRule) + : __pTimeRuleImpl(null) +{ + __month = timeRule.__month; + __day = timeRule.__day; + __week = timeRule.__week; + __dayOfWeek = timeRule.__dayOfWeek; + __hour = timeRule.__hour; + __minute = timeRule.__minute; + __timeMode = timeRule.__timeMode; + __onOrAfterDay = timeRule.__onOrAfterDay; +} + + +TimeRule::~TimeRule(void) +{ +} + + +// Exact day +TimeRule::TimeRule(Month month, int day, int hour, int minute, TimeMode timeMode) + : __pTimeRuleImpl(null) +{ + SetValue(month, day, WEEK_UNDEFINED, DAY_OF_WEEK_UNDEFINED, true, hour, minute, timeMode); +} + + +// The day of week of x-th week of month / The Last day of week of month +TimeRule::TimeRule(Month month, Week week, DayOfWeek dayOfWeek, int hour, int minute, TimeMode timeMode) + : __pTimeRuleImpl(null) +{ + SetValue(month, DAY_UNDEFINED, week, dayOfWeek, true, hour, minute, timeMode); +} + + +// Day of week on or before/after day of month +TimeRule::TimeRule(Month month, int day, DayOfWeek dayOfWeek, bool onOrAfterDay, int hour, int minute, TimeMode timeMode) + : __pTimeRuleImpl(null) +{ + SetValue(month, day, WEEK_UNDEFINED, dayOfWeek, onOrAfterDay, hour, minute, timeMode); +} + + +// Internal construction method +void +TimeRule::SetValue(Month month, int day, Week week, DayOfWeek dayOfWeek, bool onOrAfterDay, int hour, int minute, + TimeMode timeMode) +{ + __month = month; + __day = day; + __week = week; + __dayOfWeek = dayOfWeek; + __hour = hour; + __minute = minute; + __timeMode = timeMode; + __onOrAfterDay = onOrAfterDay; +} + + +Month +TimeRule::GetMonth(void) const +{ + return __month; +} + + +int +TimeRule::GetDay(void) const +{ + return __day; +} + + +Week +TimeRule::GetWeek(void) const +{ + return __week; +} + + +DayOfWeek +TimeRule::GetDayOfWeek(void) const +{ + return __dayOfWeek; +} + + +int +TimeRule::GetHour(void) const +{ + return __hour; +} + +int +TimeRule::GetMinute(void) const +{ + return __minute; +} + + +TimeMode +TimeRule::GetTimeMode(void) const +{ + return __timeMode; +} + + +bool +TimeRule::IsOnOrAfterDay(void) const +{ + return __onOrAfterDay; +} + +TimeRule& +TimeRule::operator =(const TimeRule& timeRule) +{ + if (&timeRule != this) + { + __month = timeRule.__month; + __day = timeRule.__day; + __week = timeRule.__week; + __dayOfWeek = timeRule.__dayOfWeek; + __hour = timeRule.__hour; + __minute = timeRule.__minute; + __timeMode = timeRule.__timeMode; + __onOrAfterDay = timeRule.__onOrAfterDay; + } + return *this; +} + +int +TimeRule::GetRuleMode(void) const +{ + DstRuleMode ruleMode; + + if (DAY_UNDEFINED != __day) + { + if (__dayOfWeek == DAY_OF_WEEK_UNDEFINED) + { + ruleMode = EXACT_DAY; + } + else + { + ruleMode = __onOrAfterDay ? AFTER_THE_SPECIFIED_DAY : BEFORE_THE_SPECIFIED_DAY; + } + } + else + { + ruleMode = DAY_OF_WEEK_IN_MONTH; + } + + return static_cast< int >(ruleMode); +} + +bool +TimeRule::Equals(const Object& obj) const +{ + const TimeRule* pOtherTimeRule = dynamic_cast< const TimeRule* >(&obj); + if (pOtherTimeRule) + { + if (__month == pOtherTimeRule->__month + && __day == pOtherTimeRule->__day + && __week == pOtherTimeRule->__week + && __dayOfWeek == pOtherTimeRule->__dayOfWeek + && __hour == pOtherTimeRule->__hour + && __minute == pOtherTimeRule->__minute + && __timeMode == pOtherTimeRule->__timeMode + && __onOrAfterDay == pOtherTimeRule->__onOrAfterDay + ) + { + return true; + } + + } + return false; +} + +int +TimeRule::GetHashCode(void) const +{ + Integer value = __month + __day + __week + __dayOfWeek + __hour + __minute + __timeMode + __onOrAfterDay; + return value.GetHashCode(); +} + + +}} // Tizen::Locales diff --git a/src/locales/FLclTimeZone.cpp b/src/locales/FLclTimeZone.cpp new file mode 100644 index 0000000..0d5e628 --- /dev/null +++ b/src/locales/FLclTimeZone.cpp @@ -0,0 +1,405 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclTimeZone.cpp + * @brief This is the implementation file for TimeZone class. + */ + +// Includes + +#include +#include +#include +#include + +#include "FLcl_TimeZoneImpl.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +enum GregorianCalendarEras +{ + GREGORIAN_CALENDAR_BC = 0, // BC + GREGORIAN_CALENDAR_AD = 1, // AD +}; + +TimeZone::TimeZone(void) + : __pTimeZoneImpl(null) +{ + __pTimeZoneImpl = new (std::nothrow) _TimeZoneImpl; + SysAssert(__pTimeZoneImpl); +} + + +TimeZone::~TimeZone(void) +{ + delete __pTimeZoneImpl; +} + + +TimeZone::TimeZone(const TimeZone& tz) + : __pTimeZoneImpl(null) +{ + __pTimeZoneImpl = new (std::nothrow) _TimeZoneImpl(*tz.__pTimeZoneImpl); + SysAssert(__pTimeZoneImpl); +} + + +// This method constructs an instance of TimeZone with the given raw GMT offset +// and the name of time zone with no pDst. +TimeZone::TimeZone(int rawOffset, const String& id) + : __pTimeZoneImpl(null) +{ + __pTimeZoneImpl = new (std::nothrow) _TimeZoneImpl(rawOffset, id); + SysAssert(__pTimeZoneImpl); +} + + +// This method constructs an instance of TimeZone with the name, offset, and given pDst rules. +TimeZone::TimeZone(int rawOffset, const String& id, const TimeRule& startingRule, const TimeRule& endingRule, int dstOffset) + : __pTimeZoneImpl(null) +{ + __pTimeZoneImpl = new (std::nothrow) _TimeZoneImpl(rawOffset, id, startingRule, endingRule, dstOffset); + SysAssert(__pTimeZoneImpl); +} + + +// This method compares the equality of obj and the current instance. +bool +TimeZone::operator ==(const TimeZone& timeZone) const +{ + return *__pTimeZoneImpl == *timeZone.__pTimeZoneImpl; +} + +bool +TimeZone::Equals(const Object& obj) const +{ + ClearLastResult(); + const TimeZone* pOtherTimeZone = dynamic_cast< const TimeZone* >(&obj); + if (pOtherTimeZone != null) + { + return *this == *pOtherTimeZone; + } + return false; +} + +int +TimeZone::GetHashCode(void) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetHashCode(); +} + + +// This method gets the amount of time to be added to local standard time to get local wall clock time. +int +TimeZone::GetDstSavings(void) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetDstSavings(); // method return value in minutes +} + + +int +TimeZone::GetDstStartingYear(void) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetDstStartingYear(); +} + + +// This method gets the difference in minutes between local time and GMT, +// taking into consideration both the raw offset and the effect of dst offset. +result +TimeZone::GetOffset(const DateTime& date, bool local, int& rawOffset, int& dstOffset) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetOffset(date, local, rawOffset, dstOffset); +} + + +// This method gets the difference in minutes between local time and GMT, +// taking into consideration both the raw offset and the effect of pDst. +result +TimeZone::GetOffset(long long ticks, int& offset) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetOffset(ticks, offset); +} + + +// This method gets the difference in milliseconds between local time and GMT, not including pDst.(i.e. Raw offset) +int +TimeZone::GetRawOffset(void) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetRawOffset(); // method return value in minutes +} + + +// This method gets the id of time zone. +String +TimeZone::GetId(void) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetId(); +} + + +const TimeRule* +TimeZone::GetDstStartingRule(void) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetDstStartingRule(); +} + + +const TimeRule* +TimeZone::GetDstEndingRule(void) const +{ + ClearLastResult(); + return __pTimeZoneImpl->GetDstEndingRule(); +} + + +// This method checks that the current instance uses pDst. +bool +TimeZone::IsDstUsed(void) const +{ + ClearLastResult(); + return __pTimeZoneImpl->IsDstUsed(); +} + + +// This method sets the amount of time in minute that the clock is advanced during pDst. +void +TimeZone::SetDstSavings(int dstSavings) +{ + ClearLastResult(); + __pTimeZoneImpl->SetDstSavings(dstSavings); +} + + +// This method sets the pDst starting/end rule. +result +TimeZone::SetDstRules(const TimeRule& startingRule, const TimeRule& endingRule, int dstSavings) +{ + ClearLastResult(); + return __pTimeZoneImpl->SetDstRules(startingRule, endingRule, dstSavings); +} + + +// This method sets the pDst end rule +void +TimeZone::SetDstEndingRule(const TimeRule& endingRule) +{ + ClearLastResult(); + __pTimeZoneImpl->SetDstEndingRule(endingRule); +} + + +// This method sets the pDst starting rule +void +TimeZone::SetDstStartingRule(const TimeRule& startingRule) +{ + ClearLastResult(); + __pTimeZoneImpl->SetDstStartingRule(startingRule); +} + + +// This method sets the difference in minutes between local time and GMT, not including pDst.(i.e. Raw offset) +void +TimeZone::SetRawOffset(int rawOffset) +{ + ClearLastResult(); + __pTimeZoneImpl->SetRawOffset(rawOffset); // rawOffset is in minutes +} + + +// This method sets the pDst starting year. +void +TimeZone::SetDstStartingYear(int year) +{ + ClearLastResult(); + __pTimeZoneImpl->SetDstStartingYear(year); +} + + +// This method sets the id of time zone. +void +TimeZone::SetId(const String& id) +{ + ClearLastResult(); + __pTimeZoneImpl->SetId(id); +} + + +// This operator assigns the specified @c TimeZone instance to the current instance. +TimeZone& +TimeZone::operator =(const TimeZone& otherTimeZone) +{ + ClearLastResult(); + if (otherTimeZone != *this) + { + delete __pTimeZoneImpl; + __pTimeZoneImpl = otherTimeZone.__pTimeZoneImpl->CloneN(); + } + return *this; +} + + +// This inequality operator returns @c true if the specified @c TimeZone instance is not equals to the +// current instance. Otherwise, the operator returns @c false. +bool +TimeZone::operator !=(const TimeZone& otherTimeZone) const +{ + ClearLastResult(); + return !operator ==(otherTimeZone); +} + + +// This method converts the UTC time to the standard time. +Tizen::Base::DateTime +TimeZone::UtcTimeToStandardTime(const Tizen::Base::DateTime& utcTime) +{ + ClearLastResult(); + DateTime standardTime = utcTime; + standardTime.AddMinutes(__pTimeZoneImpl->GetRawOffset()); + return standardTime; +} + + +// This method converts the UTC time to the wall time. +Tizen::Base::DateTime +TimeZone::UtcTimeToWallTime(const Tizen::Base::DateTime& utcTime) +{ + ClearLastResult(); + DateTime wallTime = utcTime; + int rawOffset = 0; + int dstOffset = 0; + + result r = __pTimeZoneImpl->GetOffset(utcTime, false, rawOffset, dstOffset); + if (!IsFailed(r)) + { + wallTime.AddMinutes(rawOffset + dstOffset); + } + return wallTime; +} + + +// This method converts the standard time to the UTC time. +Tizen::Base::DateTime +TimeZone::StandardTimeToUtcTime(const Tizen::Base::DateTime& standardTime) +{ + ClearLastResult(); + DateTime utcTime = standardTime; + utcTime.AddMinutes(-GetRawOffset()); + return utcTime; +} + + +// This method converts the wall time to the UTC time. +Tizen::Base::DateTime +TimeZone::WallTimeToUtcTime(const Tizen::Base::DateTime& wallTime) +{ + ClearLastResult(); + DateTime utcTime = wallTime; + int rawOffset = 0; + int dstOffset = 0; + + result r = GetOffset(wallTime, true, rawOffset, dstOffset); + SysAssert(r == E_SUCCESS); + + utcTime.AddMinutes(-(rawOffset + dstOffset)); + return utcTime; +} + + +// This method gets the GMT. +// The GMT time zone has a raw offset of zero and does not use daylight savings time. +TimeZone +TimeZone::GetGmtTimeZone(void) +{ + ClearLastResult(); + return TimeZone(0, L"Europe/London"); +} + +result +TimeZone::GetTimeZone(const Tizen::Base::String& id, Tizen::Locales::TimeZone& timeZone) +{ + ClearLastResult(); + return _TimeZoneImpl::GetTimeZone(id, timeZone); +} + +result +TimeZone::GetTimeZone(const Tizen::Base::String& id, const Tizen::Base::DateTime& utcTime, Tizen::Locales::TimeZone& timeZone) +{ + ClearLastResult(); + return _TimeZoneImpl::GetTimeZone(id, utcTime, timeZone); +} + + +DateTime +TimeZone::UtcTimeToStandardTime(const DateTime& utcTime, int rawOffset) +{ + ClearLastResult(); + DateTime dt = utcTime; + dt.AddMinutes(rawOffset); + + return dt; +} + + +DateTime +TimeZone::StandardTimeToUtcTime(const DateTime& standardTime, int rawOffset) +{ + ClearLastResult(); + DateTime dt = standardTime; + dt.AddMinutes(rawOffset); + + return dt; +} + + +DateTime +TimeZone::UtcTimeToWallTime(const DateTime& utcTime, int rawOffset, int dstOffset) +{ + ClearLastResult(); + DateTime dt = utcTime; + dt.AddMinutes(rawOffset + dstOffset); + + return dt; +} + + +DateTime +TimeZone::WallTimeToUtcTime(const DateTime& wallTime, int rawOffset, int dstOffset) +{ + ClearLastResult(); + DateTime dt = wallTime; + dt.AddMinutes(rawOffset + dstOffset); + + return dt; +} + + +}; +}; // Tizen::Locales diff --git a/src/locales/FLcl_CalendarImpl.cpp b/src/locales/FLcl_CalendarImpl.cpp new file mode 100644 index 0000000..08f0bf3 --- /dev/null +++ b/src/locales/FLcl_CalendarImpl.cpp @@ -0,0 +1,653 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_CalendarImpl.cpp + * @brief This is the implementation file for _CalendarImpl class. + */ + +#include +#include + +#include +#include +#include +#include + +#include "FLcl_CalendarImpl.h" +#include "FLcl_IcuCalendarImpl.h" +#include "FLcl_LocaleData.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +static const int ONE_MINUTE_IN_MILLISEC = 60000; + +_CalendarImpl::_CalendarImpl() + : __type(CALENDAR_GREGORIAN) + , __locale(LANGUAGE_INVALID, COUNTRY_INVALID) + , __timezone() + , __pCalendar(null) +{ +} + +_CalendarImpl::~_CalendarImpl() +{ + delete __pCalendar; + __pCalendar = null; +} + + +Calendar* +_CalendarImpl::CreateCalendarInstanceN(CalendarType calendarType) +{ + return CreateInstanceN(TimeZone::GetGmtTimeZone(), calendarType); +} + +Calendar* +_CalendarImpl::CreateCalendarInstanceN(const TimeZone& timeZone, CalendarType calendarType) +{ + return CreateInstanceN(timeZone, _LocaleData::GetOspSystemLocale(), calendarType); +} + +Calendar* +_CalendarImpl::CreateCalendarInstanceN(const Locale& locale, CalendarType calendarType) +{ + // Create calendar using system time zone and given locale and calendar type + return CreateInstanceN(TimeZone::GetGmtTimeZone(), locale, calendarType); +} + +Calendar* +_CalendarImpl::CreateCalendarInstanceN(const TimeZone& timeZone, const Locale& locale, CalendarType calendarType) +{ + ClearLastResult(); + result r = E_SYSTEM; + switch (calendarType) + { + case CALENDAR_GREGORIAN: + { + std::unique_ptr< GregorianCalendar > pGregCalendar(new (std::nothrow) GregorianCalendar); + SysTryReturn(NID_LCL, pGregCalendar != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pGregCalendar->Construct(timeZone, locale); + SysTryReturn(NID_LCL, !IsFailed(r), null, r, "[%s] Unable to construct calendar", GetErrorMessage(r)); + + return pGregCalendar.release(); + } + + default: + break; + } + + std::unique_ptr< _CalendarImpl > pCalendar(new (std::nothrow) _CalendarImpl); + SysTryReturn(NID_LCL, pCalendar != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pCalendar->Construct(timeZone, locale, calendarType); + SetLastResult(r); + SysTryReturn(NID_LCL, !IsFailed(r), null, r, "[%s] Unable to construct calendar", GetErrorMessage(r)); + return pCalendar.release(); +} + +Calendar* +_CalendarImpl::CloneN(void) const +{ + std::unique_ptr< _CalendarImpl > pCalendar(new (std::nothrow) _CalendarImpl()); + SysTryReturn(NID_LCL, pCalendar != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + if (__pCalendar != null) + { + pCalendar->__pCalendar = __pCalendar->CloneN(); + if (pCalendar->__pCalendar != null) + { + pCalendar->__type = __type; + pCalendar->__locale = __locale; + pCalendar->__timezone = __timezone; + + pCalendar->_pCalendarImpl = pCalendar.get(); + } + } + + return pCalendar.release(); +} + +result +_CalendarImpl::Construct(CalendarType calendarType) +{ + Locale defaultLocale = _LocaleData::GetOspSystemLocale(); + return Construct( TimeZone::GetGmtTimeZone(), defaultLocale, calendarType); +} + +result +_CalendarImpl::Construct(const TimeZone& timezone, CalendarType calendarType) +{ + Locale defaultLocale = _LocaleData::GetOspSystemLocale(); + return Construct(timezone, defaultLocale, calendarType); +} + +result +_CalendarImpl::Construct(const Locale& locale, CalendarType calendarType) +{ + TimeZone defaultTimeZone = TimeZone::GetGmtTimeZone(); + return Construct(defaultTimeZone, locale, calendarType); +} + +result +_CalendarImpl::Construct(const TimeZone& timeZone, const Locale& locale, CalendarType calendarType) +{ + // Object is not allowed to construct twice + SysAssertf(__pCalendar == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + SysTryReturnResult(NID_LCL, locale.GetLanguageCode() != LANGUAGE_INVALID, + E_INVALID_ARG, "Invalid argument is used. Language code is invalid. Given locale is not supported"); + + SysTryReturnResult(NID_LCL, locale.GetCountryCode() != COUNTRY_INVALID, + E_INVALID_ARG, "Invalid argument is used. Country code is invalid. Given locale is not supported"); + + std::unique_ptr< _IcuCalendarImpl > pCalendar(new (std::nothrow) _IcuCalendarImpl); + SysTryReturnResult(NID_LCL, pCalendar != null, E_OUT_OF_MEMORY, "Memory allocation failed"); + + result r = pCalendar->Construct(timeZone, locale, calendarType); + if (!IsFailed(r)) + { + __pCalendar = pCalendar.release(); + __type = calendarType; + __locale = locale; + __timezone = timeZone; + + _pCalendarImpl = this; + return E_SUCCESS; + } + + return E_SYSTEM; +} + +result +_CalendarImpl::Construct(const Calendar& otherCalendar) +{ + // Object is not allowed to construct twice + SysAssertf(__pCalendar == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + result r = E_SYSTEM; + const _CalendarImpl* pOtherCalendar = dynamic_cast< const _CalendarImpl* >(&otherCalendar); + if ((pOtherCalendar != null) && (pOtherCalendar->__pCalendar != null)) + { + delete __pCalendar; + + __pCalendar = pOtherCalendar->__pCalendar->CloneN(); + if (__pCalendar != null) + { + __type = pOtherCalendar->__type; + __locale = pOtherCalendar->__locale; + __timezone = pOtherCalendar->__timezone; + + _pCalendarImpl = pOtherCalendar->_pCalendarImpl; + return E_SUCCESS; + } + r = GetLastResult(); + } + return r; +} + +result +_CalendarImpl::SetTimeFieldImpl(TimeField field, int value) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_LCL, ValidateTimeField(field), + E_INVALID_ARG, "Invalid argument is used. Timefield is less than 0 or grater than time field count."); + SysTryReturnResult(NID_LCL, ValidateTimeFieldValue(field, value), E_OUT_OF_RANGE, "value(%d) is out of range.", value); + + return __pCalendar->SetTimeField(field, value); +} + +result +_CalendarImpl::SetTimeInMillisecImpl(long long millisec) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->SetTimeInMillisec(millisec - __timezone.GetRawOffset() * ONE_MINUTE_IN_MILLISEC); +} + +result +_CalendarImpl::SetTimeImpl(const DateTime& dateTime) +{ + return SetTimeImpl(dateTime.GetYear(), dateTime.GetMonth(), dateTime.GetDay(), dateTime.GetHour(), dateTime.GetMinute(), dateTime.GetSecond()); +} + +result +_CalendarImpl::SetTimeImpl(int year, int month, int day, int hour, int minute, int second) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_LCL, ValidateTimeFieldValue(TIME_FIELD_YEAR, year), E_OUT_OF_RANGE, "year(%d) is out of range.", year); + SysTryReturnResult(NID_LCL, ValidateTimeFieldValue(TIME_FIELD_MONTH, month), E_OUT_OF_RANGE, "month(%d) is out of range.", month); + SysTryReturnResult(NID_LCL, ValidateTimeFieldValue(TIME_FIELD_DAY_OF_MONTH, day), E_OUT_OF_RANGE, "day(%d) is out of range.", day); + SysTryReturnResult(NID_LCL, ValidateTimeFieldValue(TIME_FIELD_HOUR_OF_DAY, hour),E_OUT_OF_RANGE, "hour(%d) is out of range.", hour); + SysTryReturnResult(NID_LCL, ValidateTimeFieldValue(TIME_FIELD_MINUTE, minute), E_OUT_OF_RANGE, "minute(%d) is out of range.", minute); + SysTryReturnResult(NID_LCL, ValidateTimeFieldValue(TIME_FIELD_SECOND, second), E_OUT_OF_RANGE, "second(%d) is out of range.", second); + + return __pCalendar->SetTime(year, month, day, hour, minute, second); +} + +result +_CalendarImpl::SetFirstDayOfWeekImpl(DayOfWeek dayOfWeek) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_LCL, ValidateDaysOfWeek(dayOfWeek), E_INVALID_ARG, "Invalid argument is used. Unknown day of week"); + + return __pCalendar->SetFirstDayOfWeek(dayOfWeek); +} + +result +_CalendarImpl::SetLenientImpl(bool lenient) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->SetLenient(lenient); +} + +result +_CalendarImpl::SetMinDaysInFirstWeekImpl(short value) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->SetMinDaysInFirstWeek(value); +} + +result +_CalendarImpl::SetTimeZoneImpl(const TimeZone& timeZone) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + + _timeZone = timeZone; + __timezone = timeZone; + return __pCalendar->SetTimeZone(__timezone); +} + +result +_CalendarImpl::ClearImpl(void) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->Clear(); +} + +result +_CalendarImpl::ClearImpl(TimeField field) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_LCL, ValidateTimeField(field), E_INVALID_ARG, + "Invalid argument is used. Timefield is less than 0 or grater than time field count."); + + return __pCalendar->Clear(field); +} + +result +_CalendarImpl::AddTimeField(TimeField field, int amount) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + + result r = E_INVALID_ARG; + + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_INVALID_STATE; + } + + SysTryReturnResult(NID_LCL, ValidateTimeField(field), r, + "Invalid argument is used. Timefield is less than 0 or grater than time field count."); + + return __pCalendar->AddTimeField(field, amount); +} + +result +_CalendarImpl::Roll(TimeField field, int amount) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + + result r = E_INVALID_ARG; + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_INVALID_STATE; + } + + SysTryReturnResult(NID_LCL, ValidateTimeField(field), r, + "Invalid argument is used. Timefield is less than 0 or grater than time field count."); + + return __pCalendar->Roll(field, amount); +} + +result +_CalendarImpl::After(const _CalendarImpl& otherInstance, bool& after) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + + result r = E_INVALID_ARG; + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_INVALID_STATE; + } + + SysTryReturnResult(NID_LCL, otherInstance.__pCalendar, r, "Invalid argument is used. otherCalendar instance is invalid"); + + return __pCalendar->After(*(otherInstance.__pCalendar), after); +} + +result +_CalendarImpl::Before(const _CalendarImpl& otherInstance, bool& before) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + + result r = E_INVALID_ARG; + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_INVALID_STATE; + } + + SysTryReturnResult(NID_LCL, otherInstance.__pCalendar, r, "Invalid argument is used. otherCalendar instance is invalid"); + + return __pCalendar->Before(*(otherInstance.__pCalendar), before); +} + +bool +_CalendarImpl::Equals(const _CalendarImpl& otherInstance) const +{ + if ((__pCalendar != null) && (otherInstance.__pCalendar != null)) + { + return __pCalendar->Equals(*(otherInstance.__pCalendar)); + } + return (__pCalendar == otherInstance.__pCalendar); +} + +int +_CalendarImpl::GetHashCode(void) const +{ + Integer intValues = IsLenient() + GetFirstDayOfWeek() + GetMinDaysInFirstWeek(); + int hashCode = intValues.GetHashCode(); + + long long myTicks = 0; + GetTimeInMillisec(myTicks); + hashCode = (hashCode << 5) - hashCode + LongLong(myTicks).GetHashCode()+__timezone.GetHashCode(); + + return hashCode; +} + +CalendarType +_CalendarImpl::GetType(void) const +{ + return __type; +} + +int +_CalendarImpl::GetTimeFieldImpl(TimeField field) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_LCL, ValidateTimeField(field), -1, E_INVALID_ARG, + "[%s] Invalid argument is used. Timefield is less than 0 or grater than time field count.", GetErrorMessage(E_INVALID_ARG)); + + return __pCalendar->GetTimeField(field); +} + +result +_CalendarImpl::GetTimeInMillisecImpl(long long& millisec) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + result r; + long long tempMillisec; + + r = __pCalendar->GetTimeInMillisec(tempMillisec); + SysTryReturnResult(NID_LCL, r == E_SUCCESS, r, "Unable to get time in milli sec"); + millisec = tempMillisec + __timezone.GetRawOffset() * ONE_MINUTE_IN_MILLISEC; + return r; +} + +DateTime +_CalendarImpl::GetTimeImpl(void) const +{ + int year = __pCalendar->GetTimeField(TIME_FIELD_YEAR); + int month = __pCalendar->GetTimeField(TIME_FIELD_MONTH); + int date = __pCalendar->GetTimeField(TIME_FIELD_DAY_OF_MONTH); + + int hour = __pCalendar->GetTimeField(TIME_FIELD_HOUR_OF_DAY); + int minute = __pCalendar->GetTimeField(TIME_FIELD_MINUTE); + int second = __pCalendar->GetTimeField(TIME_FIELD_SECOND); + + DateTime dateTime; + result r = dateTime.SetValue(year, month, date, hour, minute, second); + SysTryReturn(NID_LCL, r == E_SUCCESS, DateTime(), r, "[%s] Unable to set time in DateTime object", GetErrorMessage(r)); + + return dateTime; +} + +int +_CalendarImpl::GetMinTimeField(TimeField field) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_LCL, ValidateTimeField(field), -1, E_INVALID_ARG, + "[%s] Invalid argument is used. Timefield is less than 0 or grater than time field count.", GetErrorMessage(E_INVALID_ARG)); + + return __pCalendar->GetMinTimeField(field); +} + +int +_CalendarImpl::GetActualMinTimeField(TimeField field) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_LCL, ValidateTimeField(field), -1, E_INVALID_ARG, + "[%s] Invalid argument is used. Timefield is less than 0 or grater than time field count.", GetErrorMessage(E_INVALID_ARG)); + + return __pCalendar->GetActualMinTimeField(field); +} + +int +_CalendarImpl::GetGreatestMinTimeField(TimeField field) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_LCL, ValidateTimeField(field), -1, E_INVALID_ARG, + "[%s] Invalid argument is used. Timefield is less than 0 or grater than time field count.", GetErrorMessage(E_INVALID_ARG)); + + return __pCalendar->GetGreatestMinTimeField(field); +} + +int +_CalendarImpl::GetLeastMaxTimeField(TimeField field) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_LCL, ValidateTimeField(field), -1, E_INVALID_ARG, + "[%s] Invalid argument is used. Timefield is less than 0 or grater than time field count.", GetErrorMessage(E_INVALID_ARG)); + + return __pCalendar->GetLeastMaxTimeField(field); +} + +int +_CalendarImpl::GetActualMaxTimeField(TimeField field) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_LCL, ValidateTimeField(field), -1, E_INVALID_ARG, + "[%s] Invalid argument is used. Timefield is less than 0 or grater than time field count.", GetErrorMessage(E_INVALID_ARG)); + + return __pCalendar->GetActualMaxTimeField(field); +} + +int +_CalendarImpl::GetMaxTimeField(TimeField field) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturn(NID_LCL, ValidateTimeField(field), -1, E_INVALID_ARG, + "[%s] Invalid argument is used. Timefield is less than 0 or grater than time field count.", GetErrorMessage(E_INVALID_ARG)); + + return __pCalendar->GetMaxTimeField(field); +} + +int +_CalendarImpl::GetFirstDayOfWeekImpl(void) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->GetFirstDayOfWeek(); +} + +int +_CalendarImpl::GetMinDaysInFirstWeekImpl(void) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->GetMinDaysInFirstWeek(); +} + +result +_CalendarImpl::IsInDst(bool& isInDst) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->IsInDst(isInDst); +} + +bool +_CalendarImpl::IsLenientImpl(void) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->IsLenient(); +} + +bool +_CalendarImpl::IsSetImpl(TimeField field) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->IsSet(field); +} + +TimeZone +_CalendarImpl::GetTimeZoneImpl(void) const +{ + return __timezone; +} + +bool +_CalendarImpl::IsLeapYear(int year) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->IsLeapYear(year); +} + +result +_CalendarImpl::SetGregorianChange(long long change) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->SetGregorianChange(change); +} + +long long +_CalendarImpl::GetGregorianChange(void) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->GetGregorianChange(); +} + +result +_CalendarImpl::SetJulianDay(int julianDay) +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->SetJulianDay(julianDay); +} + +int +_CalendarImpl::GetJulianDay(void) const +{ + SysAssertf(__pCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pCalendar->GetJulianDay(); +} + +bool +_CalendarImpl::ValidateTimeField(TimeField field) const +{ + if (field < 0 || field >= TIME_FIELD_FIELD_COUNT) + { + return false; + } + return true; +} + +bool +_CalendarImpl::ValidateTimeFieldValue(TimeField field, int value) const +{ + if (IsLenientImpl() == false) + { + if ((value < GetMinTimeField(field)) || (value > GetMaxTimeField(field))) + { + return false; + } + } + + return true; +} + +bool +_CalendarImpl::ValidateDaysOfWeek(DayOfWeek dayOfWeek) const +{ + if (dayOfWeek < SUNDAY || dayOfWeek > SATURDAY) + { + return false; + } + return true; +} + +// added for backward compatibility +result +_CalendarImpl::RollWithSingleUnit(TimeField field, bool up) +{ + return E_UNSUPPORTED_OPERATION; +} + +// added for backward compatibility +result +_CalendarImpl::ComputeTimeFields(void) +{ + return E_UNSUPPORTED_OPERATION; +} + +// added for backward compatibility +result +_CalendarImpl::ComputeTime(void) +{ + return E_UNSUPPORTED_OPERATION; +} + +// added for backward compatibility +int +_CalendarImpl::GetMonthLength(int extendedYear, int month) const +{ + SetLastResult(E_UNSUPPORTED_OPERATION); + return -1; +} + +// added for backward compatibility +int +_CalendarImpl::HandleGetLimit(TimeField field, CalendarLimitType limitType) const +{ + SetLastResult(E_UNSUPPORTED_OPERATION); + return -1; +} + +const _IcuCalendarImpl* +_CalendarImpl::GetImpl(const Calendar& calendar) +{ + if (calendar._pCalendarImpl) + { + return calendar._pCalendarImpl->__pCalendar; + } + + return null; +} + +}; +}; // Tizen::Locales diff --git a/src/locales/FLcl_CalendarImpl.h b/src/locales/FLcl_CalendarImpl.h new file mode 100644 index 0000000..211d154 --- /dev/null +++ b/src/locales/FLcl_CalendarImpl.h @@ -0,0 +1,137 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_CalendarImpl.h + * @brief This is the header file for the _CalendarImpl class. + * + * This header file contains the declarations of the _CalendarImpl class. + * + */ + +#ifndef _FLCL_INTERNAL_CALENDAR_IMPL_H_ +#define _FLCL_INTERNAL_CALENDAR_IMPL_H_ + +#include + +namespace Tizen { namespace Locales +{ + +class _IcuCalendarImpl; + +class _CalendarImpl + : public Calendar +{ +public: + _CalendarImpl(); + virtual ~_CalendarImpl(); + + virtual Calendar* CloneN(void) const; + + // Construct methods + result Construct(CalendarType calendarType = CALENDAR_GREGORIAN); + result Construct(const TimeZone& timezone, CalendarType calendarType = CALENDAR_GREGORIAN); + result Construct(const Locale& locale, CalendarType calendarType = CALENDAR_GREGORIAN); + result Construct(const TimeZone& timezone, const Locale& locale, CalendarType calendarType = CALENDAR_GREGORIAN); + result Construct(const Calendar& otherCalendar); + + // Set methods + result SetTimeFieldImpl(TimeField field, int value); + result SetTimeInMillisecImpl(long long millisec); + result SetTimeImpl(const Tizen::Base::DateTime& dateTime); + result SetTimeImpl(int year, int month, int day, int hour = 0, int minute = 0, int second = 0); + + result SetFirstDayOfWeekImpl(DayOfWeek dayOfWeek); + result SetLenientImpl(bool lenient); + result SetMinDaysInFirstWeekImpl(short value); + result SetTimeZoneImpl(const TimeZone& timeZone); + + // Methods to clear/ adjust time-fields + result ClearImpl(void); + result ClearImpl(TimeField field); + + result AddTimeField(TimeField field, int amount); + result Roll(TimeField field, int amount); + + // Methods to compare Calendars + result After(const _CalendarImpl& otherInstance, bool& after); + result Before(const _CalendarImpl& otherInstance, bool& before); + bool Equals(const _CalendarImpl& otherInstance) const; + + // Get methods + int GetHashCode(void) const; + CalendarType GetType(void) const; + + int GetTimeFieldImpl(TimeField field) const; + result GetTimeInMillisecImpl(long long& millisec) const; + Tizen::Base::DateTime GetTimeImpl(void) const; + + int GetMinTimeField(TimeField field) const; + int GetActualMinTimeField(TimeField field) const; + int GetGreatestMinTimeField(TimeField field) const; + + int GetLeastMaxTimeField(TimeField field) const; + int GetActualMaxTimeField(TimeField field) const; + int GetMaxTimeField(TimeField field) const; + + int GetFirstDayOfWeekImpl(void) const; + int GetMinDaysInFirstWeekImpl(void) const; + result IsInDst(bool& isInDst) const; + bool IsLenientImpl(void) const; + bool IsSetImpl(TimeField field) const; + TimeZone GetTimeZoneImpl(void) const; + + // methods for gregorian calendar + bool IsLeapYear(int year) const; + result SetGregorianChange(long long change); + long long GetGregorianChange(void) const; + result SetJulianDay(int julianDay); + int GetJulianDay(void) const; + + static Calendar* CreateCalendarInstanceN(CalendarType calendarType); + static Calendar* CreateCalendarInstanceN(const TimeZone& timeZone, CalendarType calendarType); + static Calendar* CreateCalendarInstanceN(const Locale& locale, CalendarType calendarType); + static Calendar* CreateCalendarInstanceN(const TimeZone& timeZone, const Locale& locale, CalendarType calendarType); + + static const _IcuCalendarImpl* GetImpl(const Calendar& calendar); + + // added for backward compatibility + virtual result RollWithSingleUnit(TimeField field, bool up); + virtual result ComputeTimeFields(void); + virtual result ComputeTime(void); + virtual int GetMonthLength(int extendedYear, int month) const; + virtual int HandleGetLimit(TimeField field, CalendarLimitType limitType) const; + +private: + _CalendarImpl(const _CalendarImpl& orig); + _CalendarImpl& operator =(const _CalendarImpl& orig); + + bool ValidateTimeField(TimeField field) const; + bool ValidateTimeFieldValue(TimeField field, int value) const; + bool ValidateDaysOfWeek(DayOfWeek dayOfWeek) const; + +private: + CalendarType __type; + Locale __locale; + TimeZone __timezone; + class _IcuCalendarImpl* __pCalendar; + +}; + +}} // Tizen::Locales + +#endif // _FLCL_INTERNAL_CALENDAR_IMPL_H_ diff --git a/src/locales/FLcl_CurrencyImpl.cpp b/src/locales/FLcl_CurrencyImpl.cpp new file mode 100644 index 0000000..681e513 --- /dev/null +++ b/src/locales/FLcl_CurrencyImpl.cpp @@ -0,0 +1,141 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_CurrencyImpl.cpp + * @brief This is the implementation file for _CurrencyImpl class. + */ +#include +#include + +#include +#include + +#include "FLcl_LocaleData.h" +#include "FLcl_LocaleImpl.h" +#include "FLcl_CurrencyImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +result +_CurrencyImpl::GetCurrencyCodeSymbol(const Locale& locale, Tizen::Base::String& currencyCodeSymbol) +{ + const _LocaleImpl* pLclImpl = _LocaleImpl::GetLocaleImpl(locale); + SysTryReturnResult(NID_LCL, pLclImpl != null && pLclImpl->IsLocaleSupported(), + E_INVALID_ARG, "Invalid argument is used. Given locale is not supported"); + + UErrorCode ec = U_ZERO_ERROR; + IcuDecimalFormatSymbols sym(pLclImpl->GetIcuLocale(), ec); + if (U_SUCCESS(ec)) + { + String currCode = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kIntlCurrencySymbol)); + String currSym = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kCurrencySymbol)); + + if (currCode.IsEmpty() || currSym.IsEmpty()) + { + currCode = ""; + currSym = ""; + return E_SYSTEM; + } + else + { + currencyCodeSymbol = currCode + "_" + currSym; + return E_SUCCESS; + } + } + + return (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) ? E_UNSUPPORTED_OPERATION : E_INVALID_ARG; +} + +result +_CurrencyImpl::GetCurrencyCodeSymbol(const String currencyCode, String& currencyCodeSymbol) +{ + int count = 0; + const IcuLocale* pIcuLocaleList = IcuLocale::getAvailableLocales(count); + SysTryReturnResult(NID_LCL, pIcuLocaleList && (count > 0), E_SYSTEM, "The method cannot proceed due to a severe system error."); + + for (int i = 0; i < count; i++) + { + SysTryReturnResult(NID_LCL, (pIcuLocaleList + i) != null, E_SYSTEM, "The method cannot proceed due to a severe system error."); + + UErrorCode ec = U_ZERO_ERROR; + IcuDecimalFormatSymbols sym(*(pIcuLocaleList + i), ec); + SysTryReturnResult(NID_LCL, U_SUCCESS(ec), E_SYSTEM, "The method cannot proceed due to a severe system error."); + + String currCode = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kIntlCurrencySymbol)); + if (currCode == currencyCode) + { + String currencySymbol= _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kCurrencySymbol)); + currencyCodeSymbol = currencyCode + "_" + currencySymbol; + return E_SUCCESS; + } + } + return E_INVALID_ARG; +} + +IList* +_CurrencyImpl::GetAvailableCurrenciesN(void) +{ + int count = 0; + const IcuLocale* pIcuLocaleList = IcuLocale::getAvailableLocales(count); + SysTryReturn(NID_LCL, pIcuLocaleList && (count > 0), null,E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.",GetErrorMessage(E_SYSTEM)); + + std::unique_ptr pNewList(new (std::nothrow) ArrayList()); + SysTryReturn(NID_LCL, pNewList, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < count; i++) + { + SysTryReturn(NID_LCL, (pIcuLocaleList + i) != null, null, E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.",GetErrorMessage(E_SYSTEM)); + + UErrorCode ec = U_ZERO_ERROR; + IcuDecimalFormatSymbols sym(*(pIcuLocaleList + i), ec); + SysTryReturn(NID_LCL, U_SUCCESS(ec), null, E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.",GetErrorMessage(E_SYSTEM)); + + String currCode = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kIntlCurrencySymbol)); + String currSymbol= _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kCurrencySymbol)); + + if (!currCode.IsEmpty() && !currSymbol.IsEmpty()) + { + Currency* pCurr = new (std::nothrow) Currency; + SysTryReturn(NID_LCL, pCurr, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + pCurr->__currencyCodeSymbol = currCode + "_" + currSymbol; + if (!pNewList->Contains(*pCurr)) + { + result r = pNewList->Add(*(pCurr)); + if (IsFailed(r)) + { + delete pCurr; + SetLastResult(E_SYSTEM); + return null; + } + } + } + } + + SetLastResult(E_SUCCESS); + return pNewList.release(); +} + + +}}//Tizen::Locales diff --git a/src/locales/FLcl_CurrencyImpl.h b/src/locales/FLcl_CurrencyImpl.h new file mode 100644 index 0000000..4bb3c08 --- /dev/null +++ b/src/locales/FLcl_CurrencyImpl.h @@ -0,0 +1,44 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_CurrencyImpl.h + * @brief This is the header file for the %Currency class. + * + * This header file contains the declarations of the %Currency class. + * + */ +#ifndef _FLCL_INTERNAL_CURRENCY_IMPL_H_ +#define _FLCL_INTERNAL_CURRENCY_IMPL_H_ + +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +namespace Tizen { namespace Locales +{ +class _CurrencyImpl + :public Tizen::Base::Object +{ +public: + static result GetCurrencyCodeSymbol(const Locale& locale, String& currencyCodeSymbol); + static result GetCurrencyCodeSymbol(const String currencyCode, String& currencyCodeSymbol); + static IList* GetAvailableCurrenciesN(void); +}; +}} +#endif //_FLCL_INTERNAL_CURRENCY_IMPL_H_ diff --git a/src/locales/FLcl_DateTimeFormatterImpl.cpp b/src/locales/FLcl_DateTimeFormatterImpl.cpp new file mode 100644 index 0000000..a00830f --- /dev/null +++ b/src/locales/FLcl_DateTimeFormatterImpl.cpp @@ -0,0 +1,171 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclDateTimeFormatter.cpp + * @brief This is the implementation file for DateTimeFormatter class. + */ + +// Includes +#include +#include +#include +#include +#include "FLcl_DateTimeFormatterImpl.h" +#include "FLcl_LocaleData.h" +#include "FLcl_LocaleManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +namespace Tizen { namespace Locales +{ + +_DateTimeFormatterImpl::_DateTimeFormatterImpl(void) + : __pLocaleData(null) + , __pSymbols(null) +{ +} + +_DateTimeFormatterImpl::~_DateTimeFormatterImpl(void) +{ + delete __pLocaleData; + delete __pSymbols; +} + +// The DateTimeFormatter always use System Locale if not provided by the user. +// System locale may be different for default ICU locale. +DateTimeFormatter* +_DateTimeFormatterImpl::CreateInstanceN(DateTimeStyle dateStyle, DateTimeStyle timeStyle) +{ + result r = E_INVALID_ARG; + + if (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) + { + r = E_UNSUPPORTED_OPERATION; + } + + SysTryReturn(NID_LCL, ValidateDateTimeStyle(dateStyle), null, r, "[%s] Invalid argument is used. dateStyle is invalid", GetErrorMessage(r)); + SysTryReturn(NID_LCL, ValidateDateTimeStyle(timeStyle), null, r, "[%s] Invalid argument is used. timeStyle is invalid", GetErrorMessage(r)); + + // using system locale, may be different from ICU default locale + DateTimeFormatter* pDateTimeFormatter = CreateInstanceN(_LocaleManagerImpl::GetSystemLocale(), dateStyle, timeStyle); + + if (GetLastResult() == E_INVALID_ARG) + { + SetLastResult(E_UNSUPPORTED_OPERATION); + } + return pDateTimeFormatter; +} + +DateTimeFormatter* +_DateTimeFormatterImpl::CreateInstanceN(const Locale& locale, DateTimeStyle dateStyle, DateTimeStyle timeStyle) +{ + result r = (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) ? E_UNSUPPORTED_OPERATION : E_INVALID_ARG; + + SysTryReturn(NID_LCL, ValidateDateTimeStyle(dateStyle), null, r, "[%s] Invalid argument is used. dateStyle is invalid", GetErrorMessage(r)); + SysTryReturn(NID_LCL, ValidateDateTimeStyle(timeStyle), null, r, "[%s] Invalid argument is used. timeStyle is invalid", GetErrorMessage(r)); + + ClearLastResult(); + + // Create a DateTimeFormatter of the desired style. + std::unique_ptr pDateTimeFormatter(new (std::nothrow) DateTimeFormatter()); + SysTryReturn(NID_LCL, pDateTimeFormatter, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + std::unique_ptr<_DateTimeFormatterImpl> pDateTimeFormatterImpl(new (std::nothrow) _DateTimeFormatterImpl); + SysTryReturn(NID_LCL,pDateTimeFormatterImpl, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + std::unique_ptr<_LocaleData> pLocaleData(new (std::nothrow) _LocaleData); + SysTryReturn(NID_LCL, pLocaleData, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + // This create and set ICU DateFormatter in _Locale data object for future use + r = pLocaleData->SetDateTimeFormatter(dateStyle, timeStyle, locale); + SysTryReturn(NID_LCL, !IsFailed(r), null, r, "[%s]",GetErrorMessage(r)); + + // Create DateTimeSymbols and construct using locale + pDateTimeFormatterImpl->__pSymbols = new (std::nothrow) DateTimeSymbols; + if (pDateTimeFormatterImpl->__pSymbols) + { + pDateTimeFormatterImpl->__pSymbols->Construct(locale); + } + + pDateTimeFormatter->__pDateTimeFormatterImpl = pDateTimeFormatterImpl.release(); + pDateTimeFormatter->__pDateTimeFormatterImpl->__pLocaleData = pLocaleData.release(); + return pDateTimeFormatter.release(); // Here as LastResult is already cleared, no need to set it to E_SUCCESS +} + +// This function will not have TimeZone informations and always print time zone as GMT+00:00 +result +_DateTimeFormatterImpl::Format(const DateTime& date, String& strBuf) const +{ + SysAssertf(__pLocaleData != null, "Not yet constructed! Construct() should be called before use."); + return __pLocaleData->FormatDateTime(date, strBuf); // Format date using ICU date formatter +} + +result +_DateTimeFormatterImpl::Format(const Calendar& calendar, String& strBuf) const +{ + SysAssertf(__pLocaleData != null, "Not yet constructed! Construct() should be called before use."); + return __pLocaleData->FormatDateTime(calendar, strBuf); // Format date using ICU date formatter +} + +// This function sets pattern used by DateTimeFormatter for formatting date. +// Please check http://icu-project.org/apiref/icu4c/classSimpleDateFormat.html for possible letter and +// their meaning in patter string. +result +_DateTimeFormatterImpl::ApplyPattern(const String& pattern) +{ + SysAssertf(__pLocaleData != null, "Not yet constructed! Construct() should be called before use."); + return __pLocaleData->SetDateTimePattern(pattern); // Set pattern to ICU date formatter +} + +String +_DateTimeFormatterImpl::GetPattern(void) const +{ + return __pLocaleData->GetDateTimePattern(); +} + +const DateTimeSymbols* +_DateTimeFormatterImpl::GetDateTimeSymbols(void) const +{ + return __pSymbols; +} + +void +_DateTimeFormatterImpl::SetDateTimeSymbols(const DateTimeSymbols& newSymbols) +{ + SysAssertf(__pLocaleData != null, "Not yet constructed! Construct() should be called before use."); + + result r = __pLocaleData->SetDateTimeSymbols(newSymbols); // Set symbols to ICU date formatter + if (!IsFailed(r)) + { + if (__pSymbols) + { + __pSymbols = __pLocaleData->GetDateTimeSymbolsN(__pSymbols); // Set __pSymbols obtained from ICU date formatter + } + } +} + +bool +_DateTimeFormatterImpl::ValidateDateTimeStyle(DateTimeStyle dateTimeStyle) +{ + return (dateTimeStyle < DATE_TIME_STYLE_NONE || dateTimeStyle > DATE_TIME_STYLE_SHORT)? false : true; +} + +}; +}; // Tizen::Locales diff --git a/src/locales/FLcl_DateTimeFormatterImpl.h b/src/locales/FLcl_DateTimeFormatterImpl.h new file mode 100644 index 0000000..1d5c750 --- /dev/null +++ b/src/locales/FLcl_DateTimeFormatterImpl.h @@ -0,0 +1,172 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_DateTimeFormatterImpl.h + * @brief This is the header file for the _DateTimeFormatterImpl class. + * + * This header file contains the declarations of the _DateTimeFormatterImpl class. + * + */ +#ifndef _FLCL_INTERNAL_DATE_TIME_FORMATTER_IMPL_H_ +#define _FLCL_INTERNAL_DATE_TIME_FORMATTER_IMPL_H_ + +// Includes +#include +#include +#include +#include + + +namespace Tizen { namespace Locales +{ +class NumberFormatter; +class _LocaleData; +}; +}; + + +namespace Tizen { namespace Locales +{ + +class _DateTimeFormatterImpl + : public Tizen::Base::Object +{ + +public: + _DateTimeFormatterImpl(void); + ~_DateTimeFormatterImpl(void); + + + static DateTimeFormatter* CreateInstanceN(const Locale& locale, DateTimeStyle dateStyle, DateTimeStyle timeStyle); + static DateTimeFormatter* CreateInstanceN(DateTimeStyle dateStyle, DateTimeStyle timeStyle); + + +// Operations +public: + /** + * Formats a DateTime object into a date/time string and appends the resulting string to the specified string buffer. + * + * @since 1.0 + * @return An error code + * @param[in] date The DateTime object to format + * @param[out] str The String to append the resulting string to + * @exception E_SUCCESS The method was successful. + * @remarks This method does not handle the time zone information, so "z" pattern always returns "GMT+00:00". + * @see Tizen::Base::DateTime + */ + virtual result Format(const Tizen::Base::DateTime& date, Tizen::Base::String& str) const; + + + /** + * Formats a Calendar object into a date/time string and appends the resulting string to the specified string buffer. + * + * @since 1.0 + * @return An error code + * @param[in] calendar The Calendar object to format + * @param[out] str The String to append the resulting string to + * @exception E_SUCCESS The method was successful. + * @see Tizen::Base::DateTime + */ + virtual result Format(const Calendar& calendar, Tizen::Base::String& str) const; + + +//private: + +// Operation +public: + /** + * Applies the specified pattern string to the date format. + * + * @since 1.0 + * @param[in] pattern The new date and time pattern for the date format + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG The length of specified @c pattern is 0. + */ + result ApplyPattern(const Tizen::Base::String& pattern); + + + /** + * Gets a pattern string describing the date format. + * + * @since 1.0 + * @return A String describing the date format + */ + Tizen::Base::String GetPattern(void) const; + + + /** + * Gets the date and time format symbols of the formatter. + * + * @since 1.0 + * @return A pointer to DateTimeSymbols for the formatter instance + * @see SetDateTimeSymbols() + */ + const DateTimeSymbols* GetDateTimeSymbols(void) const; + + + /** + * Sets the date and time format symbols of the date format. + * + * @since 1.0 + * @param[in] newSymbols The new date and time format symbols + * @see GetDateTimeSymbols() + */ + void SetDateTimeSymbols(const DateTimeSymbols& newSymbols); + + /** + * Formats a DateTime into a date/time string and appends the result string to a given string buffer. + * + * @return An error code + * @param[in] date The DateTime object to format + * @param[in] pos On input: an alignment field, if desired @n + * On output: the offsets of the alignment field + * @param[out] str The String where the formatted string is to be appended + * @exception E_SUCCESS The method was successful. + * @see Tizen::Base::DateTime + */ + result Format(const Tizen::Base::DateTime& date, _FieldPosition& pos, Tizen::Base::String& str) const; + + + /** + * Formats a Calendar into a date/time string and appends the result string to a given string buffer. + * + * @return An error code + * @param[in] cal The Calendar object to format + * @param[in] pos On input: an alignment field, if desired @n + * On output: the offsets of the alignment field + * @param[out] str The String where the formatted string is to be appended + * @exception E_SUCCESS The method was successful. + * @see Calendar() + */ + result Format(const Calendar& calendar, _FieldPosition& pos, Tizen::Base::String& str) const; + + static bool ValidateDateTimeStyle(DateTimeStyle dateTimeStyle); +private: + _DateTimeFormatterImpl(const _DateTimeFormatterImpl& dateTimeFormatterImpl); + _DateTimeFormatterImpl& operator =(const _DateTimeFormatterImpl& dateTimeFormatterImpl); + +// Attribute + _LocaleData* __pLocaleData; + DateTimeSymbols* __pSymbols; + +}; // _DateTimeFormatterImpl +}; +}; // Tizen::Locales + +#endif //_FLCL_INTERNAL_DATE_TIME_FORMATTER_IMPL_H_ + diff --git a/src/locales/FLcl_DateTimeSymbolsImpl.cpp b/src/locales/FLcl_DateTimeSymbolsImpl.cpp new file mode 100644 index 0000000..79ef05f --- /dev/null +++ b/src/locales/FLcl_DateTimeSymbolsImpl.cpp @@ -0,0 +1,610 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_DateTimeSymbolsImpl.cpp + * @brief This is the implementation file for _DateTimeSymbolsImpl class. + */ + +#include + +#include +#include +#include "FLcl_DateTimeSymbolsImpl.h" +#include "FLcl_LocaleData.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +namespace Tizen { namespace Locales +{ + +// This will be used to define non localized pattern string. +static const wchar_t PATTERN_CHARS[] = +{ + // GyMdkHmsSEDFwWahKzYeugAZ + 0x47, 0x79, 0x4D, 0x64, 0x6B, 0x48, 0x6D, 0x73, 0x53, 0x45, 0x44, + 0x46, 0x77, 0x57, 0x61, 0x68, 0x4B, 0x7A, 0x59, 0x65, 0x75, 0x67, + 0x41, 0x5A, 0 // Should be ended with 0 as we are not setting null at the end of the pattern +}; + +static const int PATTERN_LENGTH = 24 + 1; // 24 Char and one null (0) + +static const int ERAS_COUNT = 2; +static const int MONTH_COUNT = 12; +static const int WEEKDAYS_COUNT = 7; +static const int AM_PM_COUNT =2; + +static const int MAX_TIMEZONE_NAME = 4; + +WcharBuffer* +_DateTimeSymbolsImpl::GetNonLocalizedDateTimePatternN(void) +{ + ClearLastResult(); + std::unique_ptr< WcharBuffer > pChars(new (std::nothrow) WcharBuffer()); + SysTryReturn(NID_TEXT, pChars, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = pChars->Construct(PATTERN_LENGTH); + SysTryCatch(NID_LCL, r == E_SUCCESS, , r, "[%s] Propagated.", GetErrorMessage(r)); + + r = pChars->SetArray(PATTERN_CHARS, 0, PATTERN_LENGTH); // Setting value from PATTERN_CHARS defined above + SysTryCatch(NID_LCL, r == E_SUCCESS, , r, "[%s] Propagated.", GetErrorMessage(r)); + + pChars->Flip(); + return pChars.release(); + +CATCH: + return null; +} + +_DateTimeSymbolsImpl::_DateTimeSymbolsImpl(void) + : __pErasList(null) + , __pMonthsList(null) + , __pShortMonthsList(null) + , __pWeekdaysList(null) + , __pShortWeekdaysList(null) + , __pAmPmList(null) + , __pTimeZonesMap(null) + , __CalendarType(CALENDAR_GREGORIAN) + , __pIcuDateFormatSymbols(null) +{ +} + +_DateTimeSymbolsImpl::~_DateTimeSymbolsImpl(void) +{ + ReleaseAll(); + if (__pIcuDateFormatSymbols) + { + delete __pIcuDateFormatSymbols; + } +} + +result +_DateTimeSymbolsImpl::Initialize(CalendarType calendarType) +{ + return Initialize(_LocaleData::GetOspSystemLocale(), calendarType); +} + +result +_DateTimeSymbolsImpl::Initialize(const Locale& locale, CalendarType calendarType) +{ + SysTryReturnResult(NID_LCL, locale.GetCountryCode() != COUNTRY_INVALID, E_INVALID_ARG, + "Invalid argument is used. Country code is invalid. Given locale is not supported"); + SysTryReturnResult(NID_LCL, locale.GetLanguageCode() != LANGUAGE_INVALID, E_INVALID_ARG, + "Invalid argument is used. Language code is invalid. Given locale is not supported"); + + _LocaleData localeData; + result r = localeData.SetDateFormatSymbols(locale); // this will set ICU DateTimeSymbol in _LocaleData object for future use + + if (!IsFailed(r)) + { + __pErasList = localeData.GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_ERA_LIST); + __pMonthsList = localeData.GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_MONTH_LIST); + __pShortMonthsList = localeData.GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_SHORT_MONTH_LIST); + __pWeekdaysList = localeData.GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_WEEKDAY_LIST); + __pShortWeekdaysList = localeData.GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_SHORT_WEEKDAY_LIST); + __pAmPmList = localeData.GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_AM_PM_LIST); + __CalendarType = calendarType; + + UErrorCode ec = U_ZERO_ERROR; + __pIcuDateFormatSymbols = new IcuDateFormatSymbols(ec); + } + + return r; +} + +void +_DateTimeSymbolsImpl::Set(const _DateTimeSymbolsImpl* pOther) +{ + SysTryReturnVoidResult(NID_LCL, pOther != null, E_INVALID_ARG, + "[%s] Invalid argument is used. pOther instance is invalid", GetErrorMessage(E_INVALID_ARG)); + + __pErasList = CloneArrayListN(pOther->__pErasList); // Copying EraList + __pMonthsList = CloneArrayListN(pOther->__pMonthsList); // Copying Month List + __pShortMonthsList = CloneArrayListN(pOther->__pShortMonthsList); // Copying Short Month List + __pWeekdaysList = CloneArrayListN(pOther->__pWeekdaysList); // Copying Weekdays List + __pShortWeekdaysList = CloneArrayListN(pOther->__pShortWeekdaysList); // Copying Short Weekdays List + __pAmPmList = CloneArrayListN(pOther->__pAmPmList); // Copying AM/ PM String + if(pOther->__pTimeZonesMap) + { + __pTimeZonesMap = CloneMultiHashMapN(pOther->__pTimeZonesMap); // Copying available TimeZone List + } + __CalendarType = pOther->__CalendarType; // Copying Calendar Type +} + + +result +_DateTimeSymbolsImpl::AddTimeZoneName(const String& timeZoneId, const String& concatenatedTimeZoneName, bool isOverwrite) +{ + StringTokenizer tokenizer(concatenatedTimeZoneName, L"|"); + SysTryReturnResult(NID_LCL, (tokenizer.GetTokenCount() == MAX_TIMEZONE_NAME), + E_INVALID_ARG, "Invalid argument is used. %ls is invalid.", concatenatedTimeZoneName.GetPointer()); + result r; + + if (!isOverwrite) + { + String tzName(timeZoneId); + GetTimeZoneName(tzName, 0); + + r = GetLastResult(); + SysTryReturnResult(NID_LCL, r != E_SUCCESS, E_OBJ_ALREADY_EXIST, "The timeZoneId already exists."); + } + + if (!__pTimeZonesMap) + { + MultiHashMap* pMultiHashMap = new (std::nothrow) MultiHashMap(); + SysTryReturnResult(NID_LCL, pMultiHashMap, E_OUT_OF_MEMORY, "Memory allocation failed."); + pMultiHashMap->Construct(); + + __pTimeZonesMap = (IMultiMap*) pMultiHashMap; + } + + String token; + std::unique_ptr< String >pKey(new (std::nothrow) String(timeZoneId)); + SysTryReturnResult(NID_LCL, pKey, E_OUT_OF_MEMORY, "Memory allocation failed"); + + r = E_OUT_OF_MEMORY; + while (tokenizer.HasMoreTokens()) + { + tokenizer.GetNextToken(token); + std::unique_ptr< String >pValue(new (std::nothrow)String(token)); + if (pValue) + { + r = __pTimeZonesMap->Add(*pKey, *pValue); + if (IsFailed(r)) + { + __pTimeZonesMap->Remove(*pKey,true); + return E_OUT_OF_MEMORY; + } + pValue.release(); + } + } + + pKey.release(); + return r; +} + + +const IList* +_DateTimeSymbolsImpl::GetAmPm(void) const +{ + SysAssertf(__pAmPmList != null, "Not yet constructed! Construct() should be called before use"); + + ClearLastResult(); // Setting Last result to E_SUCCESS + return __pAmPmList; +} + + +result +_DateTimeSymbolsImpl::SetAmPm(const String& amPm) +{ + SysAssertf(__pAmPmList != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< ArrayList, AllElementsDeleter > pTempArrayList(new (std::nothrow) ArrayList()); + SysTryReturnResult(NID_LCL, pTempArrayList != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = SetList(pTempArrayList.get(), AM_PM_COUNT, amPm); + if (!IsFailed(r)) + { + __pAmPmList->RemoveAll(true); + delete __pAmPmList; + __pAmPmList = pTempArrayList.release(); + } + + return r; +} + +const IList* +_DateTimeSymbolsImpl::GetEras(void) const +{ + SysAssertf(__pErasList != null, "Not yet constructed! Construct() should be called before use"); + return __pErasList; +} + +result +_DateTimeSymbolsImpl::SetEras(const String& eras) +{ + SysAssertf(__pErasList != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< ArrayList, AllElementsDeleter > pTempArrayList(new (std::nothrow) ArrayList()); + SysTryReturnResult(NID_LCL, pTempArrayList != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = SetList(pTempArrayList.get(), ERAS_COUNT, eras); + if (!IsFailed(r)) + { + __pErasList->RemoveAll(true); + delete __pErasList; + + __pErasList = pTempArrayList.release(); + } + + return r; +} + +const IList* +_DateTimeSymbolsImpl::GetMonths(void) const +{ + SysAssertf(__pMonthsList != null, "Not yet constructed! Construct() should be called before use"); + + ClearLastResult(); // Setting Last result to E_SUCCESS + return __pMonthsList; +} + +result +_DateTimeSymbolsImpl::SetMonths(const String& months) +{ + SysAssertf(__pMonthsList != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< ArrayList, AllElementsDeleter > pTempArrayList(new (std::nothrow) ArrayList()); + SysTryReturnResult(NID_LCL, pTempArrayList != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = SetList(pTempArrayList.get(), MONTH_COUNT, months); + if (!IsFailed(r)) + { + __pMonthsList->RemoveAll(true); + delete __pMonthsList; + + __pMonthsList = pTempArrayList.release(); + } + + return r; +} +const IList* +_DateTimeSymbolsImpl::GetShortMonths(void) const +{ + SysAssertf(__pShortMonthsList != null, "Not yet constructed! Construct() should be called before use"); + + ClearLastResult(); // Setting Last result to E_SUCCESS + return __pShortMonthsList; +} + +result +_DateTimeSymbolsImpl::SetShortMonths(const String& shortMonths) +{ + SysAssertf(__pShortMonthsList != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< ArrayList, AllElementsDeleter > pTempArrayList(new (std::nothrow) ArrayList()); + SysTryReturnResult(NID_LCL, pTempArrayList != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = SetList(pTempArrayList.get(), MONTH_COUNT, shortMonths); + if (!IsFailed(r)) + { + __pShortMonthsList->RemoveAll(true); + delete __pShortMonthsList; + + __pShortMonthsList = pTempArrayList.release(); + } + + return r; +} + +const IList* +_DateTimeSymbolsImpl::GetWeekdays(void) const +{ + SysAssertf(__pWeekdaysList != null, "Not yet constructed! Construct() should be called before use"); + + ClearLastResult(); // Setting Last result to E_SUCCESS + return __pWeekdaysList; +} + +result +_DateTimeSymbolsImpl::SetWeekdays(const String& weekdays) +{ + SysAssertf(__pWeekdaysList != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< ArrayList, AllElementsDeleter > pTempArrayList(new (std::nothrow) ArrayList()); + SysTryReturnResult(NID_LCL, pTempArrayList != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = SetList(pTempArrayList.get(), WEEKDAYS_COUNT, weekdays); + if (!IsFailed(r)) + { + __pWeekdaysList->RemoveAll(true); + delete __pWeekdaysList; + + __pWeekdaysList = pTempArrayList.release(); + } + + return r; +} + + +const IList* +_DateTimeSymbolsImpl::GetShortWeekdays(void) const +{ + SysAssertf(__pShortWeekdaysList != null, "Not yet constructed! Construct() should be called before use"); + + ClearLastResult(); // Setting Last result to E_SUCCESS + return __pShortWeekdaysList; +} + +result +_DateTimeSymbolsImpl::SetShortWeekdays(const String& shortWeekdays) +{ + SysAssertf(__pShortWeekdaysList != null, "Not yet constructed! Construct() should be called before use"); + + std::unique_ptr< ArrayList, AllElementsDeleter > pTempArrayList(new (std::nothrow) ArrayList()); + SysTryReturnResult(NID_LCL, pTempArrayList != null, E_OUT_OF_MEMORY, "Memory allocation failed."); + + result r = SetList(pTempArrayList.get(), WEEKDAYS_COUNT, shortWeekdays); + if (!IsFailed(r)) + { + __pShortWeekdaysList->RemoveAll(true); + delete __pShortWeekdaysList; + + __pShortWeekdaysList = pTempArrayList.release(); + } + + return r; +} + + +String +_DateTimeSymbolsImpl::GetTimeZoneName(Tizen::Base::String& timeZoneId, int timeZoneStyle) +{ + SysTryReturn(NID_LCL, timeZoneStyle < MAX_TIMEZONE_NAME, String(), E_INVALID_ARG, + "[%s] Invalid argument is used. timeZoneStyle(%d) is grater than MAX_TIMEZONE_NAME", GetErrorMessage(E_INVALID_ARG), timeZoneStyle); + + ClearLastResult(); + + if (__pTimeZonesMap && __pTimeZonesMap->GetValuesN(timeZoneId)) + { + std::unique_ptr< IEnumerator >pValueEnum(__pTimeZonesMap->GetValuesN(timeZoneId)); + + int i = 0; + String timeZoneName; + while(pValueEnum->MoveNext() == E_SUCCESS) + { + if (i++ == timeZoneStyle) + { + timeZoneName = *(static_cast (pValueEnum->GetCurrent())); + } + } + SetLastResult(E_SUCCESS); + return timeZoneName; + } + + const IcuUnicodeString** pIcuMap = null; + + int rowCount = 0; + int columnCount = 0; + + pIcuMap = __pIcuDateFormatSymbols->getZoneStrings(rowCount, columnCount); + if (pIcuMap && rowCount && columnCount) + { + for (int rc = 0; rc < rowCount; rc++) + { + if (timeZoneId == _LocaleData::GetOspString(pIcuMap[rc][0])) + { + SetLastResult(E_SUCCESS); + return _LocaleData::GetOspString(pIcuMap[rc][timeZoneStyle+1]); + } + } + } + SetLastResult(E_OBJ_NOT_FOUND); + return String(); +} + +result +_DateTimeSymbolsImpl::SetTimeZoneName(const Tizen::Base::String& timeZoneId, const Tizen::Base::String& concatenatedTimeZoneName) +{ + // checking if concatenatedTimeZoneName has 4 names + StringTokenizer tokenizer(concatenatedTimeZoneName, L"|"); + SysTryReturnResult(NID_LCL, (tokenizer.GetTokenCount() == MAX_TIMEZONE_NAME), + E_INVALID_ARG, "Invalid argument is used. %ls is invalid.", concatenatedTimeZoneName.GetPointer()); + + if (__pTimeZonesMap) + { + bool check = true; + __pTimeZonesMap->ContainsKey(timeZoneId, check); // checking if Time zone is already exist + + if (check) + { + __pTimeZonesMap->Remove(timeZoneId, true); + return AddTimeZoneName(timeZoneId, concatenatedTimeZoneName, true); + } + } + + String tzName(timeZoneId); + GetTimeZoneName(tzName, 0); + + result r = GetLastResult(); + + if(!IsFailed(r)) + { + return AddTimeZoneName(timeZoneId, concatenatedTimeZoneName, true); + } + return E_OBJ_NOT_FOUND; +} + + +// internal function +// This function makes a copy of input array list of strings +IList* +_DateTimeSymbolsImpl::CloneArrayListN(const IList* pList) const +{ + SysTryReturn(NID_LCL, pList, null, E_INVALID_ARG, "[%s] Invalid argument is used. pList is Null", GetErrorMessage(E_INVALID_ARG)); + + ClearLastResult(); // Setting last result to E_SUCCESS + std::unique_ptr< ArrayList, AllElementsDeleter > pClonedArrayList(new (std::nothrow) ArrayList()); + SysTryReturn(NID_LCL, pClonedArrayList, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = pClonedArrayList->Construct(pList->GetCount()); + SysTryReturn(NID_LCL, !IsFailed(r), null, r, "[%s] Unable to construct ArrayList.", GetErrorMessage(r)); + + for (int i = 0; i < pList->GetCount(); i++) + { + std::unique_ptr< String > pClonedString(new (std::nothrow) String(*(static_cast(pList->GetAt(i))))); + SysTryReturn(NID_LCL, pClonedString, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pClonedArrayList->Add(*pClonedString); + SysTryReturn(NID_LCL, !IsFailed(r), null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + pClonedString.release(); + } + + return pClonedArrayList.release(); +} + + + +IMultiMap* +_DateTimeSymbolsImpl::CloneMultiHashMapN(const Tizen::Base::Collection::IMultiMap* pMultiMap) const +{ + SysTryReturn(NID_LCL, pMultiMap, null, E_INVALID_ARG, "[%s] Invalid argument is used. pMultiMap is null.", GetErrorMessage(E_INVALID_ARG)); + + ClearLastResult(); + + std::unique_ptr< MultiHashMap, AllElementsDeleter > pClonedMultiHashMap(new (std::nothrow) MultiHashMap()); + SysTryReturn(NID_LCL, pClonedMultiHashMap, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = pClonedMultiHashMap->Construct(); + SysTryReturn(NID_LCL, !IsFailed(r), null, r, "[%s] Unable to construct hash map.", GetErrorMessage(r)); + + std::unique_ptr< IList > pKeys(pMultiMap->GetKeysN()); + r = GetLastResult(); + SysTryReturn(NID_LCL, pKeys != null, null, r, "[%s] Unable to get key list.", GetErrorMessage(r)); + + for (int i = 0; i < pKeys->GetCount(); i++) + { + String* pKey = static_cast< String* >(pKeys->GetAt(i)); + SysTryReturn(NID_LCL, pKey != null, null, r, "[%s] Propagated.", GetLastResult()); + + std::unique_ptr< IEnumerator > pValueEnum(pMultiMap->GetValuesN(*pKey)); + r = GetLastResult(); + SysTryReturn(NID_LCL, pValueEnum != null, null, r, "[%s] Unable to get values for key.", GetErrorMessage(r)); + + std::unique_ptr< String > pMapKey(new (std::nothrow)String(*pKey)); + SysTryReturn(NID_LCL, pMapKey != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + while (pValueEnum->MoveNext() == E_SUCCESS) + { + std::unique_ptr< String > pTimeZoneName(new (std::nothrow) String(*(static_cast (pValueEnum->GetCurrent())))); + if (pTimeZoneName) + { + r = pClonedMultiHashMap->Add(*pMapKey, *pTimeZoneName); + if (IsFailed(r)) + { + pClonedMultiHashMap->Remove(*pMapKey,true); + break; + } + + pTimeZoneName.release(); + } + else + { + pClonedMultiHashMap->Remove(*pMapKey,true); + break; + } + } + + pMapKey.release(); + } + + return pClonedMultiHashMap.release(); +} + +result +_DateTimeSymbolsImpl::SetList(Tizen::Base::Collection::ArrayList* pArrayList, int tokenCount, const Tizen::Base::String& stringWillBeTokenized) +{ + StringTokenizer tokenizer(stringWillBeTokenized, L"|"); + + SysTryReturnResult(NID_LCL, (tokenizer.GetTokenCount() == tokenCount), E_INVALID_ARG, + "Invalid argument is used. stringWillBeTokenized=%ls", stringWillBeTokenized.GetPointer()); + + std::unique_ptr< ArrayList, AllElementsDeleter > pTmpArrayList(pArrayList); + SysTryReturnResult(NID_LCL, pTmpArrayList, E_INVALID_ARG, "Invalid argument is used. pArrayList should not be null"); + + result r = pTmpArrayList->Construct(tokenCount); // Constructing list for tokenCount elements + if (!IsFailed(r)) + { + String token; + std::unique_ptr< String > pListStr(null); + while (tokenizer.GetNextToken(token) == E_SUCCESS) + { + pListStr.reset(new (std::nothrow) String(token)); + SysTryReturnResult(NID_LCL, pListStr, E_OUT_OF_MEMORY, "Memory allocation failed."); + + r = pTmpArrayList->Add(*pListStr); + SysTryReturnResult(NID_LCL, r == E_SUCCESS, r, "Failed to add value to array list."); + + pListStr.release(); + } + } + + pTmpArrayList.release(); + return r; +} + +void +_DateTimeSymbolsImpl::ReleaseList(IList* pList) +{ + if (pList) + { + pList->RemoveAll(true); // Remove elements and de-allocate memory used by them + delete pList; + } +} + +// This function release all the list after deleting their contents +void +_DateTimeSymbolsImpl::ReleaseAll(void) +{ + ReleaseList(__pErasList); // Deleting EraList after deleting its contents + ReleaseList(__pMonthsList); // Deleting MonthsList after deleting its contents + ReleaseList(__pShortMonthsList); // Deleting ShortMonthsList after deleting its contents + ReleaseList(__pWeekdaysList); // Deleting WeekdaysList after deleting its contents + ReleaseList(__pShortWeekdaysList); // Deleting ShortWeekdaysList after deleting its contents + ReleaseList(__pAmPmList); // Deleting AmPmList after deleting its contents + + if (__pTimeZonesMap) + { + __pTimeZonesMap->RemoveAll(true); // Removing and deleting contents of TimeZonesMap + delete __pTimeZonesMap; // Deleting TimeZonesMap + } +} + +_DateTimeSymbolsImpl* +_DateTimeSymbolsImpl::GetDateTimeSymbolsImpl(DateTimeSymbols* pDateTimeSymbols) +{ + return pDateTimeSymbols->__pDateTimeSymbolsImpl; +} + +}; +}; // Tizen::Locale + diff --git a/src/locales/FLcl_DateTimeSymbolsImpl.h b/src/locales/FLcl_DateTimeSymbolsImpl.h new file mode 100644 index 0000000..a4a2b9a --- /dev/null +++ b/src/locales/FLcl_DateTimeSymbolsImpl.h @@ -0,0 +1,122 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_DateTimeSymbolsImpl.h + * @brief This is the header file for the _DateTimeSymbolsImpl class. + * + * This header file contains the declarations of the _DateTimeSymbolsImpl class. + * + */ +#ifndef _FLCL_INTERNAL_DATE_TIME_SYMBOLS_IMPL_H_ +#define _FLCL_INTERNAL_DATE_TIME_SYMBOLS_IMPL_H_ + + +// Includes +#include + +#include +#include +#include +#include + + +namespace Tizen { namespace Locales +{ + +class DateTimeSymbols; + +enum DateFormatSymbolsAttributes +{ + DATE_FORMAT_SYM_ERA_LIST, + DATE_FORMAT_SYM_MONTH_LIST, + DATE_FORMAT_SYM_SHORT_MONTH_LIST, + DATE_FORMAT_SYM_WEEKDAY_LIST, + DATE_FORMAT_SYM_SHORT_WEEKDAY_LIST, + DATE_FORMAT_SYM_AM_PM_LIST, + DATE_FORMAT_SYM_TIMEZONE_MAP, + + DATE_FORMAT_SYM_INVALID +}; + +class _DateTimeSymbolsImpl + : public Tizen::Base::Object +{ + +public: +// Construct Operations + _DateTimeSymbolsImpl(void); + virtual ~_DateTimeSymbolsImpl(void); + + result Initialize(CalendarType calendarType = CALENDAR_GREGORIAN); + result Initialize(const Locale& locale, CalendarType calendarType = CALENDAR_GREGORIAN); + void Set(const _DateTimeSymbolsImpl* other); + + + result AddTimeZoneName(const Tizen::Base::String& timeZoneId, const Tizen::Base::String& concatenatedTimeZoneName, bool isOverwrite = false); + + const Tizen::Base::Collection::IList* GetEras(void) const; + result SetEras(const Tizen::Base::String& eras); + const Tizen::Base::Collection::IList* GetMonths(void) const; + result SetMonths(const Tizen::Base::String& months); + const Tizen::Base::Collection::IList* GetShortMonths(void) const; + result SetShortMonths(const Tizen::Base::String& shortMonths); + const Tizen::Base::Collection::IList* GetWeekdays(void) const; + result SetWeekdays(const Tizen::Base::String& weekdays); + const Tizen::Base::Collection::IList* GetShortWeekdays(void) const; + result SetShortWeekdays(const Tizen::Base::String& shortWeekdays); + const Tizen::Base::Collection::IList* GetAmPm(void) const; + result SetAmPm(const Tizen::Base::String& amPm); + + Tizen::Base::String GetTimeZoneName(Tizen::Base::String& timeZoneId, int timeZoneStyle = 0); + result SetTimeZoneName(const Tizen::Base::String& timeZoneId, const Tizen::Base::String& concatenatedTimeZoneName); + + static Tizen::Base::WcharBuffer* GetNonLocalizedDateTimePatternN(void); + Tizen::Base::Collection::IList* CloneArrayListN(const Tizen::Base::Collection::IList* pList) const; + Tizen::Base::Collection::IMultiMap* CloneMultiHashMapN(const Tizen::Base::Collection::IMultiMap* pMap) const; + result SetList(Tizen::Base::Collection::ArrayList* pArraylist, int tokenCount, const Tizen::Base::String& stringWillBeTokenized); + + void ReleaseList(Tizen::Base::Collection::IList* pList); + void ReleaseAll(); + + static _DateTimeSymbolsImpl* GetDateTimeSymbolsImpl(DateTimeSymbols* pDateTimeSymbols); + +private: + _DateTimeSymbolsImpl(const _DateTimeSymbolsImpl& dateTimeSymbolsImpl); + _DateTimeSymbolsImpl& operator =(const _DateTimeSymbolsImpl& dateTimeSymbolsImpl); + +// Attribute + Tizen::Base::Collection::IList* __pErasList; + Tizen::Base::Collection::IList* __pMonthsList; + Tizen::Base::Collection::IList* __pShortMonthsList; + Tizen::Base::Collection::IList* __pWeekdaysList; + Tizen::Base::Collection::IList* __pShortWeekdaysList; + Tizen::Base::Collection::IList* __pAmPmList; + Tizen::Base::Collection::IMultiMap* __pTimeZonesMap; + U_ICU_NAMESPACE::DateFormatSymbols* __pIcuDateFormatSymbols; + + CalendarType __CalendarType; + + friend class DateTimeSymbols; + friend class DateTimeFormatter; + friend class _LocaleData; +}; // _DateTimeSymbolsImpl + +}} // Tizen::Locales + +#endif //_FLCL_INTERNAL_DATE_TIME_SYMBOLS_IMPL_H_ + diff --git a/src/locales/FLcl_FieldPosition.cpp b/src/locales/FLcl_FieldPosition.cpp new file mode 100644 index 0000000..a4e7c17 --- /dev/null +++ b/src/locales/FLcl_FieldPosition.cpp @@ -0,0 +1,110 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_FieldPosition.cpp + * @brief This is the implementation file for _FieldPosition class. + */ + +// Includes +#include "FLcl_FieldPosition.h" + + +namespace Tizen { namespace Locales +{ + + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Public Method + +// Construct Operations + +_FieldPosition::_FieldPosition(int field) + : __field(field) + , __beginIndex(0) + , __endIndex(0) +{ +} + + +_FieldPosition::~_FieldPosition(void) +{ +} + + +_FieldPosition::_FieldPosition(const _FieldPosition& fieldPosition) + : __field(fieldPosition.__field) + , __beginIndex(fieldPosition.__beginIndex) + , __endIndex(fieldPosition.__endIndex) +{ +} + + +// Operator + +_FieldPosition& +_FieldPosition::operator =(const _FieldPosition& fieldPosition) +{ + if (&fieldPosition != this) + { + __field = fieldPosition.__field; + __beginIndex = fieldPosition.__beginIndex; + __endIndex = fieldPosition.__endIndex; + } + return *this; +} + + +// Operation + +int +_FieldPosition::GetField(void) const +{ + return __field; +} + + +int +_FieldPosition::GetBeginIndex(void) const +{ + return __beginIndex; +} + + +void +_FieldPosition::SetBeginIndex(int beginIndex) +{ + __beginIndex = beginIndex; +} + + +int +_FieldPosition::GetEndIndex(void) const +{ + return __endIndex; +} + + +void +_FieldPosition::SetEndIndex(int endIndex) +{ + __endIndex = endIndex; +} + + +}; +}; // Tizen::Locales diff --git a/src/locales/FLcl_FieldPosition.h b/src/locales/FLcl_FieldPosition.h new file mode 100644 index 0000000..4db45f2 --- /dev/null +++ b/src/locales/FLcl_FieldPosition.h @@ -0,0 +1,179 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_FieldPosition.h + * @brief This is the header file for the FieldPosition class. + */ + +#ifndef _FLCL_INTERNAL_FIELD_POSITION_H_ +#define _FLCL_INTERNAL_FIELD_POSITION_H_ + +// Includes +#include + + +namespace Tizen { namespace Locales +{ + + +/** + * @class _FieldPosition + * @brief This class is for the @e Field position management. + * + * @since 1.0 + * + * @final This class is not intended for extension. + * + * FieldPosition is a simple class used by Format and its subclasses to identify fields in formatted output. + * FieldPosition keeps track of the position of the field within the formatted output with two indices: + * the index of the first character of the field and the index of the last character of the field. + * + * The example code below should be updated. + * @code + + #include "FBase.h" + #include "FLocales.h" + + using Tizen::Base; + using Tizen::Locales; + + void + main(void) + { + result r; + double num = 12345678.9 + NumberFormat* pMyFormat; + pMyFormat = NumberFormat::CreateNumberFormat(); + if (IsFailed(GetLastResult())) goto CATCH; + FieldPosition fp(NumberFormat::ALIGNMENT_FIELD_INTEGER); + + String strBuf; + strBuf.Contruct(); + r = pMyFormat->Format(doubleNum, fp, strBuf); + if (IsFailed(r) ) goto CATCH; + return; + + CATCH: + // Error handling code + } + + @endcode + * + * + */ +class _FieldPosition + : public Tizen::Base::Object +{ +// Construct Operations +public: + /** + * Initializes an instance of FieldPosition with the specified field identifier. + * + * @param[in] field The field identifier + */ + _FieldPosition(int field); + + + /** + * Initializes an instance of FieldPosition with the values same as that of the specified instance. + * + * @param[in] fieldPosition An instance of FieldPosition + */ + _FieldPosition(const _FieldPosition& fieldPosition); + + + /** + * This is the destructor for this class. + */ + virtual ~_FieldPosition(void); + + +// Operations +public: + /** + * Assigns the values of the member variables of the specified instance of FieldPosition + * to the member variables of the current instance. + * + * @return An FieldPosition object with new values for the member variables + * @param[in] fieldPosition The other FieldPosition instance + */ + _FieldPosition& operator =(const _FieldPosition& fieldPosition); + + + /** + * Gets the field identifier. + * + * @return An integer value representing the field identifier + * + */ + int GetField(void) const; + + + /** + * Gets the index of the first character in the requested field. + * + * @return An integer value representing the begin index + * + * @see SetBeginIndex + * + */ + int GetBeginIndex(void) const; + + + /** + * Sets the begin index with the specified index value. + * + * @param[in] beginIndex The begin index of the field + * + * @see GetBeginIndex + * + */ + void SetBeginIndex(int beginIndex); + + + /** + * Gets the index of the character following the last character in the requested field. + * + * @return An integer value representing the end index + * + * @see SetEndIndex + * + */ + int GetEndIndex(void) const; + + + /** + * Sets the end index with the specified index value. + * + * @param[in] endIndex The end index of the field + * + * @see GetEndIndex + * + */ + void SetEndIndex(int endIndex); + + +private: + int __field; // field identifier of this field position + int __beginIndex; // begin index of this field position + int __endIndex; // end index of this field position +}; // FieldPosition + +}} // Tizen::Locales + +#endif //_FLCL_INTERNAL_FIELD_POSITION_H_ diff --git a/src/locales/FLcl_IcuCalendarImpl.cpp b/src/locales/FLcl_IcuCalendarImpl.cpp new file mode 100644 index 0000000..d8468e7 --- /dev/null +++ b/src/locales/FLcl_IcuCalendarImpl.cpp @@ -0,0 +1,977 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_IcuCalendarImpl.cpp + * @brief This is the implementation file for _IcuCalendarImpl class. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include "FLcl_LocaleData.h" +#include "FLcl_IcuCalendarImpl.h" +#include "FLcl_TimeZoneImpl.h" + + +typedef U_ICU_NAMESPACE::ErrorCode IcuErrorCode; +typedef U_ICU_NAMESPACE::Locale IcuLocale; +typedef U_ICU_NAMESPACE::Calendar IcuCalendar; +typedef U_ICU_NAMESPACE::GregorianCalendar IcuGregorianCalendar; +typedef U_ICU_NAMESPACE::TimeZone IcuTimeZone; +typedef U_ICU_NAMESPACE::SimpleTimeZone IcuSimpleTimeZone; + +using namespace Tizen::Base; + +static const long long _EPOCH_OFFSET_IN_MILLISEC = 62135596800000LL; +static const int _GREGORIAN_DEFAULT_YEAR = 1970; + +namespace Tizen { namespace Locales +{ + +_IcuCalendarImpl::_IcuCalendarImpl() + : __pIcuCalendar(null) + , __isEraFieldOverFlowed(false) +{ +} + +_IcuCalendarImpl::~_IcuCalendarImpl() +{ + delete __pIcuCalendar; + __pIcuCalendar = null; +} + +result +_IcuCalendarImpl::Construct(const TimeZone& timeZone, const Locale& locale, int calendarType) +{ + // Object is not allowed to construct twice + SysAssertf(__pIcuCalendar == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + IcuLocale icuLocale = GetIcuLocale(locale, calendarType); + result r = GetLastResult(); + if (!IsFailed(r)) + { + const _TimeZoneImpl* pTimeZoneImpl = _TimeZoneImpl::GetTimeZoneImpl(timeZone); + if (pTimeZoneImpl) + { + IcuErrorCode err; + __pIcuCalendar = IcuCalendar::createInstance(pTimeZoneImpl->GetIcuTimeZone().clone(), icuLocale, err); + r = GetOspException(err); + } + } + return r; +} + +_IcuCalendarImpl* +_IcuCalendarImpl::CloneN(void) +{ + std::unique_ptr< _IcuCalendarImpl > pIcuCalendar(new (std::nothrow) _IcuCalendarImpl); + SysTryReturn(NID_LCL, pIcuCalendar != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + if (__pIcuCalendar != null) + { + pIcuCalendar->__pIcuCalendar = __pIcuCalendar->clone(); + if (pIcuCalendar->__pIcuCalendar != null) + { + pIcuCalendar->__isEraFieldOverFlowed = __isEraFieldOverFlowed; + } + } + + return pIcuCalendar.release(); +} + +result +_IcuCalendarImpl::AddTimeField(int field, int amount) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + +// Uncomment these lines if OSP values are set to be in minutes +// if (field == TIME_FIELD_ZONE_OFFSET || field == TIME_FIELD_DST_OFFSET) +// { +// amount *= Calendar::ONE_MINUTE_IN_MILLISEC; +// } + + IcuErrorCode err; + __pIcuCalendar->add(static_cast< UCalendarDateFields >(GetIcuTimeField(field)), amount, err); + + return GetOspException(err); +} + +result +_IcuCalendarImpl::After(const _IcuCalendarImpl& otherInstance, bool& after) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_LCL, otherInstance.__pIcuCalendar, E_INVALID_ARG, "otherInstance is not constructed"); + + result r = ValidateFieldsForOverFlow(); + SysTryReturn(NID_LCL, !IsFailed(r), r, r, "[%s] Fields values are not valid", GetErrorMessage(r)); + + r = otherInstance.ValidateFieldsForOverFlow(); + SysTryReturn(NID_LCL, !IsFailed(r), r, r, "[%s] otherInstance's Fields values are not valid", GetErrorMessage(r)); + + IcuErrorCode err; + after = __pIcuCalendar->after(*(otherInstance.__pIcuCalendar), err); + return GetOspException(err); +} + +result +_IcuCalendarImpl::Before(const _IcuCalendarImpl& otherInstance, bool& before) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + SysTryReturnResult(NID_LCL, otherInstance.__pIcuCalendar, E_INVALID_ARG, "otherInstance is not constructed"); + + result r = ValidateFieldsForOverFlow(); + SysTryReturn(NID_LCL, !IsFailed(r), r, r, "[%s] Fields values are not valid", GetErrorMessage(r)); + + r = otherInstance.ValidateFieldsForOverFlow(); + SysTryReturn(NID_LCL, !IsFailed(r), r, r, "[%s] otherInstance's Fields values are not valid", GetErrorMessage(r)); + + IcuErrorCode err; + before = __pIcuCalendar->before(*(otherInstance.__pIcuCalendar), err); + return GetOspException(err); +} + +result +_IcuCalendarImpl::Clear(void) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + __pIcuCalendar->clear(); + return E_SUCCESS; +} + +result +_IcuCalendarImpl::Clear(int field) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + SysTryReturnResult(NID_LCL, icuTimeField != UCAL_FIELD_COUNT, + E_INVALID_ARG, "Invalid argument is used. Input field value is not supported"); + + // Hack to reset year field to 1970 while clearing TIME_FIELD_YEAR in GregorianCalendar + if (icuTimeField == UCAL_YEAR) + { + IcuGregorianCalendar* pCal = dynamic_cast< IcuGregorianCalendar* >(__pIcuCalendar); + if (pCal != null) + { + IcuErrorCode err; + pCal->set(UCAL_YEAR, _GREGORIAN_DEFAULT_YEAR); + pCal->getTime(err); + } + } + + __pIcuCalendar->clear(icuTimeField); + return E_SUCCESS; +} + +bool +_IcuCalendarImpl::Equals(const _IcuCalendarImpl& otherInstance) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + if (otherInstance.__pIcuCalendar != null) + { + IcuErrorCode err; + bool isEqual = __pIcuCalendar->equals(*(otherInstance.__pIcuCalendar), err); + if (err.isSuccess()) + { + return isEqual; + } + return false; + } + return false; +} + +int +_IcuCalendarImpl::GetActualMaxTimeField(int field) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + if (icuTimeField != UCAL_FIELD_COUNT) + { + IcuErrorCode err; + int value = __pIcuCalendar->getActualMaximum(icuTimeField, err); + if (err.isSuccess()) + { + SetLastResult(E_SUCCESS); + return ConvertToOspTimeFieldValue(field, value); + } + } + + SetLastResult(E_INVALID_ARG); + return -1; +} + +int +_IcuCalendarImpl::GetActualMinTimeField(int field) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + if (icuTimeField != UCAL_FIELD_COUNT) + { + IcuErrorCode err; + int value = __pIcuCalendar->getActualMinimum(icuTimeField, err); + if (err.isSuccess()) + { + SetLastResult(E_SUCCESS); + return ConvertToOspTimeFieldValue(field, value); + } + SetLastResult(E_SYSTEM); + } + + SetLastResult(E_INVALID_ARG); + return -1; +} + +int +_IcuCalendarImpl::GetFirstDayOfWeek(void) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + IcuErrorCode err; + int value = __pIcuCalendar->getFirstDayOfWeek(err); // ICU DAY of week and OSP day of week are similar + if (err.isSuccess()) + { + return value; + } + + return -1; +} + +int +_IcuCalendarImpl::GetGreatestMinTimeField(int field) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + if (icuTimeField != UCAL_FIELD_COUNT) + { + SetLastResult(E_SUCCESS); + int value = __pIcuCalendar->getGreatestMinimum(icuTimeField); + return ConvertToOspTimeFieldValue(field, value); + } + + SetLastResult(E_INVALID_ARG); + return -1; +} + +int +_IcuCalendarImpl::GetHashCode(void) const +{ + return (int) E_UNSUPPORTED_OPERATION; +} + +int +_IcuCalendarImpl::GetLeastMaxTimeField(int field) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + if (icuTimeField != UCAL_FIELD_COUNT) + { + SetLastResult(E_SUCCESS); + int value = __pIcuCalendar->getLeastMaximum(icuTimeField); + return ConvertToOspTimeFieldValue(field, value); + } + + SetLastResult(E_INVALID_ARG); + return -1; +} + +int +_IcuCalendarImpl::GetMaxTimeField(int field) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + if (icuTimeField != UCAL_FIELD_COUNT) + { + SetLastResult(E_SUCCESS); + int value = __pIcuCalendar->getMaximum(icuTimeField); + return ConvertToOspTimeFieldValue(field, value); + } + + SetLastResult(E_INVALID_ARG); + return -1; +} + +int +_IcuCalendarImpl::GetMinDaysInFirstWeek(void) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pIcuCalendar->getMinimalDaysInFirstWeek(); +} + +int +_IcuCalendarImpl::GetMinTimeField(int field) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + if (icuTimeField != UCAL_FIELD_COUNT) + { + SetLastResult(E_SUCCESS); + int value = __pIcuCalendar->getMinimum(icuTimeField); + return ConvertToOspTimeFieldValue(field, value); + } + + SetLastResult(E_INVALID_ARG); + return -1; +} + +int +_IcuCalendarImpl::GetTimeField(int field) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + if (icuTimeField != UCAL_FIELD_COUNT) + { + IcuErrorCode err; + int value = __pIcuCalendar->get(icuTimeField, err); + if (err.isSuccess()) + { + return ConvertToOspTimeFieldValue(field, value); + } + SetLastResult(GetOspException(err)); + } + + return -1; +} + +result +_IcuCalendarImpl::GetTimeInMillisec(long long& millisec) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + result r = ValidateFieldsForOverFlow(); + SysTryReturn(NID_LCL, !IsFailed(r), r, r, "[%s]Instance is not constructed", GetErrorMessage(r)); + + IcuErrorCode err; + millisec = __pIcuCalendar->getTime(err); + if (err.isSuccess()) + { + millisec += _EPOCH_OFFSET_IN_MILLISEC; + return E_SUCCESS; + } + return GetOspException(err); +} + +result +_IcuCalendarImpl::IsInDst(bool& isInDst) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + result r = ValidateFieldsForOverFlow(); + SysTryReturn(NID_LCL, !IsFailed(r), r, r, "[%s] Fields values are not valid", GetErrorMessage(r)); + + IcuErrorCode err; + isInDst = __pIcuCalendar->inDaylightTime(err); + return GetOspException(err); +} + +bool +_IcuCalendarImpl::IsLeapYear(int year) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + IcuGregorianCalendar* pCal = dynamic_cast< IcuGregorianCalendar* >(__pIcuCalendar); + if (pCal != null) + { + if (year <= 0) + { + year = 1 - year; // to adjust year as year 0 to 1 BC, -1 to 2 BC and so on + } + return pCal->isLeapYear(year); + } + return false; +} + +bool +_IcuCalendarImpl::IsLenient(void) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + return __pIcuCalendar->isLenient(); +} + +bool +_IcuCalendarImpl::IsSet(int field) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + UCalendarDateFields icuTimeField = static_cast< UCalendarDateFields >(GetIcuTimeField(field)); + if (icuTimeField != UCAL_FIELD_COUNT) + { + return __pIcuCalendar->isSet(icuTimeField); + } + + return false; +} + +result +_IcuCalendarImpl::Roll(int field, int amount) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + result r = ValidateFieldsForOverFlow(); + if (!IsFailed(r)) + { + // Non Roll-able fields + if (field == TIME_FIELD_ZONE_OFFSET || field == TIME_FIELD_DST_OFFSET) + { + return E_INVALID_ARG; + } + + field = GetIcuTimeField(field); + if (field != UCAL_FIELD_COUNT) + { + IcuErrorCode err; + __pIcuCalendar->roll(static_cast< UCalendarDateFields >(field), amount, err); + return GetOspException(err); + } + return E_INVALID_ARG; + } + return r; +} + +result +_IcuCalendarImpl::SetFirstDayOfWeek(int dayOfWeek) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + if (dayOfWeek >= UCAL_SUNDAY && dayOfWeek <= UCAL_SATURDAY) + { + __pIcuCalendar->setFirstDayOfWeek(static_cast< UCalendarDaysOfWeek >(dayOfWeek)); + return E_SUCCESS; + } + return E_INVALID_ARG; +} + + +result +_IcuCalendarImpl::SetLenient(bool lenient) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + __pIcuCalendar->setLenient(lenient); + return E_SUCCESS; +} + +result +_IcuCalendarImpl::SetMinDaysInFirstWeek(short value) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + __pIcuCalendar->setMinimalDaysInFirstWeek(static_cast< byte >(value)); + return E_SUCCESS; +} + +result +_IcuCalendarImpl::SetTime(int year, int month, int day, int hour, int minute, int second) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + __pIcuCalendar->set(year, month - 1, day, hour, minute, second); + return E_SUCCESS; +} + +result +_IcuCalendarImpl::SetTimeField(int field, int value) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + field = GetIcuTimeField(field); + if (field != UCAL_FIELD_COUNT) + { + CheckInputFieldValueForOverFlow(field, value); + + __pIcuCalendar->set(static_cast< UCalendarDateFields >(field), ConvertFromOspTimeFieldValue(field, value)); + return E_SUCCESS; + } + return E_INVALID_ARG; +} + +result +_IcuCalendarImpl::SetTimeInMillisec(long long millisec) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + millisec -= _EPOCH_OFFSET_IN_MILLISEC; + + IcuErrorCode err; + __pIcuCalendar->setTime(static_cast< UDate >(millisec), err); + return GetOspException(err); +} + +result +_IcuCalendarImpl::SetTimeZone(const TimeZone& timeZone) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + + const _TimeZoneImpl* pTimeZoneImpl = _TimeZoneImpl::GetTimeZoneImpl(timeZone); + if (pTimeZoneImpl) + { + __pIcuCalendar->adoptTimeZone(pTimeZoneImpl->GetIcuTimeZone().clone()); + } + return E_SUCCESS; +} + +long long +_IcuCalendarImpl::GetGregorianChange(void) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + IcuGregorianCalendar* pCal = dynamic_cast< IcuGregorianCalendar* >(__pIcuCalendar); + if (pCal != null) + { + return pCal->getGregorianChange() + _EPOCH_OFFSET_IN_MILLISEC; + } + return -1; +} + +result +_IcuCalendarImpl::SetGregorianChange(long long change) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + IcuGregorianCalendar* pCal = dynamic_cast< IcuGregorianCalendar* >(__pIcuCalendar); + if (pCal) + { + change -= _EPOCH_OFFSET_IN_MILLISEC; + IcuErrorCode err; + pCal->setGregorianChange(change, err); + return GetOspException(err); + } + return E_UNSUPPORTED_OPERATION; +} + +int +_IcuCalendarImpl::GetJulianDay(void) const +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + IcuGregorianCalendar* pCal = dynamic_cast< IcuGregorianCalendar* >(__pIcuCalendar); + if (pCal) + { + IcuErrorCode err; + return pCal->get(UCAL_JULIAN_DAY, err); + } + return -1; +} + +result +_IcuCalendarImpl::SetJulianDay(int julianDay) +{ + SysAssertf(__pIcuCalendar != null, "Not yet constructed! Construct() should be called before use."); + IcuGregorianCalendar* pCal = dynamic_cast< IcuGregorianCalendar* >(__pIcuCalendar); + if (pCal) + { + pCal->set(UCAL_JULIAN_DAY, julianDay); + return E_SUCCESS; + } + return E_UNSUPPORTED_OPERATION; +} + +result +_IcuCalendarImpl::GetOspException(IcuErrorCode icuException) const +{ + if (U_SUCCESS(icuException)) + { + return E_SUCCESS; + } + + //SysTryLog(NID_LCL, false, "ICU Exception: %s", icuException.errorName()); + + result r = E_SUCCESS; + switch (icuException) + { + case U_ILLEGAL_ARGUMENT_ERROR: + { + if (IsLenient()) + { + r = E_OUT_OF_RANGE; + break; + } + r = E_INVALID_STATE; + break; + } + case U_MEMORY_ALLOCATION_ERROR: + { + r = E_OUT_OF_MEMORY; + break; + } + default: + { + r = E_SYSTEM; + break; + } + } + return r; +} + +int +_IcuCalendarImpl::GetIcuTimeField(int field) const +{ + int res = UCAL_FIELD_COUNT; + switch (field) + { + case TIME_FIELD_ERA: + { + res = UCAL_ERA; + break; + } + + case TIME_FIELD_YEAR: + { + res = UCAL_YEAR; + break; + } + + case TIME_FIELD_MONTH: + { + res = UCAL_MONTH; + break; + } + + case TIME_FIELD_WEEK_OF_YEAR: + { + res = UCAL_WEEK_OF_YEAR; + break; + } + + case TIME_FIELD_WEEK_OF_MONTH: + { + res = UCAL_WEEK_OF_MONTH; + break; + } + + case TIME_FIELD_DAY_OF_MONTH: + { + res = UCAL_DAY_OF_MONTH; + break; + } + + case TIME_FIELD_DAY_OF_YEAR: + { + res = UCAL_DAY_OF_YEAR; + break; + } + + case TIME_FIELD_DAY_OF_WEEK: + { + res = UCAL_DAY_OF_WEEK; + break; + } + + case TIME_FIELD_DAY_OF_WEEK_IN_MONTH: + { + res = UCAL_DAY_OF_WEEK_IN_MONTH; + break; + } + + case TIME_FIELD_AM_PM: + { + res = UCAL_AM_PM; + break; + } + + case TIME_FIELD_HOUR: + { + res = UCAL_HOUR; + break; + } + + case TIME_FIELD_HOUR_OF_DAY: + { + res = UCAL_HOUR_OF_DAY; + break; + } + + case TIME_FIELD_MINUTE: + { + res = UCAL_MINUTE; + break; + } + + case TIME_FIELD_SECOND: + { + res = UCAL_SECOND; + break; + } + + case TIME_FIELD_MILLISECOND: + { + res = UCAL_MILLISECOND; + break; + } + + case TIME_FIELD_ZONE_OFFSET: + { + res = UCAL_ZONE_OFFSET; + break; + } + + case TIME_FIELD_DST_OFFSET: + { + res = UCAL_DST_OFFSET; + break; + } + + default: + { + res = UCAL_FIELD_COUNT; + break; + } + } + return res; +} + +int +_IcuCalendarImpl::ConvertFromOspTimeFieldValue(int field, int value) const +{ + int res = value; + switch (field) + { + case TIME_FIELD_MONTH: + res -= 1; + break; + + case TIME_FIELD_ZONE_OFFSET: // fall through + case TIME_FIELD_DST_OFFSET: // fall through +// Uncomment these lines if OSP values are set to be in minutes +// res *= Calendar::ONE_MINUTE_IN_MILLISEC; +// break; + + case TIME_FIELD_ERA: // fall through + case TIME_FIELD_YEAR: // fall through + case TIME_FIELD_WEEK_OF_YEAR: // fall through + case TIME_FIELD_WEEK_OF_MONTH: // fall through + case TIME_FIELD_DAY_OF_MONTH: // fall through + case TIME_FIELD_DAY_OF_YEAR: // fall through + case TIME_FIELD_DAY_OF_WEEK: // fall through + case TIME_FIELD_DAY_OF_WEEK_IN_MONTH: // fall through + case TIME_FIELD_AM_PM: // fall through + case TIME_FIELD_HOUR: // fall through + case TIME_FIELD_HOUR_OF_DAY: // fall through + case TIME_FIELD_MINUTE: // fall through + case TIME_FIELD_SECOND: // fall through + case TIME_FIELD_MILLISECOND: // fall through + default: + break; + } + + return res; +} + +int +_IcuCalendarImpl::ConvertToOspTimeFieldValue(int field, int value) const +{ + int res = value; + switch (field) + { + case TIME_FIELD_MONTH: + res += 1; + break; + + case TIME_FIELD_ZONE_OFFSET: // fall through + case TIME_FIELD_DST_OFFSET: // fall through +// Uncomment these lines if OSP values are set to be in minutes +// res /= Calendar::ONE_MINUTE_IN_MILLISEC; +// break; + + case TIME_FIELD_ERA: // fall through + case TIME_FIELD_YEAR: // fall through + case TIME_FIELD_WEEK_OF_YEAR: // fall through + case TIME_FIELD_WEEK_OF_MONTH: // fall through + case TIME_FIELD_DAY_OF_MONTH: // fall through + case TIME_FIELD_DAY_OF_YEAR: // fall through + case TIME_FIELD_DAY_OF_WEEK: // fall through + case TIME_FIELD_DAY_OF_WEEK_IN_MONTH: // fall through + case TIME_FIELD_AM_PM: // fall through + case TIME_FIELD_HOUR: // fall through + case TIME_FIELD_HOUR_OF_DAY: // fall through + case TIME_FIELD_MINUTE: // fall through + case TIME_FIELD_SECOND: // fall through + case TIME_FIELD_MILLISECOND: // fall through + default: + break; + } + + return res; +} + +IcuLocale +_IcuCalendarImpl::GetIcuLocale(const Locale& ospLocale, int type) const +{ + ClearLastResult(); + String localeStr = ospLocale.GetLocaleCodeString(); + if (!localeStr.IsEmpty()) + { + switch (type) + { + case CALENDAR_GREGORIAN: + localeStr += "@calendar=gregorian"; + break; + + case CALENDAR_BUDDHIST: + localeStr += "@calendar=buddhist"; + break; + + case CALENDAR_CHINESE: + localeStr += "@calendar=chinese"; + break; + + case CALENDAR_COPTIC: + localeStr += "@calendar=coptic"; + break; + + case CALENDAR_ETHIOPIC_AMETE_ALEM: + localeStr += "@calendar=ethiopic-amete-alem"; + break; + + case CALENDAR_ETHIOPIC: + localeStr += "@calendar=ethiopic"; + break; + + case CALENDAR_HEBREW: + localeStr += "@calendar=hebrew"; + break; + + case CALENDAR_INDIAN: + localeStr += "@calendar=indian"; + break; + + case CALENDAR_ISLAMIC: + localeStr += "@calendar=islamic"; + break; + + case CALENDAR_ISLAMIC_CIVIL: + localeStr += "@calendar=islamic-civil"; + break; + + case CALENDAR_JAPANESE: + localeStr += "@calendar=japanese"; + break; + + case CALENDAR_PERSIAN: + localeStr += "@calendar=persian"; + break; + + case CALENDAR_ROC: + localeStr += "@calendar=roc"; + break; + + case CALENDAR_TAIWAN: + localeStr += "@calendar=taiwan"; + break; + + case CALENDAR_ISO8601: + localeStr += "@calendar=iso8601"; + break; + + default: + localeStr += "@calendar=gregorian"; + break; + } + } + + std::unique_ptr< char [] > pLclStr(_StringConverter::CopyToCharArrayN(localeStr)); + IcuLocale icuLocale = IcuLocale(pLclStr.get()); + if (icuLocale.isBogus()) + { + SetLastResult(E_SYSTEM); + } + + return icuLocale; +} + +SimpleTimeZone* +_IcuCalendarImpl::GetIcuTimeZone(const TimeZone& ospTimeZone) const +{ + String timeZoneId = ospTimeZone.GetId(); + std::unique_ptr< char [] > pTimezoneStr(_StringConverter::CopyToCharArrayN(timeZoneId)); + if (pTimezoneStr != null) + { + int rawOffset = ospTimeZone.GetRawOffset() * 60 * 1000; + std::unique_ptr< IcuSimpleTimeZone > pIcuTimeZone(new IcuSimpleTimeZone(rawOffset, pTimezoneStr.get())); + if (pIcuTimeZone != null) + { + _LocaleData lclData; + result r = lclData.SetStartTimeRule(*pIcuTimeZone, ospTimeZone.GetDstStartingRule()); + if (!IsFailed(r)) + { + r = lclData.SetEndTimeRule(*pIcuTimeZone, ospTimeZone.GetDstEndingRule()); +// if (!IsFailed(r)) +// { +// ClearLastResult(); +// return pIcuTimeZone; +// } + } + ClearLastResult(); + return pIcuTimeZone.release(); + } + } + + SetLastResult(E_SYSTEM); + return null; +} + +void +_IcuCalendarImpl::CheckInputFieldValueForOverFlow(int field, int value) +{ + if (field == TIME_FIELD_ERA) + { + __isEraFieldOverFlowed = (value < GetMinTimeField(TIME_FIELD_ERA)) || (value > GetMaxTimeField(TIME_FIELD_ERA)); + } +} + +result +_IcuCalendarImpl::ValidateFieldsForOverFlow(void) const +{ + if (__isEraFieldOverFlowed) + { + if (IsLenient()) + { + return E_OUT_OF_RANGE; + } + return E_INVALID_STATE; + } + return E_SUCCESS; +} + +IcuCalendar* +_IcuCalendarImpl::GetIcuCalendarCloneN(void) const +{ + if (__pIcuCalendar) + { + return __pIcuCalendar->clone(); + } + return null; +} + +}; +}; // Tizen::Locales diff --git a/src/locales/FLcl_IcuCalendarImpl.h b/src/locales/FLcl_IcuCalendarImpl.h new file mode 100644 index 0000000..fc0b134 --- /dev/null +++ b/src/locales/FLcl_IcuCalendarImpl.h @@ -0,0 +1,134 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_IcuCalendarImpl.h + * @brief This is the header file for the _IcuCalendarImpl class. + * + * This header file contains the declarations of the _IcuCalendarImpl class. + * + */ + +#ifndef _FLCL_INTERNAL_ICU_CALENDAR_IMPL_H_ +#define _FLCL_INTERNAL_ICU_CALENDAR_IMPL_H_ + +#include + +namespace U_ICU_NAMESPACE +{ +class ErrorCode; +class Locale; +class SimpleTimeZone; +class Calendar; +} + +namespace Tizen { namespace Locales +{ + +class _IcuCalendarImpl +{ +public: + _IcuCalendarImpl(); + virtual ~_IcuCalendarImpl(); + + virtual result Construct(const TimeZone& timeZone, const Locale& locale, int calendarType); + virtual _IcuCalendarImpl* CloneN(void); + + // Date & Time Clear/ Get/ Set methods + + virtual result Clear(void); + virtual result Clear(int field); + + virtual result AddTimeField(int field, int amount); // Affect all fields + virtual result Roll(int field, int amount); // Does not affect higher fields + virtual result SetTime(int year, int month, int day, int hour = 0, int minute = 0, int second = 0); + + virtual int GetTimeField(int field) const; + virtual result SetTimeField(int field, int value); + + virtual result GetTimeInMillisec(long long& millisec) const; + virtual result SetTimeInMillisec(long long millisec); + + virtual int GetMaxTimeField(int field) const; + virtual int GetMinTimeField(int field) const; + + // Comparison methods + virtual result After(const _IcuCalendarImpl& otherInstance, bool& after); + virtual result Before(const _IcuCalendarImpl& otherInstance, bool& before); + virtual bool Equals(const _IcuCalendarImpl& otherInstance); + + // Methods to get properties + virtual int GetHashCode(void) const; + + virtual int GetActualMinTimeField(int field) const; + virtual int GetGreatestMinTimeField(int field) const; + virtual int GetLeastMaxTimeField(int field) const; + virtual int GetActualMaxTimeField(int field) const; + + virtual bool IsSet(int field) const; + virtual result IsInDst(bool& isInDst) const; + virtual bool IsLeapYear(int year) const; // defined for GregorianCalendar + + virtual bool IsLenient(void) const; + virtual result SetLenient(bool lenient); + + virtual result SetFirstDayOfWeek(int dayOfWeek); + virtual int GetFirstDayOfWeek(void) const; + + virtual int GetMinDaysInFirstWeek(void) const; + virtual result SetMinDaysInFirstWeek(short value); + + virtual result SetTimeZone(const TimeZone& timeZone); +// virtual TimeZone GetTimeZone(void) const; + + // For Gregorian Calendar + virtual long long GetGregorianChange(void) const; + virtual result SetGregorianChange(long long change); + + virtual int GetJulianDay(void) const; + virtual result SetJulianDay(int julianDay); + + U_ICU_NAMESPACE::Calendar* GetIcuCalendarCloneN(void) const; + +private: + _IcuCalendarImpl(const _IcuCalendarImpl& orig); + _IcuCalendarImpl& operator =(const _IcuCalendarImpl& orig); + + result GetOspException(U_ICU_NAMESPACE::ErrorCode icuException) const; + + int GetIcuTimeField(int field) const; + int ConvertFromOspTimeFieldValue(int field, int value) const; + int ConvertToOspTimeFieldValue(int field, int value) const; + +// UCalendarDaysOfWeek GetIcuDayOfWeek(DayOfWeek dayOfWeek) const; +// DayOfWeek GetOspDayOfWeek(UCalendarDaysOfWeek dayOfWeek) const; + + U_ICU_NAMESPACE::Locale GetIcuLocale(const Locale& ospLocale, int type) const; + U_ICU_NAMESPACE::SimpleTimeZone* GetIcuTimeZone(const TimeZone& ospTimeZone) const; + + void CheckInputFieldValueForOverFlow(int field, int value); + result ValidateFieldsForOverFlow(void) const; + +private: + class U_ICU_NAMESPACE::Calendar* __pIcuCalendar; + + bool __isEraFieldOverFlowed; +}; + +}} // Tizen::Locales + +#endif // _FLCL_INTERNAL_ICU_CALENDAR_IMPL_H_ diff --git a/src/locales/FLcl_LocaleData.cpp b/src/locales/FLcl_LocaleData.cpp new file mode 100644 index 0000000..20c8187 --- /dev/null +++ b/src/locales/FLcl_LocaleData.cpp @@ -0,0 +1,1358 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclLocaleData.cpp + * @brief This is the implementation file for _LocaleData class. + */ + +// Includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FBase_StringConverter.h" +#include "FLcl_DateTimeSymbolsImpl.h" +#include "FLcl_CalendarImpl.h" +#include "FLcl_IcuCalendarImpl.h" +#include "FLcl_LocaleData.h" + + +// Other defines +#define LOCALE_DATA_NUM_OF_MILLISEC_IN_HOUR 3600000LL // number of mili second in a hour +#define LOCALE_DATA_NUM_OF_MILLISEC_IN_MINUTE 60000LL // number of mili second in a minute + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +namespace Tizen { namespace Locales +{ + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Public Method + +// this function is to convert ICU FieldPosition from OSP _FieldPosition +IcuFieldPosition +_LocaleData::GetIcuFieldPosition(_FieldPosition pos) +{ + IcuFieldPosition icuPos(pos.GetField()); // Create IcuFieldPosition with field value in pos + icuPos.setBeginIndex(pos.GetBeginIndex()); // Set Beginning index + icuPos.setEndIndex(pos.GetEndIndex()); // Set End index + return icuPos; +} + +U_ICU_NAMESPACE::UnicodeString +_LocaleData::GetIcuString(const String& ospStr) +{ + IcuUnicodeString icuStr; + + if (!ospStr.IsEmpty()) // if ospStr is not empty + { + ByteBuffer* pBuff = null; + pBuff = StringUtil::StringToUtf8N(ospStr); // Convert unicode value to UTF8 + if (pBuff) + { + icuStr = IcuUnicodeString((const char*) pBuff->GetPointer()); // Create ICU string using UTF8 array + icuStr.setCharAt(0, icuStr.charAt(0)); // This is to handle ICU copy on write design + delete pBuff; // delete temporary buffer + } + } + + return icuStr; +} +// This function convert ICU string to OSP string +String +_LocaleData::GetOspString(const IcuUnicodeString& icuStr) +{ + int len = icuStr.length(); // get length + if (len) // if icuStr is not empty + { + char out[len * 3 + 1]; // Create buffer of thrice the icuStr length + out[icuStr.extract(0, len, out)] = 0; // icuStr.extract() converts Unicode to UTF8 + return String(out); + } + return String(""); +} + +// This convert OSP string to ICU strings +void +_LocaleData::GetIcuString(const String& ospStr, IcuUnicodeString& icuStr) +{ + if (!ospStr.IsEmpty()) // if ospStr is not empty + { + ByteBuffer* pBuff = null; + pBuff = StringUtil::StringToUtf8N(ospStr); // Convert unicode value to UTF8 + if (pBuff) + { + icuStr = IcuUnicodeString((const char*) pBuff->GetPointer()); // Create ICU string using UTF8 array + icuStr.setCharAt(0, icuStr.charAt(0)); // This is to handle ICU copy on write design + delete pBuff; // delete temporary buffer + } + } + +// return icuStr; +} + +// This function return OSP array list of OSP string from ICU string list +ArrayList* +_LocaleData::ConvertIcuStringArrayToOspArrayN(const IcuUnicodeString* pIcuStrList, int count) +{ + result r = E_SUCCESS; + ArrayList* pTempArrayList = null; + if (pIcuStrList && count > 0) // validating inputs + { + pTempArrayList = new (std::nothrow) ArrayList(); + if (pTempArrayList) // If allocation is successful + { + r = pTempArrayList->Construct(count); + if (!IsFailed(r)) // If ArrayList::Construct() is successful + { + for (int i = 0; i < count; i++) + { + String* pString = new (std::nothrow) String(); + if (pString != null) + { + *pString = _LocaleData::GetOspString(pIcuStrList[i]); // Get OSP string from ICU string + + if (!pString->IsEmpty()) + { + pTempArrayList->Add(*pString); // Add OSP string to arraylist if it is not empty + } + else + { + delete pString; + } + } + } + } + } + } + + SetLastResult(r); // Setting last result value + return pTempArrayList; // Return array list +} + +// this function convert OSP string array list to ICU string array list +IcuUnicodeString* +_LocaleData::ConvertOspArrayToIcuStringArrayN(const Tizen::Base::Collection::IList* pIcuStrList, int& count) +{ + count = 0; // Setting count [Out param] to 0 + SysTryReturn(NID_LCL, pIcuStrList, null, E_INVALID_ARG, "[%s] Invalid argument is used. pIcuStrList is null.", GetErrorMessage(E_INVALID_ARG)); + + count = pIcuStrList->GetCount(); + if (count > 0) // if pIcuStrList is not empty + { + IcuUnicodeString* pIcuStrArray = new IcuUnicodeString[count]; + if (pIcuStrArray) // if allocation is successful + { + IEnumerator* pEnum = pIcuStrList->GetEnumeratorN(); + if (pEnum) // if pEnum is non null + { + int i = 0; + String* pObj = null; + while (pEnum->MoveNext() == E_SUCCESS) // if enum has more value + { + pObj = static_cast< String* >(pEnum->GetCurrent()); // Get object and cast it to String + if (pObj) // if String is non null + { + GetIcuString(*pObj, pIcuStrArray[i]); // Convert it to ICU string and set to array + i++; + } + } + + delete pEnum; // Delete enumerator + return pIcuStrArray; // return ICU Array + } + delete[] pIcuStrArray; + } + } + + return null; // return null in case of failure +} + +// This function convert ICU locale to OSP Locale +Locale +_LocaleData::GetOspLocale(const IcuLocale& icuLocale) +{ + SysTryReturn(NID_LCL, !icuLocale.isBogus(), Locale(LANGUAGE_INVALID, COUNTRY_INVALID, null), E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.",GetErrorMessage(E_SYSTEM)); + + LanguageCode langCode = LANGUAGE_INVALID; + CountryCode countryCode = COUNTRY_INVALID; + const char* pIcuStr = icuLocale.getLanguage(); + langCode = Locale::TwoLetterLanguageCodeStringToLanguageCode(pIcuStr); + + if (langCode == LANGUAGE_INVALID) + { + langCode = Tizen::Locales::Locale::StringToLanguageCode(pIcuStr); + SysTryReturn(NID_LCL, langCode != LANGUAGE_INVALID, Locale(LANGUAGE_INVALID, COUNTRY_INVALID, null), E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.",GetErrorMessage(E_SYSTEM)); + } + + pIcuStr = icuLocale.getCountry(); + countryCode = Tizen::Locales::Locale::StringToCountryCode(pIcuStr); + + SysTryReturn(NID_LCL, countryCode != COUNTRY_INVALID, Locale(LANGUAGE_INVALID, COUNTRY_INVALID, null), E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.",GetErrorMessage(E_SYSTEM)); + + String variantCodeString = icuLocale.getVariant(); + SetLastResult(E_SUCCESS); + + if (variantCodeString.IsEmpty()) + { + return Locale(langCode, countryCode, null); + } + + return Locale(langCode, countryCode, &variantCodeString); +} + +IcuLocale +_LocaleData::GetIcuLocale(const Locale& ospLocale) +{ + ClearLastResult(); + String language = ospLocale.GetLanguageCodeString(); + String country = ospLocale.GetCountryCodeString(); + String variant = ospLocale.GetVariantCodeString(); + + const char* pLangStr = _StringConverter::CopyToCharArrayN(language); + const char* pCountryStr = _StringConverter::CopyToCharArrayN(country); + const char* pVariantStr = null; + + if (!variant.IsEmpty()) + { + pVariantStr = _StringConverter::CopyToCharArrayN(variant); + } + + IcuLocale icuLocale = IcuLocale(pLangStr, pCountryStr, pVariantStr); + + delete[] pLangStr; + delete[] pCountryStr; + delete[] pVariantStr; + + if (icuLocale.isBogus()) + { + SetLastResult(E_SYSTEM); + } + + return icuLocale; +} + +Locale +_LocaleData::GetOspSystemLocale(void) +{ + char* pRegion = null; + int ret = runtime_info_get_value_string(RUNTIME_INFO_KEY_REGION, &pRegion); + if (ret == RUNTIME_INFO_ERROR_NONE) + { + IcuLocale icuLcl(pRegion); + free(pRegion); + SetLastResult(E_SUCCESS); + return _LocaleData::GetOspLocale(icuLcl); + } + + SetLastResult(E_SYSTEM); + return Locale(LANGUAGE_INVALID, COUNTRY_INVALID, null); +} + +const IcuLocale& +_LocaleData::GetIcuLocale(void) +{ + return __icuLocale; +} + +bool +_LocaleData::IsLocaleSupported(void) +{ + return !__icuLocale.isBogus(); +} + +result +_LocaleData::SetLocale(const Locale& ospLocale) +{ + if (ospLocale.GetCountryCode() != COUNTRY_INVALID) + { + if (ospLocale.GetLanguageCode() != LANGUAGE_INVALID) + { + __icuLocale = GetIcuLocale(ospLocale); + return E_SUCCESS; + } + } + + __icuLocale.setToBogus(); + return (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) ? E_UNSUPPORTED_OPERATION : E_INVALID_ARG; +} + +result +_LocaleData::GetNumberSymbols(const Locale& locale, String symbols[]) +{ + UErrorCode status = U_ZERO_ERROR; + ; + SetLocale(locale); + + SysTryReturnResult(NID_LCL, IsLocaleSupported(), E_SYSTEM, "A System error has been occurred. Locale is not supported"); + + IcuDecimalFormatSymbols sym(__icuLocale, status); + SysTryReturnResult(NID_LCL, U_SUCCESS(status), E_SYSTEM, "A System error has been occurred. Unable to get ICU Decimal Format Symbols"); + + symbols[NUMBER_SYMBOL_DECIMAL_SEPARATOR] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kDecimalSeparatorSymbol)); + symbols[NUMBER_SYMBOL_GROUPING_SEPARATOR] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kGroupingSeparatorSymbol)); + symbols[NUMBER_SYMBOL_PATTERN_SEPARATOR] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kPatternSeparatorSymbol)); + symbols[NUMBER_SYMBOL_PERCENT] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kPercentSymbol)); + symbols[NUMBER_SYMBOL_ZERO_DIGIT] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kZeroDigitSymbol)); + symbols[NUMBER_SYMBOL_DIGIT] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kDigitSymbol)); + symbols[NUMBER_SYMBOL_CURRENCY] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kCurrencySymbol)); + symbols[NUMBER_SYMBOL_INTL_CURRENCY] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kIntlCurrencySymbol)); + symbols[NUMBER_SYMBOL_MONETARY_SEPARATOR] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kMonetarySeparatorSymbol)); + symbols[NUMBER_SYMBOL_PER_MILL] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kPerMillSymbol)); + symbols[NUMBER_SYMBOL_EXPONENTIAL] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kExponentialSymbol)); + symbols[NUMBER_SYMBOL_PLUS_SIGN] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kPlusSignSymbol)); + symbols[NUMBER_SYMBOL_MINUS_SIGN] = _LocaleData::GetOspString(sym.getSymbol(IcuDecimalFormatSymbols::kMinusSignSymbol)); + + return E_SUCCESS; +} + +result +_LocaleData::SetNumberFormatter(const Locale& locale, NumberFormatterStyle style) +{ + if (__pIcuNumberFormatter) + { + delete __pIcuNumberFormatter; + __pIcuNumberFormatter = null; + } + + IcuNumberFormat* pNumFmt = null; + UErrorCode ec = U_ZERO_ERROR; + result r = SetLocale(locale); + + if (!IsFailed(r)) + { + switch (style) + { + case NUM_FORMATTER_STYLE_NUMBER: + { + pNumFmt = IcuNumberFormat::createInstance(__icuLocale, ec); + break; + } + + case NUM_FORMATTER_STYLE_CURRENCY: + { + pNumFmt = IcuNumberFormat::createCurrencyInstance(__icuLocale, ec); + break; + } + + case NUM_FORMATTER_STYLE_PERCENT: + { + pNumFmt = IcuNumberFormat::createPercentInstance(__icuLocale, ec); + break; + } + + default: + { + r = E_UNSUPPORTED_OPERATION; + break; + } + } + + if (IsFailed(r)) + { + return r; + } + + if (U_SUCCESS(ec)) + { + if (pNumFmt && (pNumFmt->getDynamicClassID() == IcuDecimalFormat::getStaticClassID())) + { + __pIcuNumberFormatter = dynamic_cast< IcuDecimalFormat* >(pNumFmt); + if (__pIcuNumberFormatter) + { + return E_SUCCESS; + } + } + } + } + + return E_UNSUPPORTED_OPERATION; +} + +result +_LocaleData::FormatNumber(long number, _FieldPosition& pos, Tizen::Base::String& str) +{ + str = ""; + + if (__pIcuNumberFormatter) + { + IcuUnicodeString icuStr; + IcuFieldPosition icuPos = GetIcuFieldPosition(pos); + icuStr = __pIcuNumberFormatter->format(static_cast< int32_t >(number), icuStr, icuPos); + + str = _LocaleData::GetOspString(icuStr); + return E_SUCCESS; + } + + return E_SYSTEM; +} + +result +_LocaleData::FormatNumber(double number, _FieldPosition& pos, Tizen::Base::String& str) +{ + str = ""; + + if (__pIcuNumberFormatter) + { + IcuUnicodeString icuStr; + IcuFieldPosition icuPos = GetIcuFieldPosition(pos); + icuStr = __pIcuNumberFormatter->format(number, icuStr, icuPos); + + str = _LocaleData::GetOspString(icuStr); + return E_SUCCESS; + } + + return E_SYSTEM; +} + +result +_LocaleData::ApplyNumberPattern(const Tizen::Base::String& pattern, bool localized) +{ + if (__pIcuNumberFormatter) + { + IcuUnicodeString icuPattern; + icuPattern = __pIcuNumberFormatter->toPattern(icuPattern); + + UErrorCode ec = U_ZERO_ERROR; + IcuUParseError parseError = {0}; + IcuUnicodeString icuNewPatter; + GetIcuString(pattern, icuNewPatter); + + if (localized) + { + __pIcuNumberFormatter->applyLocalizedPattern(icuNewPatter, parseError, ec); + } + else + { + __pIcuNumberFormatter->applyPattern(icuNewPatter, parseError, ec); + } + + if (U_SUCCESS(ec)) + { + return E_SUCCESS; + } + else + { + SysLog(NID_LCL, "Error [%d -> %s] in setting pattern to %ls at %d:%d", + ec, u_errorName(ec), pattern.GetPointer(), parseError.line, parseError.offset); + + __pIcuNumberFormatter->applyPattern(icuPattern, ec); + } + } + + return E_INVALID_ARG; +} + +String +_LocaleData::GetNumberFormatterStringAttributes(NumberFormatterAttributes attrName) +{ + IcuUnicodeString icuRetValue; + + if (__pIcuNumberFormatter) + { + switch (attrName) + { + case NUM_FORMATTER_FIELD_CURRENCY: + { + icuRetValue = __pIcuNumberFormatter->getCurrency(); + break; + } + + case NUM_FORMATTER_FIELD_POSITIVE_PREFIX: + { + icuRetValue = __pIcuNumberFormatter->getPositivePrefix(icuRetValue); + break; + } + + case NUM_FORMATTER_FIELD_NEGATIVE_PREFIX: + { + icuRetValue = __pIcuNumberFormatter->getNegativePrefix(icuRetValue); + break; + } + + case NUM_FORMATTER_FIELD_POSITIVE_SUFFIX: + { + icuRetValue = __pIcuNumberFormatter->getPositiveSuffix(icuRetValue); + break; + } + + case NUM_FORMATTER_FIELD_NEGATIVE_SUFFIX: + { + icuRetValue = __pIcuNumberFormatter->getNegativeSuffix(icuRetValue); + break; + } + + case NUM_FORMATTER_FIELD_PATTERN: + { + icuRetValue = __pIcuNumberFormatter->toPattern(icuRetValue); + break; + } + + case NUM_FORMATTER_FIELD_LOCALIZED_PATTERN: + { + icuRetValue = __pIcuNumberFormatter->toLocalizedPattern(icuRetValue); + break; + } + + default: + { + break; + } + } + + return _LocaleData::GetOspString(icuRetValue); + } + + return Tizen::Base::String(""); +} + +void +_LocaleData::SetNumberFormatterAttributes(const String& newValue, NumberFormatterAttributes attrName) +{ + if (__pIcuNumberFormatter) + { + IcuUnicodeString icuNewValue; + GetIcuString(newValue, icuNewValue); + + switch (attrName) + { + case NUM_FORMATTER_FIELD_CURRENCY: + { + __pIcuNumberFormatter->setCurrency(icuNewValue.getTerminatedBuffer()); + break; + } + + case NUM_FORMATTER_FIELD_POSITIVE_PREFIX: + { + __pIcuNumberFormatter->setPositivePrefix(icuNewValue); + break; + } + + case NUM_FORMATTER_FIELD_NEGATIVE_PREFIX: + { + __pIcuNumberFormatter->setNegativePrefix(icuNewValue); + break; + } + + case NUM_FORMATTER_FIELD_POSITIVE_SUFFIX: + { + __pIcuNumberFormatter->setPositiveSuffix(icuNewValue); + break; + } + + case NUM_FORMATTER_FIELD_NEGATIVE_SUFFIX: + { + __pIcuNumberFormatter->setNegativeSuffix(icuNewValue); + break; + } + + default: + { + break; + } + } + } +} + +int +_LocaleData::GetNumberFormatterIntAttributes(NumberFormatterAttributes attrName) +{ + int res = 0; + if (__pIcuNumberFormatter) + { + switch (attrName) + { + case NUM_FORMATTER_FIELD_MAX_INTEGER_DIGITS: + { + res = __pIcuNumberFormatter->getMaximumIntegerDigits(); + break; + } + + case NUM_FORMATTER_FIELD_MIN_INTEGER_DIGITS: + { + res = __pIcuNumberFormatter->getMinimumIntegerDigits(); + break; + } + + case NUM_FORMATTER_FIELD_MAX_FRACTION_DIGITS: + { + res = __pIcuNumberFormatter->getMaximumFractionDigits(); + break; + } + + case NUM_FORMATTER_FIELD_MIN_FRACTION_DIGITS: + { + res = __pIcuNumberFormatter->getMinimumFractionDigits(); + break; + } + + case NUM_FORMATTER_FIELD_MIN_EXPONENT_DIGITS: + { + res = __pIcuNumberFormatter->getMinimumExponentDigits(); + break; + } + + case NUM_FORMATTER_FIELD_MULTIPLIER: + { + res = __pIcuNumberFormatter->getMultiplier(); + break; + } + + case NUM_FORMATTER_FIELD_GROUPING_SIZE: + { + res = __pIcuNumberFormatter->getGroupingSize(); + break; + } + + default: + { + res = 0; + break; + } + } + } + + return res; +} + +void +_LocaleData::SetNumberFormatterAttributes(const int newValue, NumberFormatterAttributes attrName) +{ + if (__pIcuNumberFormatter) + { + switch (attrName) + { + case NUM_FORMATTER_FIELD_MAX_INTEGER_DIGITS: + { + __pIcuNumberFormatter->setMaximumIntegerDigits(newValue); + break; + } + + case NUM_FORMATTER_FIELD_MIN_INTEGER_DIGITS: + { + __pIcuNumberFormatter->setMinimumIntegerDigits(newValue); + break; + } + + case NUM_FORMATTER_FIELD_MAX_FRACTION_DIGITS: + { + __pIcuNumberFormatter->setMaximumFractionDigits(newValue); + break; + } + + case NUM_FORMATTER_FIELD_MIN_FRACTION_DIGITS: + { + __pIcuNumberFormatter->setMinimumFractionDigits(newValue); + break; + } + + case NUM_FORMATTER_FIELD_MIN_EXPONENT_DIGITS: + { + __pIcuNumberFormatter->setMinimumExponentDigits(newValue); + break; + } + + case NUM_FORMATTER_FIELD_MULTIPLIER: + { + __pIcuNumberFormatter->setMultiplier(newValue); + break; + } + + case NUM_FORMATTER_FIELD_GROUPING_SIZE: + { + __pIcuNumberFormatter->setGroupingSize(newValue); + break; + } + + default: + { + break; + } + } + } +} + +bool +_LocaleData::GetNumberFormatterBoolAttributes(NumberFormatterAttributes attrName) +{ + bool res = false; + if (__pIcuNumberFormatter) + { + switch (attrName) + { + case NUM_FORMATTER_FIELD_IS_GROUPING_USED: + { + res = __pIcuNumberFormatter->isGroupingUsed(); + break; + } + + case NUM_FORMATTER_FIELD_IS_DECIMAL_SEPARATOR_ALWAYS_SHOWN: + { + res = __pIcuNumberFormatter->isDecimalSeparatorAlwaysShown(); + break; + } + + case NUM_FORMATTER_FIELD_IS_POSITIVE_SIGN_ALWAYS_SHOWN: + { + IcuUnicodeString ps("+"); + IcuUnicodeString pp; + pp = __pIcuNumberFormatter->getPositivePrefix(pp); + + res = (pp == ps); + break; + } + + default: + { + res = false; + break; + } + } + } + + return res; +} + +void +_LocaleData::SetNumberFormatterAttributes(const bool newValue, NumberFormatterAttributes attrName) +{ + if (__pIcuNumberFormatter) + { + switch (attrName) + { + case NUM_FORMATTER_FIELD_IS_GROUPING_USED: + { + __pIcuNumberFormatter->setGroupingUsed(newValue); + break; + } + + case NUM_FORMATTER_FIELD_IS_DECIMAL_SEPARATOR_ALWAYS_SHOWN: + { + __pIcuNumberFormatter->setDecimalSeparatorAlwaysShown(newValue); + break; + } + + case NUM_FORMATTER_FIELD_IS_POSITIVE_SIGN_ALWAYS_SHOWN: + { + IcuUnicodeString ps("+"); + IcuUnicodeString pp; + pp = __pIcuNumberFormatter->getPositivePrefix(pp); + + if (newValue) + { + __pIcuNumberFormatter->setPositivePrefix(ps); + } + else + { + if (pp == ps) + { + __pIcuNumberFormatter->setPositivePrefix(""); + } + } + break; + } + + default: + { + break; + } + } + } +} + +result +_LocaleData::SetDateFormatSymbols(const Locale& locale) +{ + if (__pIcuDateFormatSymbols) + { + delete __pIcuDateFormatSymbols; + __pIcuDateFormatSymbols = null; + } + + UErrorCode ec = U_ZERO_ERROR; + result r = SetLocale(locale); + + if (!IsFailed(r)) + { + __pIcuDateFormatSymbols = new IcuDateFormatSymbols(__icuLocale, ec); + + if (__pIcuDateFormatSymbols && U_SUCCESS(ec)) + { + return E_SUCCESS; + } + } + + delete __pIcuDateFormatSymbols; + __pIcuDateFormatSymbols = null; + + return r; +} + +IList* +_LocaleData::GetDateFormatSymbolAttrArrayN(DateFormatSymbolsAttributes attrName) +{ + if (__pIcuDateFormatSymbols) + { + ClearLastResult(); + int count = 0; + const IcuUnicodeString* pIcuList = null; + + switch (attrName) + { + case DATE_FORMAT_SYM_ERA_LIST: + { + pIcuList = __pIcuDateFormatSymbols->getEras(count); + break; + } + + case DATE_FORMAT_SYM_MONTH_LIST: + { + pIcuList = __pIcuDateFormatSymbols->getMonths(count); + break; + } + + case DATE_FORMAT_SYM_SHORT_MONTH_LIST: + { + pIcuList = __pIcuDateFormatSymbols->getShortMonths(count); + break; + } + + case DATE_FORMAT_SYM_WEEKDAY_LIST: + { + pIcuList = __pIcuDateFormatSymbols->getWeekdays(count); + break; + } + + case DATE_FORMAT_SYM_SHORT_WEEKDAY_LIST: + { + pIcuList = __pIcuDateFormatSymbols->getShortWeekdays(count); + break; + } + + case DATE_FORMAT_SYM_AM_PM_LIST: + { + pIcuList = __pIcuDateFormatSymbols->getAmPmStrings(count); + break; + } + + default: + { + SetLastResult(E_UNSUPPORTED_OPERATION); + break; + } + } + + if (pIcuList) + { + return ConvertIcuStringArrayToOspArrayN(pIcuList, count); + } + } + + SetLastResult(E_INVALID_STATE); + return null; +} + + +IcuUDate +_LocaleData::GetIcuDate(DateTime date) +{ + DateTime icuBaseTime; + icuBaseTime.SetValue(1970, 1, 1); + DateTime ospBaseTime = DateTime::GetMinValue(); + + result r = icuBaseTime.Subtract(ospBaseTime.GetTime()); + if (r != E_SUCCESS) + { + SysLogException(NID_LCL, r, "[%s] Propagated.", GetErrorMessage(r)); + } + + TimeSpan tsIcu = icuBaseTime.GetTime(); + TimeSpan tsOsp = date.GetTime(); + TimeSpan diff = tsOsp - tsIcu; + + IcuUDate icuDate = diff.GetTicks(); + return icuDate; +} + +result +_LocaleData::SetDateTimeFormatter(DateTimeStyle dateStyle, DateTimeStyle timeStyle, const Locale& locale) +{ + IcuDateFormat* pIcuDateFormat = null; + + result r = SetLocale(locale); + SysTryReturnResult(NID_LCL, !IsFailed(r), E_INVALID_ARG, "Locale setting failed."); + + U_ICU_NAMESPACE::DateFormat::EStyle icuDateStyle = (U_ICU_NAMESPACE::DateFormat::EStyle) dateStyle; + U_ICU_NAMESPACE::DateFormat::EStyle icuTimeStyle = (U_ICU_NAMESPACE::DateFormat::EStyle) timeStyle; + + if (dateStyle == DATE_TIME_STYLE_NONE) + { + if (timeStyle != DATE_TIME_STYLE_NONE) + { + pIcuDateFormat = IcuDateFormat::createTimeInstance(icuTimeStyle, __icuLocale); + } + } + else + { + if (timeStyle == DATE_TIME_STYLE_NONE) + { + pIcuDateFormat = IcuDateFormat::createDateInstance(icuDateStyle, __icuLocale); + } + else + { + pIcuDateFormat = IcuDateFormat::createDateTimeInstance(icuDateStyle, icuTimeStyle, __icuLocale); + } + } + + if (pIcuDateFormat) + { + if (__pIcuDateFormat) + { + delete __pIcuDateFormat; + __pIcuDateFormat = null; + } + __pIcuDateFormat = dynamic_cast< IcuSimpleDateFormat* >(pIcuDateFormat); + + if (__pIcuDateFormat) + { + if (__pIcuDateFormatSymbols) + { + delete __pIcuDateFormatSymbols; + __pIcuDateFormatSymbols = null; + } + + const IcuDateFormatSymbols* pDateTimeFormatSym = __pIcuDateFormat->getDateFormatSymbols(); + + if (pDateTimeFormatSym) + { + __pIcuDateFormatSymbols = new IcuDateFormatSymbols(*pDateTimeFormatSym); + } + + return E_SUCCESS; + } + } + + delete pIcuDateFormat; + return E_INVALID_ARG; +} + +result +_LocaleData::SetStartTimeRule(IcuSimpleTimeZone& zone, const TimeRule* pOspTimeRule) +{ + if (pOspTimeRule) + { + UErrorCode status = U_ZERO_ERROR; + IcuDateTimeRule::TimeRuleType icuTimeRuleType; + + DstRuleMode ospRuleMode = static_cast< DstRuleMode >(pOspTimeRule->GetRuleMode()); + Tizen::System::TimeMode ospTimeMode = pOspTimeRule->GetTimeMode(); + + switch (ospTimeMode) + { + case Tizen::System::UTC_TIME: + { + icuTimeRuleType = IcuDateTimeRule::UTC_TIME; + break; + } + + case Tizen::System::STANDARD_TIME: + { + icuTimeRuleType = IcuDateTimeRule::STANDARD_TIME; + break; + } + + case Tizen::System::WALL_TIME: + default: + { + icuTimeRuleType = IcuDateTimeRule::WALL_TIME; + break; + } + } + + int time = ((pOspTimeRule->GetHour() * 60) + pOspTimeRule->GetMinute()) * 60 * 1000; + + switch (ospRuleMode) + { + case EXACT_DAY: + { + zone.setStartRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetDay(), + time, + icuTimeRuleType, + status); + break; + } + + case DAY_OF_WEEK_IN_MONTH: + { + zone.setStartRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetWeek(), + pOspTimeRule->GetDayOfWeek(), + time, + icuTimeRuleType, + status); + break; + } + + case AFTER_THE_SPECIFIED_DAY: + { + zone.setStartRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetDay(), + pOspTimeRule->GetDayOfWeek(), + time, + icuTimeRuleType, + status); + break; + } + + case BEFORE_THE_SPECIFIED_DAY: + { + zone.setStartRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetDay(), + -pOspTimeRule->GetDayOfWeek(), + time, + icuTimeRuleType, + status); + break; + } + + case BACKWARD_FROM_END_OF_MONTH: + { + zone.setStartRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetWeek() * -1, + 0, + time, + icuTimeRuleType, + status); + break; + } + } + return U_SUCCESS(status) ? E_SUCCESS : E_SYSTEM; + } + return E_INVALID_ARG; +} + +result +_LocaleData::SetEndTimeRule(IcuSimpleTimeZone& zone, const TimeRule* pOspTimeRule) +{ + if (pOspTimeRule) + { + UErrorCode status = U_ZERO_ERROR; + IcuDateTimeRule::TimeRuleType icuTimeRuleType; + + DstRuleMode ospRuleMode = static_cast< DstRuleMode >(pOspTimeRule->GetRuleMode()); + Tizen::System::TimeMode ospTimeMode = pOspTimeRule->GetTimeMode(); + + switch (ospTimeMode) + { + case Tizen::System::UTC_TIME: + { + icuTimeRuleType = IcuDateTimeRule::UTC_TIME; + break; + } + + case Tizen::System::STANDARD_TIME: + { + icuTimeRuleType = IcuDateTimeRule::STANDARD_TIME; + break; + } + + case Tizen::System::WALL_TIME: + default: + { + icuTimeRuleType = IcuDateTimeRule::WALL_TIME; + break; + } + } + + int time = ((pOspTimeRule->GetHour() * 60) + pOspTimeRule->GetMinute()) * 60 * 1000; + + switch (ospRuleMode) + { + case EXACT_DAY: + { + zone.setEndRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetDay(), + time, + icuTimeRuleType, + status); + break; + } + + case DAY_OF_WEEK_IN_MONTH: + { + zone.setEndRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetWeek(), + pOspTimeRule->GetDayOfWeek(), + time, + icuTimeRuleType, + status); + break; + } + + case AFTER_THE_SPECIFIED_DAY: + { + zone.setEndRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetDay(), + pOspTimeRule->GetDayOfWeek(), + time, + icuTimeRuleType, + status); + break; + } + + case BEFORE_THE_SPECIFIED_DAY: + { + zone.setEndRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetDay(), + -pOspTimeRule->GetDayOfWeek(), + time, + icuTimeRuleType, + status); + break; + } + + case BACKWARD_FROM_END_OF_MONTH: + { + zone.setEndRule( + pOspTimeRule->GetMonth(), + pOspTimeRule->GetWeek() * -1, + 0, + time, + icuTimeRuleType, + status); + break; + } + } + return U_SUCCESS(status) ? E_SUCCESS : E_SYSTEM; + } + return E_INVALID_ARG; +} + +result +_LocaleData::FormatDateTime(const DateTime& date, String& str) +{ + std::auto_ptr pCal(Calendar::CreateInstanceN()); + SysTryReturnResult(NID_LCL, pCal.get(), E_OUT_OF_MEMORY, "Memory allocation failed"); + + result r = pCal->SetTime(date); + SysTryReturn(NID_LCL, r == E_SUCCESS, r, r, "[%s] Unable to set date time in default calendar"); + + r = pCal->Clear(TIME_FIELD_MILLISECOND); + SysTryReturn(NID_LCL, r == E_SUCCESS, r, r, "[%s] Unable to set date time in default calendar"); + + return FormatDateTime(*pCal, str); +} + +result +_LocaleData::FormatDateTime(const Calendar& calendar, Tizen::Base::String& str) +{ + SysTryReturnResult(NID_LCL, __pIcuDateFormat, E_INVALID_STATE, "This instance is not constructed"); + ClearLastResult(); + + const _IcuCalendarImpl* _pIcuCalendarImpl = _CalendarImpl::GetImpl(calendar); + if (_pIcuCalendarImpl) + { + IcuCalendar* pIcuCal = _pIcuCalendarImpl->GetIcuCalendarCloneN(); + if (pIcuCal) + { + IcuFieldPosition icuFp; + IcuUnicodeString icuStr; + + GetIcuString(str,icuStr); + icuStr = __pIcuDateFormat->format(*pIcuCal, icuStr, icuFp); + str = _LocaleData::GetOspString(icuStr); + + delete pIcuCal; + return GetLastResult(); + } + } + + return E_SYSTEM; +} + +String +_LocaleData::GetDateTimePattern() +{ + SysTryReturn(NID_LCL, __pIcuDateFormat, String(""), E_INVALID_STATE, "This instance is not constructed"); + IcuUnicodeString icuPattern; + + icuPattern = __pIcuDateFormat->toPattern(icuPattern); + return _LocaleData::GetOspString(icuPattern); +} + +result +_LocaleData::SetDateTimePattern(const String& pattern) +{ + SysTryReturnResult(NID_LCL, __pIcuDateFormat, E_INVALID_STATE, "This instance is not constructed"); + IcuUnicodeString icuStr; + + GetIcuString(pattern, icuStr); + + __pIcuDateFormat->applyPattern(icuStr); + + return E_SUCCESS; +} +DateTimeSymbols* +_LocaleData::GetDateTimeSymbolsN(DateTimeSymbols* pDateTimeSymbols) +{ + SysTryReturn(NID_LCL, __pIcuDateFormatSymbols, null, E_INVALID_STATE, "[E_INVALID_STATE] This instance is not constructed"); + SysTryReturn(NID_LCL, pDateTimeSymbols, null, E_INVALID_ARG, "[%s] Invalid argument is used. pDateTimeSymbols is null.", GetErrorMessage(E_INVALID_ARG)); + + _DateTimeSymbolsImpl* pDateTimeSymbolsImpl = _DateTimeSymbolsImpl::GetDateTimeSymbolsImpl(pDateTimeSymbols); + + if (pDateTimeSymbolsImpl) + { + pDateTimeSymbolsImpl->ReleaseAll(); + + pDateTimeSymbolsImpl->__pErasList = GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_ERA_LIST); + pDateTimeSymbolsImpl->__pMonthsList = GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_MONTH_LIST); + pDateTimeSymbolsImpl->__pShortMonthsList = GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_SHORT_MONTH_LIST); + pDateTimeSymbolsImpl->__pWeekdaysList = GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_WEEKDAY_LIST); + pDateTimeSymbolsImpl->__pShortWeekdaysList = GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_SHORT_WEEKDAY_LIST); + pDateTimeSymbolsImpl->__pAmPmList = GetDateFormatSymbolAttrArrayN(DATE_FORMAT_SYM_AM_PM_LIST); + + return pDateTimeSymbols; + } + + return null; +} + +// This function convert and set ICU DateTime symbols from OSP DateTimeSymbols +result +_LocaleData::SetDateTimeSymbols(const DateTimeSymbols& newValue) +{ + UErrorCode ec = U_ZERO_ERROR; + + if (!__pIcuDateFormatSymbols) + { + __pIcuDateFormatSymbols = new IcuDateFormatSymbols(ec); + } + + IcuUnicodeString* pIcuArray = null; + int count = 0; + + if (U_SUCCESS(ec) && __pIcuDateFormatSymbols != null) + { + pIcuArray = ConvertOspArrayToIcuStringArrayN(newValue.GetEras(), count); + __pIcuDateFormatSymbols->setEras(pIcuArray, count); + delete[] pIcuArray; + + pIcuArray = ConvertOspArrayToIcuStringArrayN(newValue.GetMonths(), count); + __pIcuDateFormatSymbols->setMonths(pIcuArray, count); + delete[] pIcuArray; + + pIcuArray = ConvertOspArrayToIcuStringArrayN(newValue.GetShortMonths(), count); + __pIcuDateFormatSymbols->setShortMonths(pIcuArray, count); + delete[] pIcuArray; + + pIcuArray = ConvertOspArrayToIcuStringArrayN(newValue.GetWeekdays(), count); + __pIcuDateFormatSymbols->setWeekdays(pIcuArray, count); + delete[] pIcuArray; + + pIcuArray = ConvertOspArrayToIcuStringArrayN(newValue.GetShortWeekdays(), count); + __pIcuDateFormatSymbols->setShortWeekdays(pIcuArray, count); + delete[] pIcuArray; + + pIcuArray = ConvertOspArrayToIcuStringArrayN(newValue.GetAmPm(), count); + __pIcuDateFormatSymbols->setAmPmStrings(pIcuArray, count); + delete[] pIcuArray; + +// From ICU Docs: SimpleDateFormat no longer use the zone strings stored in a DateFormatSymbols. Therefore, the time zone strings +// set by this method have no effects in an instance of SimpleDateFormat for formatting time zones. +// __pIcuDateFormatSymbols->setZoneStrings(); + + return E_SUCCESS; + } + + return E_UNSUPPORTED_OPERATION; +} + +void +_LocaleData::SetGregorianWeekCountData(const Locale& ospLocale, DayOfWeek& firstDayOfWeek, short& minDaysInFirstWeek) +{ + UErrorCode success = U_ZERO_ERROR; + IcuLocale icuLocale; + + icuLocale = GetIcuLocale(ospLocale); + result r = GetLastResult(); + SysAssert(r == E_SUCCESS); + + GregorianCalendar gc(icuLocale, success); + SysAssert(U_SUCCESS(success)); + + firstDayOfWeek = (DayOfWeek) gc.getFirstDayOfWeek(); // Set __firstDayOfWeek from ICU data + minDaysInFirstWeek = 1; // To align with 2.0 version +// minDaysInFirstWeek = (short) gc.getMinimalDaysInFirstWeek(); // Set __minDaysInFirstWeek from ICU data +} + +_LocaleData::_LocaleData(void) + : __icuLocale() + , // default ICU locale + __pIcuNumberFormatter(null) + , __pIcuDateFormatSymbols(null) + , __pIcuDateFormat(null) +{ +} + + +_LocaleData::~_LocaleData(void) +{ + if (__pIcuNumberFormatter) // Delete __pIcuNumberFormatter and set to null + { + delete __pIcuNumberFormatter; + __pIcuNumberFormatter = null; + } + + if (__pIcuDateFormatSymbols) // Delete __pIcuDateFormatSymbols and set to null + { + delete __pIcuDateFormatSymbols; + __pIcuDateFormatSymbols = null; + } + + if (__pIcuDateFormat) // Delete __pIcuDateFormat and set to null + { + delete __pIcuDateFormat; + __pIcuDateFormat = null; + } +} + + +}; +}; // Tizen::Locales + diff --git a/src/locales/FLcl_LocaleData.h b/src/locales/FLcl_LocaleData.h new file mode 100644 index 0000000..521632d --- /dev/null +++ b/src/locales/FLcl_LocaleData.h @@ -0,0 +1,204 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_LocaleData.h + * @brief This is the header file for _LocaleData class. + */ +#ifndef _FLCL_INTERNAL_LOCALE_DATA_H_ +#define _FLCL_INTERNAL_LOCALE_DATA_H_ + +// Includes +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FLcl_NumberFormatterImpl.h" +#include "FLcl_DateTimeSymbolsImpl.h" +#include "FLcl_FieldPosition.h" + + +typedef UParseError IcuUParseError; +typedef UDate IcuUDate; +typedef UChar IcuUChar; + +typedef U_ICU_NAMESPACE::UnicodeString IcuUnicodeString; +typedef U_ICU_NAMESPACE::StringEnumeration IcuStringEnumeration; +typedef U_ICU_NAMESPACE::Locale IcuLocale; +typedef U_ICU_NAMESPACE::TimeZone IcuTimeZone; +typedef U_ICU_NAMESPACE::BasicTimeZone IcuBasicTimeZone; +typedef U_ICU_NAMESPACE::SimpleTimeZone IcuSimpleTimeZone; +typedef U_ICU_NAMESPACE::DecimalFormatSymbols IcuDecimalFormatSymbols; +typedef U_ICU_NAMESPACE::Calendar IcuCalendar; +typedef U_ICU_NAMESPACE::GregorianCalendar IcuGregorianCalendar; +typedef U_ICU_NAMESPACE::InitialTimeZoneRule IcuInitialTimeZoneRule; +typedef U_ICU_NAMESPACE::AnnualTimeZoneRule IcuAnnualTimeZoneRule; +typedef U_ICU_NAMESPACE::DateTimeRule IcuDateTimeRule; +typedef U_ICU_NAMESPACE::NumberFormat IcuNumberFormat; +typedef U_ICU_NAMESPACE::DecimalFormat IcuDecimalFormat; +typedef U_ICU_NAMESPACE::FieldPosition IcuFieldPosition; + +typedef U_ICU_NAMESPACE::DateFormatSymbols IcuDateFormatSymbols; +typedef U_ICU_NAMESPACE::DateFormat IcuDateFormat; +typedef U_ICU_NAMESPACE::SimpleDateFormat IcuSimpleDateFormat; + +namespace Tizen { namespace Locales +{ + +/** + * @enum DstRuleMode + * Possible DST rule mode + * + * @since 1.0 + */ +enum DstRuleMode +{ + EXACT_DAY = 0, + DAY_OF_WEEK_IN_MONTH, + AFTER_THE_SPECIFIED_DAY, + BEFORE_THE_SPECIFIED_DAY, + BACKWARD_FROM_END_OF_MONTH +}; + +/** + * @class _LocaleData + * @brief This class is for loading the @e locale data. + * @since 1.0 + * + * _LocaleData is represented locale data which is specific localized. + * This class is used by other classed in locale namespace to load the localized data. + * + */ + +class _LocaleData + : public Tizen::Base::Object +{ + + +// Construct Operations +public: + /** + * Creates an @b uninitialized instance. + * + * @remarks After creating an instance of this class, you must explicitly call the @e Construct() method + * to initialize the instance. + * @see Construct + */ + _LocaleData(void); + + + /** + * Destroys this instance. + */ + virtual ~_LocaleData(void); + + +// Operations +private: + + Tizen::Base::Collection::ArrayList* ConvertIcuStringArrayToOspArrayN(const IcuUnicodeString* pIcuStrList, int count); + IcuUnicodeString* ConvertOspArrayToIcuStringArrayN(const Tizen::Base::Collection::IList* pIcuStrList, int& count); + + // Methods to support Locale + const IcuLocale& GetIcuLocale(void); + IcuLocale GetIcuLocale(const Tizen::Locales::Locale& ospLocale); + +public: + static Tizen::Base::String GetOspString(const IcuUnicodeString& icuStr); + static U_ICU_NAMESPACE::UnicodeString GetIcuString(const Tizen::Base::String& ospString); + static void GetIcuString(const Tizen::Base::String& ospStr, IcuUnicodeString& icuStr); + + static IcuUDate GetIcuDate(Tizen::Base::DateTime date); + static IcuFieldPosition GetIcuFieldPosition(_FieldPosition pos); + + // Methods to support Locale + bool IsLocaleSupported(); + static Locale GetOspSystemLocale(void); + static Locale GetOspLocale(const IcuLocale& icuLocale); + result SetLocale(const Locale& ospLocale); + + // Methods to support NumberSymbols + result GetNumberSymbols(const Locale &locale, Tizen::Base::String symbols[]); + + // Methods to support NumberFormatter + result SetNumberFormatter(const Locale& locale, NumberFormatterStyle style); + result FormatNumber(long number, _FieldPosition& pos, Tizen::Base::String& str); + result FormatNumber(double number, _FieldPosition& pos, Tizen::Base::String& str); + result ApplyNumberPattern(const Tizen::Base::String& pattern, bool localized); + + Tizen::Base::String GetNumberFormatterStringAttributes(NumberFormatterAttributes attrName); + void SetNumberFormatterAttributes(const Tizen::Base::String& newValue, NumberFormatterAttributes attrName); + + int GetNumberFormatterIntAttributes(NumberFormatterAttributes attrName); + void SetNumberFormatterAttributes(const int newValue, NumberFormatterAttributes attrName); + + bool GetNumberFormatterBoolAttributes(NumberFormatterAttributes attrName); + void SetNumberFormatterAttributes(const bool newValue, NumberFormatterAttributes attrName); + + + // Methods to support DateTimeSymbols + result SetDateFormatSymbols(const Locale& locale); + Tizen::Base::Collection::IList* GetDateFormatSymbolAttrArrayN(DateFormatSymbolsAttributes attrName); + + // Methods to support DateTimeFormatter + result SetDateTimeFormatter(DateTimeStyle dateStyle, DateTimeStyle timeStyle, const Locale& locale); + result FormatDateTime(const Tizen::Base::DateTime& date, Tizen::Base::String& str); + result FormatDateTime(const Calendar& calendar, Tizen::Base::String& str); + Tizen::Base::String GetDateTimePattern(); + result SetDateTimePattern(const Tizen::Base::String& pattern); + DateTimeSymbols* GetDateTimeSymbolsN(DateTimeSymbols* pDateTimeSymbols); + result SetDateTimeSymbols(const DateTimeSymbols& newValue); + + + // Methods to support TimeZone + result SetStartTimeRule(IcuSimpleTimeZone& zone, const TimeRule* pOspTimeRule); + result SetEndTimeRule(IcuSimpleTimeZone& zone, const TimeRule* pOspTimeRule); + + // Methods to support Calendar + void SetGregorianWeekCountData(const Locale& ospLocale, DayOfWeek& firstDayOfWeek, short& minDaysInFirstWeek); + + // Lists from ICU TimeZone + Tizen::Base::Collection::IList* GetAvailableTimeZonesN(void); + Tizen::Base::Collection::IList* GetAvailableTimeZonesN(int rawOffset); + +private: + _LocaleData(const _LocaleData& localeData); + _LocaleData& operator =(const _LocaleData& localeData); + +private: + IcuLocale __icuLocale; + IcuDecimalFormat* __pIcuNumberFormatter; + IcuDateFormatSymbols* __pIcuDateFormatSymbols; + IcuSimpleDateFormat* __pIcuDateFormat; + +}; // LocaleData + +}} // Tizen::Locales + +#endif // _FLCL_INTERNAL_LOCALE_DATA_H_ + diff --git a/src/locales/FLcl_LocaleImpl.cpp b/src/locales/FLcl_LocaleImpl.cpp new file mode 100644 index 0000000..b87f81b --- /dev/null +++ b/src/locales/FLcl_LocaleImpl.cpp @@ -0,0 +1,292 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_LocaleImpl.cpp + * @brief This is the implementation file for _LocaleImpl class. + */ + +#include +#include + +#include +#include + +#include "FLcl_LocaleImpl.h" +#include "FLcl_LocaleData.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +_LocaleImpl::_LocaleImpl(void) + : __icuLocale() +{ +} + +_LocaleImpl::_LocaleImpl(const char* pLocaleCode) + : __icuLocale(pLocaleCode) +{ + if (pLocaleCode == null || *pLocaleCode == '\0') + { + __icuLocale.setToBogus(); + } +} + +_LocaleImpl::_LocaleImpl(const char* pLanguage, const char* pCountry, const char* pVariant) + : __icuLocale(pLanguage, pCountry, pVariant) +{ + if (pLanguage == null || pCountry == null) + { + __icuLocale.setToBogus(); + } +} + +_LocaleImpl::_LocaleImpl(const U_ICU_NAMESPACE::Locale& icuLocale) + : __icuLocale(icuLocale) +{ +} + +_LocaleImpl::~_LocaleImpl(void) +{ +} + +_LocaleImpl* +_LocaleImpl::CloneN(void) +{ + return new (std::nothrow) _LocaleImpl(__icuLocale); +} + +U_ICU_NAMESPACE::Locale +_LocaleImpl::GetIcuLocale (void) const +{ + return __icuLocale; +} + +Locale +_LocaleImpl::GetOspLocale(void) +{ + LanguageCode languageCode = Locale::StringToLanguageCode(GetLanguageCodeString(false)); + CountryCode countryCode = Locale::StringToCountryCode(Get2LetterCountryCodeString()); + String variant(GetVariantCodeString()); + return Locale(languageCode, countryCode, &variant); +} + +bool +_LocaleImpl::operator ==(const _LocaleImpl& otherLocale) const +{ + return __icuLocale == otherLocale.__icuLocale; +} + +bool +_LocaleImpl::operator !=(const _LocaleImpl& otherLocale) const +{ + return !(*this == otherLocale); +} + +bool +_LocaleImpl::Equals(const Object& obj) const +{ + const _LocaleImpl* pOtherLocale = dynamic_cast< const _LocaleImpl* >(&obj); + if (pOtherLocale) + { + return *this == *pOtherLocale; + } + return false; +} + +int +_LocaleImpl::GetHashCode(void) const +{ + return __icuLocale.hashCode(); +} + +String +_LocaleImpl::GetLanguageCodeString(bool isTwoLetter) +{ + String languageCode((isTwoLetter ? __icuLocale.getLanguage() : __icuLocale.getISO3Language())); + String languageScriptTmp(__icuLocale.getScript()); + + if (!languageScriptTmp.IsEmpty()) + { + String languageScript; + languageScriptTmp.ToLowerCase(languageScript); + languageCode.Append(L"-"); + languageCode.Append(languageScript); + } + return languageCode; +} + +result +_LocaleImpl::GetLanguageName(String& languageName) const +{ + U_ICU_NAMESPACE::UnicodeString icuStr; + languageName = _LocaleData::GetOspString(__icuLocale.getDisplayLanguage(icuStr)); + if (!languageName.IsEmpty()) + { + String languageScriptTmp(__icuLocale.getScript()); + + if (!languageScriptTmp.IsEmpty()) + { + U_ICU_NAMESPACE::UnicodeString icuScriptStr; + String languageScriptName = _LocaleData::GetOspString(__icuLocale.getDisplayScript(icuScriptStr)); + languageName.Append(L" ("); + languageName.Append(languageScriptName); + languageName.Append(L")"); + } + return E_SUCCESS; + } + return E_UNSUPPORTED_OPERATION; +} + +result +_LocaleImpl::GetLanguageName(const _LocaleImpl& otherLocale, String& languageName) const +{ + U_ICU_NAMESPACE::UnicodeString icuStr; + languageName = _LocaleData::GetOspString(__icuLocale.getDisplayLanguage(otherLocale.__icuLocale, icuStr)); + if (!languageName.IsEmpty()) + { + String languageScriptTmp(__icuLocale.getScript()); + + if (!languageScriptTmp.IsEmpty()) + { + U_ICU_NAMESPACE::UnicodeString icuScriptStr; + String languageScriptName = _LocaleData::GetOspString(__icuLocale.getDisplayScript(otherLocale.__icuLocale, icuScriptStr)); + languageName.Append(L" ("); + languageName.Append(languageScriptName); + languageName.Append(L")"); + } + return E_SUCCESS; + } + return E_UNSUPPORTED_OPERATION; +} + +const char* +_LocaleImpl::Get2LetterCountryCodeString(void) const +{ + return __icuLocale.getCountry(); +} + +const char* +_LocaleImpl::Get3LetterCountryCodeString(void) const +{ + return __icuLocale.getISO3Country(); +} + +result +_LocaleImpl::GetCountryName(String& countryName) const +{ + U_ICU_NAMESPACE::UnicodeString icuStr; + countryName = _LocaleData::GetOspString(__icuLocale.getDisplayCountry(icuStr)); + if (!countryName.IsEmpty()) + { + return E_SUCCESS; + } + return E_UNSUPPORTED_OPERATION; +} + +result +_LocaleImpl::GetCountryName(const _LocaleImpl& otherLocale, String& countryName) const +{ + U_ICU_NAMESPACE::UnicodeString icuStr; + countryName = _LocaleData::GetOspString(__icuLocale.getDisplayCountry(otherLocale.__icuLocale, icuStr)); + if (!countryName.IsEmpty()) + { + return E_SUCCESS; + } + return E_UNSUPPORTED_OPERATION; +} + + +const char* +_LocaleImpl::GetVariantCodeString(void) const +{ + return __icuLocale.getVariant(); +} + +void +_LocaleImpl::SetVariantCodeString(const char* pVariantCode) +{ + __icuLocale = U_ICU_NAMESPACE::Locale(__icuLocale.getLanguage(), __icuLocale.getCountry(), pVariantCode); +} + +const char* +_LocaleImpl::GetLocaleCodeString(void) const +{ + return __icuLocale.getName(); +} + +bool +_LocaleImpl::IsLocaleSupported(void) const +{ + return !__icuLocale.isBogus(); +} + +const _LocaleImpl* +_LocaleImpl::GetLocaleImpl(const Locale& ospLocale) +{ + return ospLocale.__pLocaleImpl; +} + +String +_LocaleImpl::Get2LetterLanguageCodeString(const char* pLanguageCodeString) +{ + if (pLanguageCodeString) + { + _LocaleImpl localeImpl(pLanguageCodeString, "US", null); + return localeImpl.GetLanguageCodeString(true); + } + return null; +} + +String +_LocaleImpl::Get3LetterLanguageCodeString(const char* pLanguageCodeString) +{ + if (pLanguageCodeString) + { + _LocaleImpl localeImpl(pLanguageCodeString, "US", null); + return localeImpl.GetLanguageCodeString(false); + } + return null; +} + +const char* +_LocaleImpl::Get2LetterCountryCodeString(const char* pCountryCodeString) +{ + if (pCountryCodeString && strlen(pCountryCodeString) == 3) + { + _LocaleImpl localeImpl("en", pCountryCodeString, null); + return localeImpl.Get2LetterCountryCodeString(); + } + return null; +} + +const char* +_LocaleImpl::Get3LetterCountryCodeString(const char* pCountryCodeString) +{ + if (pCountryCodeString) + { + _LocaleImpl localeImpl("en", pCountryCodeString, null); + return localeImpl.Get3LetterCountryCodeString(); + } + return null; +} + +}; +}; // Tizen::Locales + diff --git a/src/locales/FLcl_LocaleImpl.h b/src/locales/FLcl_LocaleImpl.h new file mode 100644 index 0000000..6d30f81 --- /dev/null +++ b/src/locales/FLcl_LocaleImpl.h @@ -0,0 +1,91 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_LocaleImpl.h + * @brief This is the header file for the _LocaleImpl class. + * + * This header file contains declarations of the _LocaleImpl class. + * + */ + +#ifndef _FLCL_INTERNAL_LOCALE_IMPL_H_ +#define _FLCL_INTERNAL_LOCALE_IMPL_H_ + +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +class Locale; + +class _LocaleImpl + : public Tizen::Base::Object +{ +public: + _LocaleImpl(void); + _LocaleImpl(const char* pLocaleCode); + _LocaleImpl(const char* pLanguage, const char* pCountry, const char* pVariant = null); + _LocaleImpl(const U_ICU_NAMESPACE::Locale& icuLocale); + + _LocaleImpl* CloneN(void); + + virtual ~_LocaleImpl(void); + + bool operator ==(const _LocaleImpl& otherLocale) const; + bool operator !=(const _LocaleImpl& otherLocale) const; + virtual bool Equals(const Tizen::Base::Object& obj) const; + virtual int GetHashCode(void) const; + + String GetLanguageCodeString(bool isTwoLetter); + + result GetLanguageName(Tizen::Base::String& languageName) const; + result GetLanguageName(const _LocaleImpl& otherLocale, Tizen::Base::String& languageName) const; + + const char* Get2LetterCountryCodeString(void) const; + const char* Get3LetterCountryCodeString(void) const; + result GetCountryName(Tizen::Base::String& countryName) const; + result GetCountryName(const _LocaleImpl& otherLocale, Tizen::Base::String& countryName) const; + + const char* GetVariantCodeString(void) const; + void SetVariantCodeString(const char* pVariantCode = null); + + const char* GetLocaleCodeString(void) const; + + bool IsLocaleSupported(void) const; + + U_ICU_NAMESPACE::Locale GetIcuLocale (void) const; + Locale GetOspLocale(void); + + static const _LocaleImpl* GetLocaleImpl(const Locale& ospLocale); + + static String Get2LetterLanguageCodeString(const char* pLanguageCodeString); + static String Get3LetterLanguageCodeString(const char* pLanguageCodeString); + + static const char* Get2LetterCountryCodeString(const char* pCountryCodeString); + static const char* Get3LetterCountryCodeString(const char* pCountryCodeString); + +private: + U_ICU_NAMESPACE::Locale __icuLocale; +}; // _LocaleImpl + +}} // Tizen::Locales + +#endif //_FLCL_INTERNAL_LOCALE_IMPL_H_ diff --git a/src/locales/FLcl_LocaleManagerImpl.cpp b/src/locales/FLcl_LocaleManagerImpl.cpp new file mode 100644 index 0000000..f84272c --- /dev/null +++ b/src/locales/FLcl_LocaleManagerImpl.cpp @@ -0,0 +1,510 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** +* @file FLcl_LocaleManagerImpl.cpp +* @brief This is the implementation file for _LocaleManagerImpl class. +*/ +#include +#include +#include +#include +#include + +#include +#include + +#include "FLcl_LocaleImpl.h" +#include "FLcl_TimeZoneImpl.h" +#include "FLcl_LocaleManagerImpl.h" + + +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Locales +{ + +static const int TIMEZONE_MAX = 224; +static const char* TimeZoneList[TIMEZONE_MAX] = +{ + "Africa/Abidjan", + "Africa/Accra", + "Africa/Addis_Ababa", + "Africa/Algiers", + "Africa/Asmara", + "Africa/Bamako", + "Africa/Bangui", + "Africa/Bissau", + "Africa/Cairo", + "Africa/Casablanca", + "Africa/Conakry", + "Africa/Dakar", + "Africa/Dar_es_Salaam", + "Africa/Djibouti", + "Africa/Douala", + "Africa/Freetown", + "Africa/Gaborone", + "Africa/Harare", + "Africa/Johannesburg", + "Africa/Kampala", + "Africa/Khartoum", + "Africa/Kinshasa", + "Africa/Lagos", + "Africa/Luanda", + "Africa/Lubumbashi", + "Africa/Lusaka", + "Africa/Malabo", + "Africa/Maputo", + "Africa/Mogadishu", + "Africa/Monrovia", + "Africa/Nairobi", + "Africa/Ndjamena", + "Africa/Niamey", + "Africa/Nouakchott", + "Africa/Ouagadougou", + "Africa/Tripoli", + "Africa/Tunis", + "America/Anchorage", + "America/Antigua", + "America/Argentina/Buenos_Aires", + "America/Asuncion", + "America/Barbados", + "America/Belize", + "America/Bogota", + "America/Caracas", + "America/Cayenne", + "America/Chicago", + "America/Costa_Rica", + "America/Denver", + "America/Detroit", + "America/El_Salvador", + "America/Godthab", + "America/Guadeloupe", + "America/Guatemala", + "America/Guayaquil", + "America/Guyana", + "America/Halifax", + "America/Havana", + "America/Indiana/Indianapolis", + "America/Jamaica", + "America/Kentucky/Louisville", + "America/La_Paz", + "America/Lima", + "America/Los_Angeles", + "America/Managua", + "America/Marigot", + "America/Martinique", + "America/Mazatlan", + "America/Mexico_City", + "America/Montevideo", + "America/Montreal", + "America/New_York", + "America/Nome", + "America/Panama", + "America/Paramaribo", + "America/Phoenix", + "America/Port-au-Prince", + "America/Puerto_Rico", + "America/Recife", + "America/Regina", + "America/Santiago", + "America/Santo_Domingo", + "America/Sao_Paulo", + "America/St_Johns", + "America/St_Thomas", + "America/Tegucigalpa", + "America/Tijuana", + "America/Toronto", + "America/Tortola", + "America/Vancouver", + "America/Winnipeg", + "Asia/Aden", + "Asia/Almaty", + "Asia/Amman", + "Asia/Anadyr", + "Asia/Ashgabat", + "Asia/Baghdad", + "Asia/Bahrain", + "Asia/Baku", + "Asia/Bangkok", + "Asia/Beirut", + "Asia/Bishkek", + "Asia/Colombo", + "Asia/Damascus", + "Asia/Dhaka", + "Asia/Dubai", + "Asia/Dushanbe", + "Asia/Ho_Chi_Minh", + "Asia/Hong_Kong", + "Asia/Hovd", + "Asia/Irkutsk", + "Asia/Istanbul", + "Asia/Jakarta", + "Asia/Jayapura", + "Asia/Jerusalem", + "Asia/Kabul", + "Asia/Kamchatka", + "Asia/Karachi", + "Asia/Kathmandu", + "Asia/Kolkata", + "Asia/Krasnoyarsk", + "Asia/Kuala_Lumpur", + "Asia/Kuwait", + "Asia/Macau", + "Asia/Magadan", + "Asia/Makassar", + "Asia/Manila", + "Asia/Muscat", + "Asia/Novokuznetsk", + "Asia/Novosibirsk", + "Asia/Omsk", + "Asia/Phnom_Penh", + "Asia/Pyongyang", + "Asia/Qatar", + "Asia/Rangoon", + "Asia/Riyadh", + "Asia/Sakhalin", + "Asia/Seoul", + "Asia/Shanghai", + "Asia/Singapore", + "Asia/Taipei", + "Asia/Tashkent", + "Asia/Tbilisi", + "Asia/Tehran", + "Asia/Tokyo", + "Asia/Ulan_Bator", + "Asia/Vladivostok", + "Asia/Yakutsk", + "Asia/Yekaterinburg", + "Asia/Yerevan", + "Atlantic/Azores", + "Atlantic/Canary", + "Atlantic/Reykjavik", + "Atlantic/South_Georgia", + "Australia/Adelaide", + "Australia/Brisbane", + "Australia/Canberra", + "Australia/Darwin", + "Australia/Hobart", + "Australia/Melbourne", + "Australia/Perth", + "Australia/Sydney", + "CST6CDT", + "EST5EDT", + "Europe/Amsterdam", + "Europe/Athens", + "Europe/Belgrade", + "Europe/Berlin", + "Europe/Bratislava", + "Europe/Brussels", + "Europe/Bucharest", + "Europe/Budapest", + "Europe/Chisinau", + "Europe/Copenhagen", + "Europe/Dublin", + "Europe/Helsinki", + "Europe/Istanbul", + "Europe/Kaliningrad", + "Europe/Kiev", + "Europe/Lisbon", + "Europe/Ljubljana", + "Europe/London", + "Europe/Luxembourg", + "Europe/Madrid", + "Europe/Malta", + "Europe/Minsk", + "Europe/Moscow", + "Europe/Paris", + "Europe/Podgorica", + "Europe/Prague", + "Europe/Riga", + "Europe/Rome", + "Europe/Samara", + "Europe/San_Marino", + "Europe/Skopje", + "Europe/Sofia", + "Europe/Stockholm", + "Europe/Tallinn", + "Europe/Vaduz", + "Europe/Vienna", + "Europe/Vilnius", + "Europe/Volgograd", + "Europe/Warsaw", + "Europe/Zagreb", + "Europe/Zurich", + "Indian/Antananarivo", + "Indian/Chagos", + "Indian/Maldives", + "Indian/Mauritius", + "Indian/Reunion", + "MST7MDT", + "Pacific/Auckland", + "Pacific/Easter", + "Pacific/Fiji", + "Pacific/Galapagos", + "Pacific/Guam", + "Pacific/Honolulu", + "Pacific/Midway", + "Pacific/Noumea", + "Pacific/Pago_Pago", + "Pacific/Tahiti", + "Pacific/Tarawa", + "Pacific/Tongatapu", + "PST8PDT" +}; + +Locale +_LocaleManagerImpl::GetSystemLocale(void) +{ + char* pRegionPtr; + if (runtime_info_get_value_string(RUNTIME_INFO_KEY_REGION, &pRegionPtr) == RUNTIME_INFO_ERROR_NONE) + { + SetLastResult(E_SUCCESS); + + Locale ospLoc = _LocaleImpl(pRegionPtr).GetOspLocale(); + free(pRegionPtr); + return ospLoc; + } + + SetLastResult(E_SYSTEM); + return Locale(LANGUAGE_INVALID, COUNTRY_INVALID, null); +} + +IList* +_LocaleManagerImpl::GetAvailableLocalesN(void) +{ + result r = E_SUCCESS; + int count = 0; + const U_ICU_NAMESPACE::Locale* pIcuLocaleList = U_ICU_NAMESPACE::Locale::getAvailableLocales(count); + SysTryReturn(NID_LCL, count > 0, null, E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.", GetErrorMessage(E_SYSTEM)); + + std::unique_ptr pAvailableLocaleList(new (std::nothrow) LinkedList()); + SysTryReturn(NID_LCL, pAvailableLocaleList, null, E_OUT_OF_MEMORY, + "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < count; i++) + { + SysTryReturn(NID_LCL, (pIcuLocaleList + i) != null, null, E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.",GetErrorMessage(E_SYSTEM)); + + Locale ospLocale = _LocaleImpl(*(pIcuLocaleList + i)).GetOspLocale(); + if (ospLocale.GetLanguageCode() != LANGUAGE_INVALID && ospLocale.GetCountryCode() != COUNTRY_INVALID) + { + Locale* pLocale = new (std::nothrow) Locale(ospLocale); + SysTryReturn(NID_LCL, pLocale, null, E_OUT_OF_MEMORY, + "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + if (!pAvailableLocaleList->Contains(*pLocale)) + { + r = pAvailableLocaleList->Add(*pLocale); + if (IsFailed(r)) + { + delete pLocale; + SetLastResult(E_SYSTEM); + return null; + } + } + } + } + + SetLastResult(E_SUCCESS); + return pAvailableLocaleList.release(); +} + +String +_LocaleManagerImpl::GetSelectedLanguage(void) +{ + char* pLanguagePtr; + + int ret = runtime_info_get_value_string(RUNTIME_INFO_KEY_LANGUAGE, &pLanguagePtr); + SysTryReturn(NID_LCL, ret == RUNTIME_INFO_ERROR_NONE, String(), E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.", GetErrorMessage(E_SYSTEM)); + String language(_LocaleImpl(pLanguagePtr).Get3LetterCountryCodeString()); + free(pLanguagePtr); + + return language; +} + +IList* +_LocaleManagerImpl::GetAvailableLanguagesN(void) +{ + result r = E_SUCCESS; + std::unique_ptr pLocaleList (GetAvailableLocalesN()); + std::unique_ptr pLanguageMap(new (std::nothrow) HashMap()); + + SysTryReturn(NID_LCL, pLanguageMap, null, E_OUT_OF_MEMORY,"[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + pLanguageMap->Construct(); + + for (int i = 0; i < pLocaleList->GetCount() ; i++) + { + Locale* pLocale = (Locale*)pLocaleList->GetAt(i); + std::unique_ptr pLanguageCode(new (std::nothrow) String(pLocale->GetLanguageCodeString())); + SysTryReturn(NID_LCL, pLanguageCode, null, E_OUT_OF_MEMORY,"[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + if (!pLanguageMap->ContainsKey(*pLanguageCode)) + { + std::unique_ptr pDummyValue(new (std::nothrow) String()); + SysTryReturn(NID_LCL, pDummyValue, null, E_OUT_OF_MEMORY,"[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pLanguageMap->Add(*(pLanguageCode.get()), *(pDummyValue.get())); + + if (IsFailed(r)) + { + SetLastResult(E_UNSUPPORTED_OPERATION); + return null; + } + pLanguageCode.release(); + pDummyValue.release(); + } + } + + IList* pAvailableLanguageList; + pAvailableLanguageList = pLanguageMap->GetKeysN(); + SetLastResult(E_SUCCESS); + pLanguageMap->RemoveAll(); + return pAvailableLanguageList; +} + + +IMap* +_LocaleManagerImpl::GetAvailableTimeZonesN(U_ICU_NAMESPACE::StringEnumeration* pIcuTZStrList) +{ + SysTryReturn(NID_LCL, pIcuTZStrList, null, E_SYSTEM, + "[%s] The method cannot proceed due to a severe system error.",GetErrorMessage(E_SYSTEM)); + + std::unique_ptr pTimeZoneMap(new (std::nothrow) HashMap()); + + SysTryReturn(NID_LCL, pTimeZoneMap, null, E_OUT_OF_MEMORY, + "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + pTimeZoneMap->Construct(); + result r = E_SUCCESS; + int resultLength = -1; + UErrorCode ec = U_ZERO_ERROR; + const char* pIcuTZStr = pIcuTZStrList->next(&resultLength, ec); + IMap* pTZMap = GetAvailableTimeZonesN(); + + r = GetLastResult(); + SysTryReturn(NID_LCL, pTZMap, null, r, "[%s] Fail to get available time zone list", GetErrorMessage(r)); + + while (pIcuTZStr != null) + { + String* pTimeZone = new (std::nothrow) String(pIcuTZStr); + SysTryReturn(NID_LCL, pTimeZone, null, E_OUT_OF_MEMORY, + "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + if (!pTimeZoneMap->ContainsKey(*pTimeZone) && pTZMap->ContainsKey(*pTimeZone)) + { + String* pDummyValue = new (std::nothrow) String(); + r = pTimeZoneMap->Add(*pTimeZone, *pDummyValue); + if (IsFailed(r)) + { + delete pTimeZone; + delete pDummyValue; + pTZMap->RemoveAll(); + SetLastResult(E_SYSTEM); + return null; + } + } + + pIcuTZStr = pIcuTZStrList->next(&resultLength, ec); + } + SetLastResult(E_SUCCESS); + pTZMap->RemoveAll(); + return pTimeZoneMap.release(); +} + +IMap* +_LocaleManagerImpl::GetAvailableTimeZonesN(void) +{ + std::unique_ptr pTimeZoneMap(new (std::nothrow) HashMap()); + + SysTryReturn(NID_LCL, pTimeZoneMap, null, E_OUT_OF_MEMORY, + "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = E_SUCCESS; + int index = 0; + + pTimeZoneMap->Construct(); + + do + { + String* pTimeZone = new (std::nothrow) String(TimeZoneList[index++]); + SysTryReturn(NID_LCL, pTimeZone, null, E_OUT_OF_MEMORY, + "[%s] Memory allocation failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + if (!pTimeZoneMap->ContainsKey(*pTimeZone)) + { + String* pDummyValue = new (std::nothrow) String(); + + r = pTimeZoneMap->Add(*pTimeZone, *pDummyValue); + if (IsFailed(r)) + { + delete pTimeZone; + delete pDummyValue; + SetLastResult(E_SYSTEM); + return null; + } + } + }while (index < TIMEZONE_MAX); + + SetLastResult(E_SUCCESS); + return pTimeZoneMap.release(); +} + +IMap* +_LocaleManagerImpl::GetAvailableTimeZonesN(int rawOffset) +{ + return GetAvailableTimeZonesN(U_ICU_NAMESPACE::TimeZone::createEnumeration(rawOffset * _TimeZoneImpl::ONE_MIN_IN_MILLISEC)); +} + + +TimeZone +_LocaleManagerImpl::GetSystemTimeZone(void) +{ + char tz[PATH_MAX + 1]; + int len = readlink("/opt/etc/localtime", tz, PATH_MAX); + std::unique_ptr pTzICU(null); + if (len > 20) + { + tz[len] = '\0'; + pTzICU.reset(U_ICU_NAMESPACE::TimeZone::createTimeZone(tz + 20)); + } + else + { + pTzICU.reset(U_ICU_NAMESPACE::TimeZone::createDefault()); + } + + if (pTzICU.get()) + { + _TimeZoneImpl tzImpl(*pTzICU.get(), U_ICU_NAMESPACE::Calendar::getNow()); + return tzImpl.GetOspTimeZone(); + } + + return TimeZone(-1, ""); +} + +result +_LocaleManagerImpl::IsSupportedLocale(const Tizen::Locales::Locale& locale, bool& isSupportedLocale) +{ + isSupportedLocale = _LocaleImpl::GetLocaleImpl(locale)->IsLocaleSupported(); + return E_SUCCESS; +} + +}; +}; // Tizen::Locales diff --git a/src/locales/FLcl_NumberFormatterImpl.cpp b/src/locales/FLcl_NumberFormatterImpl.cpp new file mode 100644 index 0000000..d618860 --- /dev/null +++ b/src/locales/FLcl_NumberFormatterImpl.cpp @@ -0,0 +1,334 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclNumberFormatterEx.cpp + * @brief This is the implementation file for the NumberFormatterEx class. + */ + +#include +#include + +#include +#include + +#include "FLcl_LocaleData.h" +#include "FLcl_LocaleImpl.h" +#include "FLcl_NumberFormatterImpl.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +_NumberFormatterImpl::_NumberFormatterImpl(void) + : __pIcuNumberFormatter(null) +{ +} + +_NumberFormatterImpl::~_NumberFormatterImpl(void) +{ + delete __pIcuNumberFormatter; +} + +NumberFormatter* +_NumberFormatterImpl::CreateNumberFormatterN(NumberFormatterStyle style) +{ + return CreateNumberFormatterN(_LocaleData::GetOspSystemLocale(), style); +} + +NumberFormatter* +_NumberFormatterImpl::CreateNumberFormatterN(const Locale& locale, NumberFormatterStyle style) +{ + IcuLocale icuLocale = _LocaleImpl::GetLocaleImpl(locale)->GetIcuLocale(); + SysTryReturn(NID_LCL, !icuLocale.isBogus(), null, E_UNSUPPORTED_OPERATION, + "[%s] Given locale is not supported", GetErrorMessage(E_UNSUPPORTED_OPERATION)); + + std::unique_ptr pNewFormatter(new (std::nothrow) NumberFormatter); + SysTryReturn(NID_LCL, pNewFormatter, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + std::unique_ptr<_NumberFormatterImpl> pNumberFormatterImpl(new (std::nothrow) _NumberFormatterImpl); + SysTryReturn(NID_LCL, pNumberFormatterImpl, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation failed"); + + UNumberFormatStyle icuStyle = UNUM_FORMAT_STYLE_COUNT; + switch(style) + { + case NUM_FORMATTER_STYLE_NUMBER: + icuStyle = UNUM_DECIMAL; + break; + case NUM_FORMATTER_STYLE_CURRENCY: + icuStyle = UNUM_CURRENCY; + break; + case NUM_FORMATTER_STYLE_PERCENT: + icuStyle = UNUM_PERCENT; + break; + case NUM_FORMATTER_STYLE_INVALID: + break; + } + + UErrorCode ec = U_ZERO_ERROR; + std::unique_ptr pIcuNumberFormatter(IcuNumberFormat::createInstance(icuLocale, icuStyle, ec)); + if (pIcuNumberFormatter) + { + IcuDecimalFormat* pDecimalFmt = dynamic_cast(pIcuNumberFormatter.get()); + if (pDecimalFmt) + { + pIcuNumberFormatter.release(); + pNumberFormatterImpl->__pIcuNumberFormatter = pDecimalFmt; + pNumberFormatterImpl->__currency.Construct(locale); + pNewFormatter->__pNumberFormatterImpl = pNumberFormatterImpl.release(); + + SetLastResult(E_SUCCESS); + return pNewFormatter.release(); + } + } + + SetLastResult(E_INVALID_ARG); + return null; +} + +result +_NumberFormatterImpl::ApplyPattern(const String& pattern, bool localized) +{ + UErrorCode ec = U_ZERO_ERROR; + if (localized) + { + __pIcuNumberFormatter->applyLocalizedPattern(_LocaleData::GetIcuString(pattern), ec); + } + else + { + __pIcuNumberFormatter->applyPattern(_LocaleData::GetIcuString(pattern), ec); + } + + return U_SUCCESS(ec) ? E_SUCCESS : E_INVALID_ARG; +} + +result +_NumberFormatterImpl::Format(long number, String& str, _FieldPosition pos) const +{ + IcuUnicodeString icuStr; + IcuFieldPosition icuPos = _LocaleData::GetIcuFieldPosition(pos); + icuStr = __pIcuNumberFormatter->format((int64_t)number, icuStr, icuPos); + str = _LocaleData::GetOspString(icuStr); + return E_SUCCESS; +} + +result +_NumberFormatterImpl::Format(double number, String& str, _FieldPosition pos) const +{ + IcuUnicodeString icuStr; + IcuFieldPosition icuPos = _LocaleData::GetIcuFieldPosition(pos); + icuStr = __pIcuNumberFormatter->format(number, icuStr, icuPos); + str = _LocaleData::GetOspString(icuStr); + return E_SUCCESS; +} + +const Currency* +_NumberFormatterImpl::GetCurrency(void) +{ + return &__currency; +} + +void +_NumberFormatterImpl::SetCurrency(const Currency& newValue) +{ + __currency.Construct(newValue.GetCurrencyCode()); + __pIcuNumberFormatter->setCurrency(_LocaleData::GetIcuString(newValue.GetCurrencyCode()).getBuffer()); +} + +int +_NumberFormatterImpl::GetMaxIntegerDigits(void) const +{ + return __pIcuNumberFormatter->getMaximumIntegerDigits(); +} + +void +_NumberFormatterImpl::SetMaxIntegerDigits(int newValue) +{ + __pIcuNumberFormatter->setMaximumIntegerDigits(newValue); +} + +int +_NumberFormatterImpl::GetMinIntegerDigits(void) const +{ + return __pIcuNumberFormatter->getMinimumIntegerDigits(); +} + +void +_NumberFormatterImpl::SetMinIntegerDigits(int newValue) +{ + __pIcuNumberFormatter->setMinimumIntegerDigits(newValue); +} + +int +_NumberFormatterImpl::GetMaxFractionDigits(void) const +{ + return __pIcuNumberFormatter->getMaximumFractionDigits(); +} + +void +_NumberFormatterImpl::SetMaxFractionDigits(int newValue) +{ + __pIcuNumberFormatter->setMaximumFractionDigits(newValue); +} + +int +_NumberFormatterImpl::GetMinFractionDigits(void) const +{ + return __pIcuNumberFormatter->getMinimumFractionDigits(); +} + +void +_NumberFormatterImpl::SetMinFractionDigits(int newValue) +{ + __pIcuNumberFormatter->setMinimumFractionDigits(newValue); +} + +bool +_NumberFormatterImpl::IsGroupingUsed(void) const +{ + return __pIcuNumberFormatter->isGroupingUsed(); +} + +void +_NumberFormatterImpl::SetGroupingUsed(bool newValue) +{ + __pIcuNumberFormatter->setGroupingUsed(newValue); +} + +String +_NumberFormatterImpl::GetPositivePrefix(void) const +{ + IcuUnicodeString icuStr; + return _LocaleData::GetOspString(__pIcuNumberFormatter->getPositivePrefix(icuStr)); +} + +void +_NumberFormatterImpl::SetPositivePrefix(const String& newValue) +{ + __pIcuNumberFormatter->setPositivePrefix(_LocaleData::GetIcuString(newValue)); +} + +String +_NumberFormatterImpl::GetNegativePrefix(void) const +{ + IcuUnicodeString icuStr; + return _LocaleData::GetOspString(__pIcuNumberFormatter->getNegativePrefix(icuStr)); +} + +void +_NumberFormatterImpl::SetNegativePrefix(const String& newValue) +{ + __pIcuNumberFormatter->setNegativePrefix(_LocaleData::GetIcuString(newValue)); +} + +String +_NumberFormatterImpl::GetPositiveSuffix(void) const +{ + IcuUnicodeString icuStr; + return _LocaleData::GetOspString(__pIcuNumberFormatter->getPositiveSuffix(icuStr)); +} + +void +_NumberFormatterImpl::SetPositiveSuffix(const String& newValue) +{ + __pIcuNumberFormatter->setPositiveSuffix(_LocaleData::GetIcuString(newValue)); +} + +String +_NumberFormatterImpl::GetNegativeSuffix(void) const +{ + IcuUnicodeString icuStr; + return _LocaleData::GetOspString(__pIcuNumberFormatter->getNegativeSuffix(icuStr)); +} + +void +_NumberFormatterImpl::SetNegativeSuffix(const String& newValue) +{ + __pIcuNumberFormatter->setNegativeSuffix(_LocaleData::GetIcuString(newValue)); +} + +int +_NumberFormatterImpl::GetMultiplier(void) const +{ + return __pIcuNumberFormatter->getMultiplier(); +} + +result +_NumberFormatterImpl::SetMultiplier(int newValue) +{ + __pIcuNumberFormatter->setMultiplier(newValue); + return E_SUCCESS; +} + +int +_NumberFormatterImpl::GetGroupingSize(void) const +{ + return __pIcuNumberFormatter->getGroupingSize(); +} + +result +_NumberFormatterImpl::SetGroupingSize(int newValue) +{ + __pIcuNumberFormatter->setGroupingSize(newValue); + return E_SUCCESS; +} + +bool +_NumberFormatterImpl::IsDecimalSeparatorAlwaysShown(void) const +{ + return __pIcuNumberFormatter->isDecimalSeparatorAlwaysShown(); +} + +void +_NumberFormatterImpl::SetDecimalSeparatorAlwaysShown(bool newValue) +{ + __pIcuNumberFormatter->setDecimalSeparatorAlwaysShown(newValue); +} + +bool +_NumberFormatterImpl::IsPositiveSignAlwaysShown(void) const +{ + IcuUnicodeString ps("+"); + IcuUnicodeString pp; + pp = __pIcuNumberFormatter->getPositivePrefix(pp); + + return (pp == ps); +} + +void +_NumberFormatterImpl::SetPositiveSignAlwaysShown(bool newValue) +{ + IcuUnicodeString ps("+"); + IcuUnicodeString pp; + pp = __pIcuNumberFormatter->getPositivePrefix(pp); + + if (newValue) + { + __pIcuNumberFormatter->setPositivePrefix(ps); + } + else + { + if (pp == ps) + { + __pIcuNumberFormatter->setPositivePrefix(""); + } + } +} + +} } // Tizen::Locales diff --git a/src/locales/FLcl_NumberFormatterImpl.h b/src/locales/FLcl_NumberFormatterImpl.h new file mode 100644 index 0000000..cf89534 --- /dev/null +++ b/src/locales/FLcl_NumberFormatterImpl.h @@ -0,0 +1,159 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_NumberFormatterImpl.h + * @brief This is the header file for the _NumberFormatterImpl class. + */ + +#ifndef _FLCL_INTERNAL_NUMBER_FORMATTER_IMPL_H_ +#define _FLCL_INTERNAL_NUMBER_FORMATTER_IMPL_H_ + +#include +#include +#include +#include "FLcl_FieldPosition.h" + +namespace U_ICU_NAMESPACE +{ +class DecimalFormat; +} + +namespace Tizen { namespace Locales +{ + +// forward declaration +class NumberFormatter; +class _LocaleData; + +enum NumberFormatterStyle +{ + NUM_FORMATTER_STYLE_NUMBER, + NUM_FORMATTER_STYLE_CURRENCY, + NUM_FORMATTER_STYLE_PERCENT, + NUM_FORMATTER_STYLE_INVALID + +}; + +enum NumberFormatterAttributes +{ + NUM_FORMATTER_FIELD_CURRENCY, + NUM_FORMATTER_FIELD_POSITIVE_PREFIX, + NUM_FORMATTER_FIELD_NEGATIVE_PREFIX, + NUM_FORMATTER_FIELD_POSITIVE_SUFFIX, + NUM_FORMATTER_FIELD_NEGATIVE_SUFFIX, + NUM_FORMATTER_FIELD_PATTERN, + NUM_FORMATTER_FIELD_LOCALIZED_PATTERN, + NUM_FORMATTER_FIELD_STRING_VALUE_END, + + NUM_FORMATTER_FIELD_MAX_INTEGER_DIGITS, + NUM_FORMATTER_FIELD_MIN_INTEGER_DIGITS, + NUM_FORMATTER_FIELD_MAX_FRACTION_DIGITS, + NUM_FORMATTER_FIELD_MIN_FRACTION_DIGITS, + NUM_FORMATTER_FIELD_MIN_EXPONENT_DIGITS, + NUM_FORMATTER_FIELD_MULTIPLIER, + NUM_FORMATTER_FIELD_GROUPING_SIZE, + NUM_FORMATTER_FIELD_INT_VALUE_END, + + NUM_FORMATTER_FIELD_IS_GROUPING_USED, + NUM_FORMATTER_FIELD_IS_DECIMAL_SEPARATOR_ALWAYS_SHOWN, + NUM_FORMATTER_FIELD_IS_POSITIVE_SIGN_ALWAYS_SHOWN, + NUM_FORMATTER_FIELD_BOOL_VALUE_END, + + NUM_FORMATTER_FIELD_INVALID +}; + +/** + * @class _NumberFormatterImpl + * @brief This class is for Number formatting. + * @since 1.1 + * + */ + +class _NumberFormatterImpl + : public Tizen::Base::Object +{ +public: + + _NumberFormatterImpl(void); + virtual ~_NumberFormatterImpl(void); + + +public: + static NumberFormatter* CreateNumberFormatterN(NumberFormatterStyle style = NUM_FORMATTER_STYLE_NUMBER); + static NumberFormatter* CreateNumberFormatterN(const Locale& locale, NumberFormatterStyle style = NUM_FORMATTER_STYLE_NUMBER); + + result ApplyPattern(const Tizen::Base::String& pattern, bool localized); + + result Format(long number, Tizen::Base::String& str, _FieldPosition pos = 0) const; + result Format(double number, Tizen::Base::String& str, _FieldPosition pos = 0) const; + + const Currency* GetCurrency(void); + void SetCurrency(const Currency& newValue); + + virtual int GetMaxIntegerDigits(void) const; + virtual void SetMaxIntegerDigits(int newValue); + + virtual int GetMinIntegerDigits(void) const; + virtual void SetMinIntegerDigits(int newValue); + + virtual int GetMaxFractionDigits(void) const; + virtual void SetMaxFractionDigits(int newValue); + + virtual int GetMinFractionDigits(void) const; + virtual void SetMinFractionDigits(int newValue); + + virtual bool IsGroupingUsed(void) const; + virtual void SetGroupingUsed(bool newValue); + + Tizen::Base::String GetPositivePrefix(void) const; + void SetPositivePrefix(const Tizen::Base::String& newValue); + + Tizen::Base::String GetNegativePrefix(void) const; + void SetNegativePrefix(const Tizen::Base::String& newValue); + + Tizen::Base::String GetPositiveSuffix(void) const; + void SetPositiveSuffix(const Tizen::Base::String& newValue); + + Tizen::Base::String GetNegativeSuffix(void) const; + void SetNegativeSuffix(const Tizen::Base::String& newValue); + + int GetMultiplier(void) const; + result SetMultiplier(int newValue); + + int GetGroupingSize(void) const; + result SetGroupingSize(int newValue); + + bool IsDecimalSeparatorAlwaysShown(void) const; + void SetDecimalSeparatorAlwaysShown(bool newValue); + + bool IsPositiveSignAlwaysShown(void) const; + void SetPositiveSignAlwaysShown(bool newValue); + +private: + _NumberFormatterImpl(const _NumberFormatterImpl& numberFormatterImpl); + _NumberFormatterImpl& operator =(const _NumberFormatterImpl& numberFormatterImpl); + + Currency __currency; + U_ICU_NAMESPACE::DecimalFormat* __pIcuNumberFormatter; + +}; // _NumberFormatterImpl + +}} // Tizen::Locales + +#endif //_FLCL_INTERNAL_NUMBER_FORMATTER_IMPL_H_ + diff --git a/src/locales/FLcl_NumberSymbolsImpl.cpp b/src/locales/FLcl_NumberSymbolsImpl.cpp new file mode 100644 index 0000000..9300b7c --- /dev/null +++ b/src/locales/FLcl_NumberSymbolsImpl.cpp @@ -0,0 +1,123 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLclNumberSymbols.cpp + * @brief This is the implementation file for NumberSymbols class. + */ + +#include +#include +#include "FLcl_NumberSymbolsImpl.h" +#include "FLcl_LocaleData.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// Public Method + +_NumberSymbolsImpl::_NumberSymbolsImpl(void) + : __locale(LANGUAGE_INVALID, COUNTRY_INVALID) +{ +} + + +_NumberSymbolsImpl::_NumberSymbolsImpl(const _NumberSymbolsImpl& other) + : __locale(LANGUAGE_INVALID, COUNTRY_INVALID) +{ + this->__locale = other.__locale; + + for (int i = 0; i < NUMBER_SYMBOL_COUNT; i++) + { + this->__symbols[i] = other.__symbols[i]; // Copying symbols + } +} + + +_NumberSymbolsImpl& +_NumberSymbolsImpl::operator =(const _NumberSymbolsImpl& rhs) +{ + if (this != &rhs) + { + for (int i = 0; i < (int) NUMBER_SYMBOL_COUNT; ++i) + { + __symbols[(NumberSymbol) i] = rhs.__symbols[(NumberSymbol) i]; // Copying symbols + } + + __locale = rhs.__locale; + } + + return *this; +} + + +_NumberSymbolsImpl::~_NumberSymbolsImpl(void) +{ +} + +result +_NumberSymbolsImpl::Construct(const Locale& locale) +{ + result r = E_SUCCESS; + _LocaleData localeData; + r = localeData.GetNumberSymbols(locale, __symbols); // Get number symbols from ICU + + if (!IsFailed(r)) + { + __locale = locale; + return E_SUCCESS; + } + + return (Tizen::App::_AppInfo::GetApiVersion() == _API_VERSION_2_0 && Tizen::App::_AppInfo::IsOspCompat()) ? E_UNSUPPORTED_OPERATION : E_INVALID_ARG; +} + + +String +_NumberSymbolsImpl::GetNumberSymbol(NumberSymbol symbol) const +{ + return (symbol < NUMBER_SYMBOL_COUNT) ? __symbols[symbol] : String(); // Get symbol value for symbol +} + + +result +_NumberSymbolsImpl::SetNumberSymbol(const NumberSymbol symbol, const String& str) +{ + if (symbol < NUMBER_SYMBOL_COUNT) // validate symbol value + { + __symbols[symbol] = str; // Set symbol + } + + return E_SUCCESS; +} + + +const Locale* +_NumberSymbolsImpl::GetLocale(void) const +{ + ClearLastResult(); + return &__locale; // return locale object stored during construction +} + + +}; +}; // Tizen::Locales + diff --git a/src/locales/FLcl_NumberSymbolsImpl.h b/src/locales/FLcl_NumberSymbolsImpl.h new file mode 100644 index 0000000..7bb9a11 --- /dev/null +++ b/src/locales/FLcl_NumberSymbolsImpl.h @@ -0,0 +1,66 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_NumberSymbolsImpl.h + * @brief This is the header file for the _NumberSymbolsImpl class. + * + * This header file contains declarations of the _NumberSymbolsImpl class. + * + */ +#ifndef _FLCL_INTERNAL_NUMBER_SYMBOLS_IMPL_H_ +#define _FLCL_INTERNAL_NUMBER_SYMBOLS_IMPL_H_ + +// Includes +#include +#include + + +namespace Tizen { namespace Locales +{ + +class _NumberSymbolsImpl + : public Tizen::Base::Object +{ +// Construct Operations +public: + _NumberSymbolsImpl(void); + virtual ~_NumberSymbolsImpl(void); + + _NumberSymbolsImpl(const _NumberSymbolsImpl& other); + _NumberSymbolsImpl& operator =(const _NumberSymbolsImpl& other); + + +// Operations +public: + result Construct(const Locale& locale); + Tizen::Base::String GetNumberSymbol(NumberSymbol symbol) const; + result SetNumberSymbol(NumberSymbol symbol, const Tizen::Base::String& str); + const Locale* GetLocale(void) const; + + +// Attribute +private: + Locale __locale; + Tizen::Base::String __symbols[NUMBER_SYMBOL_COUNT]; + +}; // _NumberSymbolsImpl + +}} // Tizen::Locales + +#endif //_FLCL_INTERNAL_NUMBER_SYMBOLS_IMPL_H_ + diff --git a/src/locales/FLcl_TimeZoneImpl.cpp b/src/locales/FLcl_TimeZoneImpl.cpp new file mode 100644 index 0000000..c3658f0 --- /dev/null +++ b/src/locales/FLcl_TimeZoneImpl.cpp @@ -0,0 +1,495 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_TimeZoneImpl.cpp + * @brief This is the implementation file for _TimeZoneImpl class. + */ + +#include + +#include +#include + +#include "FLcl_LocaleData.h" +#include "FLcl_TimeZoneImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Locales +{ + +_TimeZoneImpl::_TimeZoneImpl(void) + : __icuTimeZone(0, "") + , __dstStartingYear(0) + , __startingRule(MONTH_UNDEFINED, DAY_UNDEFINED) + , __endingRule(MONTH_UNDEFINED, DAY_UNDEFINED) +{ + +} + +_TimeZoneImpl::_TimeZoneImpl(int rawOffset, const String& id) + : __icuTimeZone(rawOffset * ONE_MIN_IN_MILLISEC, _LocaleData::GetIcuString(id)) + , __dstStartingYear(0) + , __startingRule(MONTH_UNDEFINED, DAY_UNDEFINED) + , __endingRule(MONTH_UNDEFINED, DAY_UNDEFINED) +{ + +} + +_TimeZoneImpl::_TimeZoneImpl(int rawOffset, const String& id, const TimeRule& startRule, const TimeRule& endRule, int dstOffset) + : __icuTimeZone(rawOffset * ONE_MIN_IN_MILLISEC, _LocaleData::GetIcuString(id)) + , __dstStartingYear(0) + , __startingRule(MONTH_UNDEFINED, DAY_UNDEFINED) + , __endingRule(MONTH_UNDEFINED, DAY_UNDEFINED) +{ + SetDstRules(startRule, endRule, dstOffset); +} + +_TimeZoneImpl::_TimeZoneImpl(const _TimeZoneImpl& otherTimeZone) + : __icuTimeZone(otherTimeZone.__icuTimeZone) + , __dstStartingYear(otherTimeZone.__dstStartingYear) + , __startingRule(otherTimeZone.__startingRule) + , __endingRule(otherTimeZone.__endingRule) +{ +} + +_TimeZoneImpl::_TimeZoneImpl(U_ICU_NAMESPACE::TimeZone& icuTimeZone) + : __icuTimeZone(0, "") + , __dstStartingYear(0) + , __startingRule(MONTH_UNDEFINED, DAY_UNDEFINED) + , __endingRule(MONTH_UNDEFINED, DAY_UNDEFINED) +{ + U_ICU_NAMESPACE::UnicodeString id; + __icuTimeZone.setID(icuTimeZone.getID(id)); + __icuTimeZone.setRawOffset(icuTimeZone.getRawOffset()); +} + +_TimeZoneImpl::_TimeZoneImpl(U_ICU_NAMESPACE::TimeZone& icuTimeZone, UDate icuDate) + : __icuTimeZone(0, "") + , __dstStartingYear(0) + , __startingRule(MONTH_UNDEFINED, DAY_UNDEFINED) + , __endingRule(MONTH_UNDEFINED, DAY_UNDEFINED) +{ + U_ICU_NAMESPACE::UnicodeString id; + __icuTimeZone.setID(icuTimeZone.getID(id)); + __icuTimeZone.setRawOffset(icuTimeZone.getRawOffset()); + + U_ICU_NAMESPACE::BasicTimeZone* pIcuTz = dynamic_cast(&icuTimeZone); + if (pIcuTz) + { + TimeRule startingRule(MONTH_UNDEFINED, DAY_UNDEFINED); + TimeRule endingRule(MONTH_UNDEFINED, DAY_UNDEFINED); + + int dstSaving = 0; + UErrorCode status = U_ZERO_ERROR; + U_ICU_NAMESPACE::InitialTimeZoneRule* pInitial = null; + U_ICU_NAMESPACE::AnnualTimeZoneRule* pStd = null; + U_ICU_NAMESPACE::AnnualTimeZoneRule* pDst = null; + pIcuTz->getSimpleRulesNear(icuDate, pInitial, pStd, pDst, status); + if (pStd && pDst) + { + result r = GetTimeRuleFromIcuDateTimeRule(pDst->getRule(), startingRule); + if (r == E_SUCCESS) + { + dstSaving = pIcuTz->getDSTSavings() / ONE_MIN_IN_MILLISEC; + GetTimeRuleFromIcuDateTimeRule(pStd->getRule(), endingRule); + } + + int dstStartingYear = pDst->getStartYear(); + SetDstStartingYear(dstStartingYear); + } + + delete pInitial; + delete pStd; + delete pDst; + SetDstRules(startingRule, endingRule, dstSaving); + } +} + +_TimeZoneImpl* +_TimeZoneImpl::CloneN(void) +{ + return new (std::nothrow) _TimeZoneImpl(*this); +} + +_TimeZoneImpl& +_TimeZoneImpl::operator =(const _TimeZoneImpl& otherTimeZone) +{ + if (*this != otherTimeZone) + { + __icuTimeZone = otherTimeZone.__icuTimeZone; + __dstStartingYear = otherTimeZone.__dstStartingYear; + __startingRule = otherTimeZone.__startingRule; + __endingRule = otherTimeZone.__endingRule; + } + return *this; +} + +_TimeZoneImpl::~_TimeZoneImpl(void) +{ + +} + +U_ICU_NAMESPACE::SimpleTimeZone +_TimeZoneImpl::GetIcuTimeZone(void) const +{ + return __icuTimeZone; +} + +TimeZone +_TimeZoneImpl::GetOspTimeZone(void) +{ + TimeZone ospTimeZone; + ospTimeZone.__pTimeZoneImpl = new (std::nothrow) _TimeZoneImpl(*this); + SysAssert(ospTimeZone.__pTimeZoneImpl); + return ospTimeZone; +} + +bool +_TimeZoneImpl::operator ==(const _TimeZoneImpl& otherTimeZone) const +{ + return __icuTimeZone == otherTimeZone.__icuTimeZone; +} + +bool +_TimeZoneImpl::operator !=(const _TimeZoneImpl& otherTimeZone) const +{ + return !(*this == otherTimeZone); +} + +bool +_TimeZoneImpl::Equals(const Object& obj) const +{ + const _TimeZoneImpl* pTimeZoneImpl = dynamic_cast(&obj); + if (pTimeZoneImpl) + { + return (*this == *pTimeZoneImpl); + } + return false; +} + +int +_TimeZoneImpl::GetHashCode(void) const +{ + int hashCode = GetId().GetHashCode(); + Integer intValues = GetRawOffset() + GetDstSavings() + GetDstStartingYear() + IsDstUsed(); + hashCode = (hashCode << 5) - hashCode + intValues.GetHashCode(); + hashCode = (hashCode << 5) - hashCode + __startingRule.GetHashCode(); + hashCode = (hashCode << 5) - hashCode + __endingRule.GetHashCode(); + + return hashCode; +} + +String +_TimeZoneImpl::GetId(void) const +{ + U_ICU_NAMESPACE::UnicodeString icuStr; + return _LocaleData::GetOspString(__icuTimeZone.getID(icuStr)); +} + +void +_TimeZoneImpl::SetId(const String& id) +{ + U_ICU_NAMESPACE::UnicodeString icuStr = _LocaleData::GetIcuString(id); + __icuTimeZone.setID(icuStr); +} + +int +_TimeZoneImpl::GetRawOffset(void) const +{ + return __icuTimeZone.getRawOffset() / ONE_MIN_IN_MILLISEC; +} + +void +_TimeZoneImpl::SetRawOffset(int rawOffset) +{ + __icuTimeZone.setRawOffset(rawOffset * ONE_MIN_IN_MILLISEC); +} + +int +_TimeZoneImpl::GetDstStartingYear(void) const +{ + return __dstStartingYear; +} + +void +_TimeZoneImpl::SetDstStartingYear(int year) +{ + __dstStartingYear = year; + __icuTimeZone.setStartYear(year); +} + +int +_TimeZoneImpl::GetDstSavings(void) const +{ + return __icuTimeZone.getDSTSavings() / ONE_MIN_IN_MILLISEC; +} + +void +_TimeZoneImpl::SetDstSavings(int dstSavings) +{ + UErrorCode ec = U_ZERO_ERROR; + __icuTimeZone.setDSTSavings(dstSavings * ONE_MIN_IN_MILLISEC, ec); +} + +const TimeRule* +_TimeZoneImpl::GetDstStartingRule(void) const +{ + return __startingRule.GetMonth() != MONTH_UNDEFINED ? &__startingRule : null; +} + +void +_TimeZoneImpl::SetDstStartingRule(const TimeRule& startRule) +{ + int month = 0; + int dayOfWeekInMonth = 0; + int dayOfWeek = 0; + int time = 0; + int mode = 0; + + UErrorCode ec = U_ZERO_ERROR; + GetIcuTimeRuleValue(startRule, month, dayOfWeekInMonth, dayOfWeek, time, mode); + __icuTimeZone.setStartRule(month, dayOfWeekInMonth, dayOfWeek, time, mode, ec); + __startingRule = startRule; +} + +const TimeRule* +_TimeZoneImpl::GetDstEndingRule(void) const +{ + return __endingRule.GetMonth() != MONTH_UNDEFINED ? &__endingRule : null; +} + +void +_TimeZoneImpl::SetDstEndingRule(const TimeRule& endRule) +{ + int month = 0; + int dayOfWeekInMonth = 0; + int dayOfWeek = 0; + int time = 0; + int mode = 0; + + UErrorCode ec = U_ZERO_ERROR; + GetIcuTimeRuleValue(endRule, month, dayOfWeekInMonth, dayOfWeek, time, mode); + __icuTimeZone.setEndRule(month, dayOfWeekInMonth, dayOfWeek, time, mode, ec); + __endingRule = endRule; +} + +result +_TimeZoneImpl::SetDstRules(const TimeRule& startRule, const TimeRule& endRule, int dstSavings) +{ + SysTryReturnResult(NID_LCL, dstSavings >= 0, + E_OUT_OF_RANGE, "dstSavings [%d] should be greater or equal to than 0", dstSavings); + SysTryReturnResult(NID_LCL, dstSavings < ONE_DAY_IN_MINUTE, + E_OUT_OF_RANGE, "dstSavings [%d] should be greater than %d", dstSavings, ONE_DAY_IN_MINUTE); + SetDstStartingRule(startRule); + SetDstEndingRule(endRule); + SetDstSavings(dstSavings); + return E_SUCCESS; +} + +result +_TimeZoneImpl::GetOffset(const DateTime& date, bool local, int& rawOffset, int& dstOffset) const +{ + UErrorCode ec = U_ZERO_ERROR; + __icuTimeZone.getOffset(_LocaleData::GetIcuDate(date), local, rawOffset, dstOffset, ec); + rawOffset /= ONE_MIN_IN_MILLISEC; + dstOffset /= ONE_MIN_IN_MILLISEC; + return U_SUCCESS(ec) ? E_SUCCESS : E_INVALID_ARG; +} + +result +_TimeZoneImpl::GetOffset(long long ticks, int& offset) const +{ + TimeSpan ts(ticks); + DateTime date; + date.SetValue(ts.GetTicks()); + + int rawOffset = 0; + int dstOffset = 0; + UErrorCode ec = U_ZERO_ERROR; + __icuTimeZone.getOffset(_LocaleData::GetIcuDate(date), false, rawOffset, dstOffset, ec); + offset = (rawOffset + dstOffset) / ONE_MIN_IN_MILLISEC; + return U_SUCCESS(ec) ? E_SUCCESS : E_INVALID_ARG; +} + +bool +_TimeZoneImpl::IsDstUsed(void) const +{ + return __icuTimeZone.useDaylightTime(); +} + +const _TimeZoneImpl* +_TimeZoneImpl::GetTimeZoneImpl(const TimeZone& ospTimeZone) +{ + return ospTimeZone.__pTimeZoneImpl; +} + +result +_TimeZoneImpl::GetTimeZone(const String& id, Tizen::Locales::TimeZone& timeZone) +{ + U_ICU_NAMESPACE::UnicodeString icuStr = _LocaleData::GetIcuString(id); + std::unique_ptr pIcuTimeZone(U_ICU_NAMESPACE::TimeZone::createTimeZone(icuStr)); + SysTryReturnResult(NID_LCL, pIcuTimeZone != null, E_INVALID_ARG, "Unable to create ICU timezone"); + + U_ICU_NAMESPACE::UnicodeString retIcuStr; + SysTryReturnResult(NID_LCL, pIcuTimeZone->getID(retIcuStr) == icuStr, + E_INVALID_ARG, "Unsupported timezone id [%ls]", id.GetPointer()); + + U_ICU_NAMESPACE::SimpleTimeZone icuTimeZone(pIcuTimeZone->getRawOffset(), icuStr); + std::unique_ptr<_TimeZoneImpl> pTimeZoneImpl(new (std::nothrow) _TimeZoneImpl(icuTimeZone)); + if (pTimeZoneImpl) + { + delete timeZone.__pTimeZoneImpl; + timeZone.__pTimeZoneImpl = pTimeZoneImpl.release(); + return E_SUCCESS; + } + + return E_INVALID_ARG; +} + +result +_TimeZoneImpl::GetTimeZone(const String& id, const DateTime& utcTime, Tizen::Locales::TimeZone& timeZone) +{ + U_ICU_NAMESPACE::UnicodeString icuStr = _LocaleData::GetIcuString(id); + std::unique_ptr pIcuTimeZone(U_ICU_NAMESPACE::TimeZone::createTimeZone(icuStr)); + SysTryReturnResult(NID_LCL, pIcuTimeZone != null, E_INVALID_ARG, "Unable to create ICU timezone"); + + U_ICU_NAMESPACE::UnicodeString retIcuStr; + SysTryReturnResult(NID_LCL, pIcuTimeZone->getID(retIcuStr) == icuStr, + E_INVALID_ARG, "Unsupported timezone id [%ls]", id.GetPointer()); + + std::unique_ptr<_TimeZoneImpl> pTimeZoneImpl(new (std::nothrow) _TimeZoneImpl(*pIcuTimeZone, _LocaleData::GetIcuDate(utcTime))); + if (pTimeZoneImpl) + { + delete timeZone.__pTimeZoneImpl; + timeZone.__pTimeZoneImpl = pTimeZoneImpl.release(); + return E_SUCCESS; + } + + return E_INVALID_ARG; +} + +void +_TimeZoneImpl::GetIcuTimeRuleValue(const TimeRule& ospRule, int& month, int& dayOfWeekInMonth, int& dayOfWeek, int& time, int& mode) +{ + if (ospRule.GetMonth() != MONTH_UNDEFINED) + { + month = ospRule.GetMonth() - 1; + + int ospDay = ospRule.GetDay(); + dayOfWeekInMonth = (ospDay == TimeRule::DAY_UNDEFINED)? 0 : ospDay; + + int ospDayOfWeek = ospRule.GetDayOfWeek(); + dayOfWeek = (ospDayOfWeek == WEEK_UNDEFINED)? 0 : ospDayOfWeek; + + time = ospRule.GetHour() * ONE_HOUR_IN_MILLISEC + ospRule.GetMinute() * ONE_MIN_IN_MILLISEC; + + int ospTimeMode = ospRule.GetTimeMode(); + mode = IcuDateTimeRule::WALL_TIME; + if (ospTimeMode == Tizen::System::TIME_MODE_UTC) + { + mode = IcuDateTimeRule::UTC_TIME; + } + + if (ospTimeMode == Tizen::System::TIME_MODE_STANDARD) + { + mode = IcuDateTimeRule::STANDARD_TIME; + } + + switch (ospRule.GetRuleMode()) + { + case EXACT_DAY: + case BACKWARD_FROM_END_OF_MONTH: + dayOfWeek = 0; + break; + case DAY_OF_WEEK_IN_MONTH: + dayOfWeekInMonth = ospRule.GetWeek(); + if (dayOfWeekInMonth < 0) + { + ++dayOfWeekInMonth; + } + break; + case AFTER_THE_SPECIFIED_DAY: + case BEFORE_THE_SPECIFIED_DAY: + dayOfWeekInMonth *= ospRule.IsOnOrAfterDay()? 1 : -1; + dayOfWeek = -dayOfWeek; + break; + } + } +} + +result +_TimeZoneImpl::GetTimeRuleFromIcuDateTimeRule(const U_ICU_NAMESPACE::DateTimeRule* pIcuRule, TimeRule& ospRule) +{ + if (pIcuRule) + { + Month month = MONTH_UNDEFINED; + int icuMonth = pIcuRule->getRuleMonth(); + if (icuMonth >= 0 && icuMonth <= 11) + { + month = static_cast< Month > (icuMonth + 1); + } + + IcuDateTimeRule::DateRuleType dateRuleType = pIcuRule->getDateRuleType(); + int day = (dateRuleType == IcuDateTimeRule::DOW)? TimeRule::DAY_UNDEFINED : pIcuRule->getRuleDayOfMonth(); + + Week week = WEEK_UNDEFINED; + int icuWeek = pIcuRule->getRuleWeekInMonth(); + if (dateRuleType == IcuDateTimeRule::DOW) + { + week = (icuWeek == -1)? LAST_WEEK : static_cast< Week >(icuWeek); + } + + DayOfWeek dayOfWeek = DAY_OF_WEEK_UNDEFINED; + if (dateRuleType != IcuDateTimeRule::DOM) + { + dayOfWeek = static_cast< DayOfWeek >(pIcuRule->getRuleDayOfWeek()); + } + + bool onOrAfterDay = (dateRuleType == IcuDateTimeRule::DOW_LEQ_DOM)? false : true; + + int ruleMID = pIcuRule->getRuleMillisInDay(); + int hour = ruleMID / ONE_HOUR_IN_MILLISEC; + int minute = (ruleMID % ONE_HOUR_IN_MILLISEC) / ONE_MIN_IN_MILLISEC; + + Tizen::System::TimeMode timeMode = Tizen::System::TIME_MODE_WALL; + IcuDateTimeRule::TimeRuleType timeRuleType = pIcuRule->getTimeRuleType(); + if (timeRuleType == IcuDateTimeRule::UTC_TIME) + { + timeMode = Tizen::System::TIME_MODE_UTC; + } + + if (timeRuleType == IcuDateTimeRule::STANDARD_TIME) + { + timeMode = Tizen::System::TIME_MODE_STANDARD; + } + + ospRule.SetValue(month, day, week, dayOfWeek, onOrAfterDay, hour, minute, timeMode); + + + return E_SUCCESS; + } + + return E_FAILURE; +} + +}; +}; // Tizen::Locales + + + diff --git a/src/locales/FLcl_TimeZoneImpl.h b/src/locales/FLcl_TimeZoneImpl.h new file mode 100644 index 0000000..1a69565 --- /dev/null +++ b/src/locales/FLcl_TimeZoneImpl.h @@ -0,0 +1,115 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_TimeZoneImpl.h + * @brief This is the header file for the _TimeZoneImpl class. + * + * This header file contains declarations of the _TimeZoneImpl class. + * + */ + +#ifndef _FLCL_INTERNAL_TIME_ZONE_IMPL_H_ +#define _FLCL_INTERNAL_TIME_ZONE_IMPL_H_ + +#include + +#include +#include +#include +#include + +namespace Tizen { namespace Locales +{ + +class _TimeZoneImpl + : public Tizen::Base::Object +{ +public: + + _TimeZoneImpl(void); + _TimeZoneImpl(int rawOffset, const Tizen::Base::String& id); + _TimeZoneImpl(int rawOffset, const Tizen::Base::String& id, const TimeRule& startRule, const TimeRule& endRule, int dstOffset); + _TimeZoneImpl(U_ICU_NAMESPACE::TimeZone& icuTimeZone); + _TimeZoneImpl(U_ICU_NAMESPACE::TimeZone& icuTimeZone, UDate icuDate); + + _TimeZoneImpl(const _TimeZoneImpl& otherTimeZone); + + virtual ~_TimeZoneImpl(void); + + _TimeZoneImpl& operator =(const _TimeZoneImpl& otherTimeZone); + _TimeZoneImpl* CloneN(void); + + bool operator ==(const _TimeZoneImpl& otherTimeZone) const; + bool operator !=(const _TimeZoneImpl& otherTimeZone) const; + virtual bool Equals(const Tizen::Base::Object& obj) const; + virtual int GetHashCode(void) const; + + Tizen::Base::String GetId(void) const; + void SetId(const Tizen::Base::String& id); + + int GetRawOffset(void) const; + void SetRawOffset(int rawOffset); + + int GetDstStartingYear(void) const; + void SetDstStartingYear(int year); + + int GetDstSavings(void) const; + void SetDstSavings(int dstSavings); + + const TimeRule* GetDstStartingRule(void) const; + void SetDstStartingRule(const TimeRule& startRule); + + const TimeRule* GetDstEndingRule(void) const; + void SetDstEndingRule(const TimeRule& endRule); + + result SetDstRules(const TimeRule& startRule, const TimeRule& endRule, int dstSavings = 60); + + result GetOffset(const Tizen::Base::DateTime& date, bool local, int& rawOffset, int& dstOffset) const; + result GetOffset(long long ticks, int& offset) const; + bool IsDstUsed(void) const; + + U_ICU_NAMESPACE::SimpleTimeZone GetIcuTimeZone(void) const; + TimeZone GetOspTimeZone(void); + + static const _TimeZoneImpl* GetTimeZoneImpl(const TimeZone& ospTimeZone); + static result GetTimeZone(const Tizen::Base::String& id, Tizen::Locales::TimeZone& timeZone); + static result GetTimeZone(const Tizen::Base::String& id, const Tizen::Base::DateTime& utcTime, Tizen::Locales::TimeZone& timeZone); + +private: + void GetIcuTimeRuleValue(const TimeRule& ospRule, int& month, int& dayOfWeekInMonth, int& dayOfWeek, int& time, int& mode); + result GetTimeRuleFromIcuDateTimeRule(const U_ICU_NAMESPACE::DateTimeRule* pIcuRule, TimeRule& ospRule); + +public: + static const int ONE_MIN_IN_MILLISEC = 60 * 1000; + static const int ONE_HOUR_IN_MILLISEC = 60 * ONE_MIN_IN_MILLISEC; + static const int ONE_DAY_IN_MILLISEC = 24 * ONE_HOUR_IN_MILLISEC; + static const int ONE_DAY_IN_MINUTE = 24 * 60; + +private: + U_ICU_NAMESPACE::SimpleTimeZone __icuTimeZone; + + int __dstStartingYear; + TimeRule __startingRule; + TimeRule __endingRule; + + static const int DAY_UNDEFINED = -1; +}; // _TimeZoneImpl + +}} // Tizen::Locales +#endif //_FLCL_INTERNAL_TIME_ZONE_IMPL_H_ + diff --git a/src/locales/inc/FLcl_LocaleManagerImpl.h b/src/locales/inc/FLcl_LocaleManagerImpl.h new file mode 100644 index 0000000..1c8b5e4 --- /dev/null +++ b/src/locales/inc/FLcl_LocaleManagerImpl.h @@ -0,0 +1,59 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FLcl_LocaleManagerImpl.h + * @brief This is the header file for _LocaleManagerImpl class. + */ + +#ifndef _FLCL_INTERNAL_LOCALE_MANAGER_IMPL_H_ +#define _FLCL_INTERNAL_LOCALE_MANAGER_IMPL_H_ + +#include +#include +#include + +namespace U_ICU_NAMESPACE +{ +class StringEnumeration; +} + +namespace Tizen { namespace Locales +{ + +class _LocaleManagerImpl + : public Tizen::Base::Object +{ +public: + + static Tizen::Locales::Locale GetSystemLocale(void); + static Tizen::Base::Collection::IList* GetAvailableLocalesN(void); + static Tizen::Base::String GetSelectedLanguage(void); + static Tizen::Base::Collection::IList* GetAvailableLanguagesN(void); + static Tizen::Base::Collection::IMap* GetAvailableTimeZonesN(void); + static Tizen::Base::Collection::IMap* GetAvailableTimeZonesN(int rawOffset); + + static Tizen::Base::Collection::IMap* GetAvailableTimeZonesN(U_ICU_NAMESPACE::StringEnumeration* pIcuTZStrList); + + static Tizen::Locales::TimeZone GetSystemTimeZone(void); + static result IsSupportedLocale(const Tizen::Locales::Locale& locale, bool& isSupportedLocale); + +}; // _LocaleManagerImpl + +}} //Tizen::Locales + +#endif // _FLCL_INTERNAL_LOCALE_MANAGER_IMPL_H_ diff --git a/src/newlib-compat/CMakeLists.txt b/src/newlib-compat/CMakeLists.txt new file mode 100755 index 0000000..2117185 --- /dev/null +++ b/src/newlib-compat/CMakeLists.txt @@ -0,0 +1,26 @@ +SET (this_target newlib-compat) + +INCLUDE_DIRECTORIES( + ${SLP_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/inc +) + +SET (${this_target}_SOURCE_FILES + NewlibCompatMisc.cpp + NewlibCompatStdio.cpp + NewlibCompatStdlib.cpp + NewlibCompatString.cpp +) + +## SET EXTRA COMPILER FLAGS +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fPIC" ) + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} STATIC ${${this_target}_SOURCE_FILES}) diff --git a/src/newlib-compat/NewlibCompatMisc.cpp b/src/newlib-compat/NewlibCompatMisc.cpp new file mode 100644 index 0000000..ff2ec29 --- /dev/null +++ b/src/newlib-compat/NewlibCompatMisc.cpp @@ -0,0 +1,75 @@ +// +// Copyright (c) 1981, 1993 +// The Regents of the University of California. All rights reserved. +// +// This code is derived from software contributed to Berkeley by +// Chris Torek. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. 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. +// 3. All advertising materials mentioning features or use of this software +// must display the following acknowledgement: +// This product includes software developed by the University of +// California, Berkeley and its contributors. +// 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. +// + + +#include + +_OSP_EXPORT_ const char __unctrllen[256] = { + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 2, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, +}; + + diff --git a/src/newlib-compat/NewlibCompatStdio.cpp b/src/newlib-compat/NewlibCompatStdio.cpp new file mode 100644 index 0000000..64e4683 --- /dev/null +++ b/src/newlib-compat/NewlibCompatStdio.cpp @@ -0,0 +1,2102 @@ +// +// Copyright (c) 1990, 2007 The Regents of the University of California. +// All rights reserved. +// +// Redistribution and use in source and binary forms are permitted +// provided that the above copyright notice and this paragraph are +// duplicated in all such forms and that any documentation, +// advertising materials, and other materials related to such +// distribution and use acknowledge that the software was developed +// by the University of California, Berkeley. The name of the +// University may not be used to endorse or promote products derived +// from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR +// IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +// +// This license applies to all the permissions of the below mentioned functions. +// Functions: asiprintf, iprintf, fiprintf, siprintf, sniprintf, vasiprintf, +// viprintf, vsiprintf, vsniprintf, siscanf, vfiscanf, vsiscanf, fiscanf +// + + +// +// Copyright (c) 1990 The Regents of the University of California. +// All rights reserved. +// +// This code is derived from software contributed to Berkeley by +// Chris Torek. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. 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. +// 3. All advertising materials mentioning features or use of this software +// must display the following acknowledgement: +// This product includes software developed by the University of +// California, Berkeley and its contributors. +// 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. +// +// This license applies to all the permissions of the below mentioned function. +// Function: vfiprintf +// + +// +// Copyright (C) 2007, 2008 Eric Blake +// Permission to use, copy, modify, and distribute this software +// is freely granted, provided that this notice is preserved. +// +// This license applies to all the permissions of the below mentioned functions. +// Functions: asnprintfc, vasnprintf, asniprintf, vasniprintf, funopen, fropen, fwopen +// + +// +// Copyright 2005, 2007 Shaun Jackman +// Permission to use, copy, modify, and distribute this software +// is freely granted, provided that this notice is preserved. +// +// This license applies to all the permissions of the below mentioned functions. +// Functions: diprintf, vdiprintf +// + + +#include + +char* +asnprintf(char* buf, size_t* lenp, const char* format, ...) +{ + va_list ap; + int len = 0; + va_start (ap, format); + len = vsnprintf (NULL, 0, format, ap); + va_end (ap); + + if (len < 0) + { + return NULL; // errno set by vsnprintf + } + + if (!buf || len >= (int)*lenp) + { + buf = (char *)realloc(buf, len + 1); + if (!buf) + { + return NULL; // errno set by malloc + } + } + + va_start (ap, format); + *lenp = vsnprintf (buf, len + 1, format, ap); + va_end (ap); + return buf; +} + + +char* +vasnprintf(char *buf, size_t *lenp, const char *format, va_list ap) +{ + va_list ap2; // don't consume the original ap, we'll need it again + va_copy(ap2, ap); + int len = 0; + len = vsnprintf (NULL, 0, format, ap2); + va_end (ap2); + + if (len < 0) + { + return NULL; // errno set by vsnprintf + } + if (!buf || len >= (int)*lenp) + { + buf = (char *)realloc(buf, len + 1); + if (!buf) + { + return NULL; // errno set by malloc + } + } + *lenp = vsnprintf(buf, len + 1, format, ap); + + return buf; +} + + +int +asiprintf(char **strp, const char *format, ...) +{ + va_list ap; + va_start (ap, format); + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + *strp = (char*)realloc(*strp, sizeof(char)*2); + strcpy(*strp, " "); + va_end (ap); + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + + ret_val = vasprintf(strp, format, ap); + va_end (ap); + return ret_val; + +done: + va_end (ap); + return EOF; +} + + +char * +asniprintf(char *buf, size_t *lenp, const char *format, ... ) +{ + va_list ap; + va_start (ap, format); + char* pret_val = NULL; + + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + va_end (ap); + return NULL; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + pret_val = vasnprintf(buf, lenp, format, ap); + va_end (ap); + return pret_val; + +done: + va_end (ap); + return NULL; +} + + +int +iprintf(const char *format, ...) +{ + va_list ap; + va_start (ap, format); + int ret_val = 0; + + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + va_end (ap); + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vprintf(format, ap); + va_end (ap); + return ret_val; + +done: + va_end (ap); + return EOF; +} + + +int +fiprintf(FILE * fp, const char *format, ...) +{ + va_list ap; + va_start (ap, format); + int ret_val = 0; + + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + va_end (ap); + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vfprintf(fp, format, ap); + va_end (ap); + return ret_val; + +done: + va_end (ap); + return EOF; +} + +int +siprintf(char *str, const char *format, ...) +{ + va_list ap; + va_start (ap, format); + int ret_val = 0; + + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + va_end (ap); + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vsprintf(str, format, ap); + va_end (ap); + return ret_val; + +done: + va_end (ap); + return EOF; +} + + +int +sniprintf(char *str, size_t size, const char *format, ...) +{ + va_list ap; + va_start (ap, format); + int ret_val = -1; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + va_end (ap); + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + + ret_val = vsnprintf(str, size, format, ap); + +done: + va_end (ap); + return ret_val; +} + +int +vasiprintf(char **strp, const char *format, va_list ap) +{ + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vasprintf(strp, format, ap); + return ret_val; + +done: return EOF; +} + + +char* +vasniprintf(char *buf, size_t *lenp, const char *format, va_list ap) +{ + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + int len = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return NULL; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + pfmt = (char *)format; + + len = vsnprintf (NULL, 0, pfmt, ap); + va_end (ap); + + if (len < 0) + { + return NULL; // errno set by vsnprintf + } + + if (!buf || len >= (int)(*lenp)) + { + buf = (char*)malloc(len + 1); + } + + if (!buf) + { + return NULL; // errno set by malloc + } + + *lenp = vsnprintf (buf, len + 1, format, ap); + return buf; +done: return NULL; +} + + +int +vfiprintf(FILE * fp, const char *format, va_list ap) +{ + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vfprintf(fp, format, ap); + return ret_val; + +done: return EOF; +} + + +int +viprintf(const char *format, va_list ap) +{ + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vprintf(format, ap); + return ret_val; + +done: return EOF; +} + + +int +vsiprintf(char *str, const char *format, va_list ap) +{ + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vsprintf(str, format, ap); + return ret_val; + +done: return EOF; +} + + +int +vsniprintf(char *str, size_t size, const char *format, va_list ap) +{ + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vsnprintf(str, size, format, ap); + return ret_val; + +done: return EOF; +} + + +int +diprintf(int fd, const char *format, ...) +{ + va_list ap; + va_start (ap, format); + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + va_end (ap); + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vdprintf(fd, format, ap); + va_end (ap); + return ret_val; + +done: + va_end (ap); + return EOF; +} + + +int +siscanf( const char* str, const char* format, ...) +{ + va_list ap; + va_start (ap, format); + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + if (count == 0) // as no format specifier in string + { + va_end (ap); + return 0; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + va_end (ap); + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vsscanf(str, format, ap); + va_end (ap); + return ret_val; + +done: + va_end (ap); + return EOF; +} + + +int +vdiprintf(int fd, const char *format, va_list ap) +{ + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vdprintf(fd, format, ap); + return ret_val; + +done: return EOF; +} + +int vfiscanf(FILE *fp, const char *format, va_list ap) +{ + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + if (count == 0) // as no format specifier in string + { + return 0; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vfscanf(fp, format, ap); + return ret_val; + +done: return EOF; + +} + + +int +vsiscanf(const char *str, const char *format, va_list ap) +{ + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + if (count == 0) // as no format specifier in string + { + return 0; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vsscanf(str, format, ap); + return ret_val; + +done: return EOF; + +} + +int +fiscanf(FILE *fp, const char *format, ...) +{ + va_list ap; + va_start (ap, format); + int ret_val = 0; + char* pfmt = NULL; // format string + char ch = 0; // character from pfmt + int pos[100] = {0, }; + int count = 0; + int index = 0; + pfmt = (char *)format; + while (*pfmt != '\0') + { + if (*pfmt == '%') + { + pos[count++] = index; + } + index++; + pfmt++; + } + if (count == 0) // as no format specifier in string + { + va_end (ap); + return 0; + } + pfmt = (char *)format; + + if (*pfmt == '\0') + { + goto done; + } + while ((*pfmt != '%') && ( *pfmt != '\0')) + { + pfmt++; + } + index = 1; + + if (count) + { + count--; + } +rflag: ch = *pfmt++; + + switch (ch) + { + case '\'': + goto rflag; + // fall through + case ' ': + goto rflag; + // fall through + case '#': + goto rflag; + // fall through + case '*': + goto rflag; + // fall through + case '-': + goto rflag; + // fall through + case '+': + goto rflag; + // fall through + case '.': + goto rflag; + // fall through + + case '0': + goto rflag; + // fall through + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto rflag; + // fall through + case 'L': + goto rflag; + // fall through + case 'a': + case 'A': + case 'F': + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + va_end (ap); + return EOF; + break; + + default: // "%?" prints ?, unless ? is NUL + if (count) + { + pfmt = (char *)format; + pfmt = pfmt + pos[index++]; + count--; + pfmt++; + goto rflag; + // fall through + } + } + ret_val = vfscanf(fp, format, ap); + va_end (ap); + return ret_val; + +done: + va_end (ap); + return EOF; +} + + +typedef __ssize_t __io_read_fn (void* __cookie, char* __buf, size_t __nbytes); +typedef __ssize_t __io_write_fn (void* __cookie, __const char* __buf, size_t __n); +typedef int __io_seek_fn (void* __cookie, _IO_off64_t* __pos, int __w); +typedef int __io_close_fn (void* __cookie); + +//typedef _IO_cookie_io_functions_t ; + +//FILE* funopen(const void* cookie, funread readfn, funwrite writefn, funseek seekfn, funclose closefn); + +FILE* +funopen(const void* cookie, funread readfn, funwrite writefn, funseek seekfn, funclose closefn) +{ + cookie_io_functions_t cookiefn; + char mode[3] = {0, }; + if (readfn) + { + cookiefn.read = (__io_read_fn*)readfn; + if (writefn) + { + strcpy(mode, "r+"); + cookiefn.write = (__io_write_fn*)writefn; + } + else + { + strcpy(mode, "r"); + cookiefn.write = NULL; + } + } + else + { + strcpy(mode, "w"); + cookiefn.write = (__io_write_fn*)writefn; + cookiefn.read = NULL; + } + cookiefn.seek = (__io_seek_fn*)seekfn; + cookiefn.close = (__io_close_fn*)closefn; + + return fopencookie((void*)cookie, mode, cookiefn); +} + + +FILE* +fropen(const void* cookie, funread readfn) +{ + return funopen(cookie, readfn, (int (*)(void*, const char*, int))0, (fpos_t (*)(void*, fpos_t , int ))0, (int (*)(void*))0); +} + +FILE* +fwopen(const void* cookie, funwrite writefn) +{ + return funopen(cookie, (int (*)(void*, char*, int))0, writefn, (fpos_t (*)(void*, fpos_t , int))0, (int (*)(void*))0); +} diff --git a/src/newlib-compat/NewlibCompatStdlib.cpp b/src/newlib-compat/NewlibCompatStdlib.cpp new file mode 100644 index 0000000..a034613 --- /dev/null +++ b/src/newlib-compat/NewlibCompatStdlib.cpp @@ -0,0 +1,109 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// This license applies to all functions, except for the functions under the below mentioned license +// in this file. +// + + +// +// Copyright (c) 1998, M. Warner Losh +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer.c +// 2. 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. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. +// +// This license applies to all the permissions of the below mentioned function. +// Function: reallocf +// + + +#include + +float +atoff(const char* pcStr) +{ + return strtof (pcStr, NULL); +} + +char* +ecvtf(float fval, int ndigit, int* decpt, int* sign) +{ + return ecvt((double)fval, ndigit, decpt, sign); +} + + +char* +ecvtbuf(double invalue, int ndigit, int* decpt, int* sign, char* ecvt_buf) +{ + char* pecvt_ret = ecvt(invalue, ndigit, decpt, sign); + strcpy(ecvt_buf, pecvt_ret); + return ecvt_buf; +} + + +char* +fcvtf( float fval, int ndigit, int* decpt, int* sign) +{ + return fcvt((double)fval, ndigit, decpt, sign); +} + + +char* +fcvtbuf(double invalue, int ndigit, int* decpt, int* sign, char* fcvt_buf) +{ + char* pfcvt_ret = fcvt( invalue, ndigit, decpt, sign); + strcpy(fcvt_buf, pfcvt_ret); + return fcvt_buf; +} + + +char* +gcvtf( float fval, int ndigit, char* buf) +{ + return gcvt((double)fval, ndigit, buf); +} + + +void* +reallocf(void* ptr, unsigned int size) +{ + void* ptemp = NULL; + ptemp = realloc( ptr, size); + if (!ptemp && ptr) + { + free( ptr); + } + return (ptemp); +} diff --git a/src/newlib-compat/NewlibCompatString.cpp b/src/newlib-compat/NewlibCompatString.cpp new file mode 100644 index 0000000..5707a89 --- /dev/null +++ b/src/newlib-compat/NewlibCompatString.cpp @@ -0,0 +1,153 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// This license applies to all functions, except for the functions under the below mentioned license +// in this file. +// + + +// +// Copyright (c) 1998 Todd C. Miller +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. 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. +// 3. The name of the author may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED ``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 AUTHOR 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. +// +// This license applies to all the permissions of the below mentioned functions. +// Functions: wcslcat, wcslcpy +// + + +#include + +char* +strlwr(char* pcStr) +{ + unsigned char* pucs = (unsigned char*) pcStr; + while (*pucs != '\0') + { + *pucs = tolower(*pucs); + pucs++; + } + return pcStr; +} + + +char* +strupr(char* pcStr) +{ + unsigned char *pucs = (unsigned char*) pcStr; + while (*pucs != '\0') + { + *pucs = toupper(*pucs); + pucs++; + } + return pcStr; +} + + +size_t +wcslcat(wchar_t* wcDst, const wchar_t* wcSrc, size_t siz) +{ + wchar_t* pdst = wcDst; + const wchar_t* psrc = wcSrc; + size_t count = siz; + size_t dlen = 0; + + // Find the end of pdst and adjust bytes left but don't go past end + while ((*pdst != '\0') && (count-- != 0)) + { + pdst++; + } + + dlen = pdst - wcDst; + count = siz - dlen; + + if (count == 0) + { + return (dlen + wcslen (psrc)); + } + + while (*psrc != '\0') + { + if (count != 1) + { + *pdst++ = *psrc; + count--; + } + psrc++; + } + *pdst = '\0'; + + return (dlen + (psrc - wcSrc)); // count does not include NUL +} + + +size_t +wcslcpy( wchar_t* wcDst, const wchar_t* wcSrc, size_t siz) +{ + wchar_t* pdst = wcDst; + const wchar_t* psrc = wcSrc; + size_t count = siz; + + // CopyPanel as many bytes as will fit + if ((count != 0) && (--count != 0)) + { + do + { + if ((*pdst++ = *psrc++) == 0) + { + break; + } + } + while (--count != 0); + } + + // Not enough room in pdst, add NUL and traverse rest of psrc + if (count == 0) + { + if (siz != 0) + { + *pdst = '\0'; // NUL-terminate pdst + } + while (*psrc++) + { + ; + } + } + + return (psrc - wcSrc - 1); // count does not include NUL +} + diff --git a/src/osp-init/Osp.cpp b/src/osp-init/Osp.cpp new file mode 100644 index 0000000..b375d83 --- /dev/null +++ b/src/osp-init/Osp.cpp @@ -0,0 +1,48 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file Osp.cpp + * @brief This is the implementation of global OSP initialization. + */ + +#include +#include + +extern "C" +{ +extern void FBase_Initialize(void); +extern void FBase_Finalize(void); + + +__attribute__((constructor)) +void _OSP_EXPORT_ +Osp_Initialize(void) +{ + // FBase_Initialize() is moved to FApp_AppInfo.cpp due to the preloading issue. + OpenSSL_add_all_algorithms(); +} + +__attribute__((destructor)) +void _OSP_EXPORT_ +Osp_Finalize(void) +{ + //FBase_Finalize(); + EVP_cleanup(); +} + +} diff --git a/src/osp-string/CMakeLists.txt b/src/osp-string/CMakeLists.txt new file mode 100755 index 0000000..e381b2d --- /dev/null +++ b/src/osp-string/CMakeLists.txt @@ -0,0 +1,27 @@ +SET(LOCALE_ROOT_PATH "${ROOT_DIR}/target/generic/root/usr/share/locale") + +FILE(GLOB _pofiles *.po) + +FOREACH(_file ${_pofiles}) + GET_FILENAME_COMPONENT(_in ${_file} ABSOLUTE) + GET_FILENAME_COMPONENT(_basename ${_file} NAME_WE) + + SET(_out "${LOCALE_ROOT_PATH}/${_basename}/LC_MESSAGES/osp.mo") + + ADD_CUSTOM_COMMAND( + OUTPUT ${_out} + COMMENT "Generating ${_out}" + COMMAND mkdir -p ${LOCALE_ROOT_PATH}/${_basename}/LC_MESSAGES + COMMAND msgfmt -o ${_out} ${_in} + DEPENDS ${_in} + ) + + SET(mo_files ${mo_files} ${_out}) + + #INSTALL(FILES ${_out} DESTINATION "${_out}") +ENDFOREACH(_file ${_pofiles}) + +ADD_CUSTOM_TARGET(osp-string ALL DEPENDS ${mo_files}) + + + diff --git a/src/osp-string/ar.po b/src/osp-string/ar.po new file mode 100755 index 0000000..93c5bb6 --- /dev/null +++ b/src/osp-string/ar.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "إلغاء" + +msgid "IDS_COM_SK_OK" +msgstr "موافق" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "نوع التطبيق" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "التطبيق الافتراضي" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "تحديد التطبيق الافتراضي" + diff --git a/src/osp-string/bg.po b/src/osp-string/bg.po new file mode 100755 index 0000000..3d70a6e --- /dev/null +++ b/src/osp-string/bg.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Отмени" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Тип приложение" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Приложение по подразбиране" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Избор на приложение по подразбиране" + diff --git a/src/osp-string/ca.po b/src/osp-string/ca.po new file mode 100755 index 0000000..1245adc --- /dev/null +++ b/src/osp-string/ca.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Cancel·lar" + +msgid "IDS_COM_SK_OK" +msgstr "Acceptar" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Tipus d'aplicació" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Aplicació predeterminada" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Seleccionar aplicació predeterminada" + diff --git a/src/osp-string/cs.po b/src/osp-string/cs.po new file mode 100755 index 0000000..0f6b1d8 --- /dev/null +++ b/src/osp-string/cs.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "ZruÅ¡it" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Typ aplikace" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Výchozí aplikace" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Vybrat výchozí aplikaci" + diff --git a/src/osp-string/da.po b/src/osp-string/da.po new file mode 100755 index 0000000..baff758 --- /dev/null +++ b/src/osp-string/da.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Annuller" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Programtype" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Standardprogram" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Vælg standardprogram" + diff --git a/src/osp-string/de_DE.po b/src/osp-string/de_DE.po new file mode 100755 index 0000000..7b0bb5c --- /dev/null +++ b/src/osp-string/de_DE.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Abbrechen" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Anwendungstyp" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Standardanwendung" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Standardanwendung auswählen" + diff --git a/src/osp-string/el_GR.po b/src/osp-string/el_GR.po new file mode 100755 index 0000000..2b0e4f0 --- /dev/null +++ b/src/osp-string/el_GR.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Άκυρο" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Τύπος εφαρμογής" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Προεπιλεγμένη εφαρμογή" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Επιλογή προεπιλεγμένης εφαρμογής" + diff --git a/src/osp-string/en.po b/src/osp-string/en.po new file mode 100755 index 0000000..299ad64 --- /dev/null +++ b/src/osp-string/en.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Cancel" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Application type" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Default application" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Select default application" + diff --git a/src/osp-string/en_US.po b/src/osp-string/en_US.po new file mode 100755 index 0000000..299ad64 --- /dev/null +++ b/src/osp-string/en_US.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Cancel" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Application type" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Default application" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Select default application" + diff --git a/src/osp-string/es_ES.po b/src/osp-string/es_ES.po new file mode 100755 index 0000000..100e3bb --- /dev/null +++ b/src/osp-string/es_ES.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Cancelar" + +msgid "IDS_COM_SK_OK" +msgstr "Aceptar" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Tipo de aplicación" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Aplicación predeterminada" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Seleccionar aplicación predeterminada" + diff --git a/src/osp-string/fi.po b/src/osp-string/fi.po new file mode 100755 index 0000000..2fbda59 --- /dev/null +++ b/src/osp-string/fi.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Peruuta" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Sovelluksen tyyppi" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Oletussovellus" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Valitse oletussovellus" + diff --git a/src/osp-string/fr_FR.po b/src/osp-string/fr_FR.po new file mode 100755 index 0000000..d71d63c --- /dev/null +++ b/src/osp-string/fr_FR.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Annuler" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Type d'application" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Application par défaut" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Sélectionnez l'application par défaut" + diff --git a/src/osp-string/he.po b/src/osp-string/he.po new file mode 100755 index 0000000..ed7e557 --- /dev/null +++ b/src/osp-string/he.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "ביטול" + +msgid "IDS_COM_SK_OK" +msgstr "אישור" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "סוג יישום" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "יישום ברירת מחדל" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "בחר יישום ברירת מחדל" + diff --git a/src/osp-string/hi.po b/src/osp-string/hi.po new file mode 100755 index 0000000..8bd5cdc --- /dev/null +++ b/src/osp-string/hi.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "रद्द" + +msgid "IDS_COM_SK_OK" +msgstr "ठीक" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "एप्लीकेशन प्रकार" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "डिफ़ॉल्ट एप्लीकेशन" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "डिफ़ॉल्ट एप्लीकेशन चुनें" + diff --git a/src/osp-string/hr.po b/src/osp-string/hr.po new file mode 100755 index 0000000..8aca9b0 --- /dev/null +++ b/src/osp-string/hr.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Prekid" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Vrsta aplikacije" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Zadana aplikacija" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Odaberi zadanu aplikaciju" + diff --git a/src/osp-string/hu.po b/src/osp-string/hu.po new file mode 100755 index 0000000..02953fc --- /dev/null +++ b/src/osp-string/hu.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Mégse" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Alkalmazás típusa" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Alapértelmezett alkalmazás" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Alapértelmezett alkalmazás kiválasztása" + diff --git a/src/osp-string/id.po b/src/osp-string/id.po new file mode 100755 index 0000000..642a666 --- /dev/null +++ b/src/osp-string/id.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Batal" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Jenis aplikasi" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Aplikasi default" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Pilih aplikasi default" + diff --git a/src/osp-string/it_IT.po b/src/osp-string/it_IT.po new file mode 100755 index 0000000..995b473 --- /dev/null +++ b/src/osp-string/it_IT.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Annulla" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Tipo di applicazione" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Applicazione predefinita" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Seleziona applicazione predefinita" + diff --git a/src/osp-string/ja_JP.po b/src/osp-string/ja_JP.po new file mode 100755 index 0000000..100fb87 --- /dev/null +++ b/src/osp-string/ja_JP.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "キャンセル" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "アプリケーション​タイプ" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "標準​アプリケーション" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "標準​アプリケーション​を​選択​します" + diff --git a/src/osp-string/ko_KR.po b/src/osp-string/ko_KR.po new file mode 100755 index 0000000..aacd4e7 --- /dev/null +++ b/src/osp-string/ko_KR.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "취소" + +msgid "IDS_COM_SK_OK" +msgstr "확인" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "애플리케이션 종류" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "기본 애플리케이션" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "기본 애플리케이션을 선택하세요" + diff --git a/src/osp-string/lt.po b/src/osp-string/lt.po new file mode 100755 index 0000000..e2a38cb --- /dev/null +++ b/src/osp-string/lt.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "AtÅ¡aukti" + +msgid "IDS_COM_SK_OK" +msgstr "Gerai" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Programos tipas" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Numatytoji programa" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Pasirinkti numatytąją programą" + diff --git a/src/osp-string/lv.po b/src/osp-string/lv.po new file mode 100755 index 0000000..c619217 --- /dev/null +++ b/src/osp-string/lv.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Atcelt" + +msgid "IDS_COM_SK_OK" +msgstr "Labi" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Programmas veids" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Noklusējuma programma" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Izvēlieties noklusējuma programmu" + diff --git a/src/osp-string/ms.po b/src/osp-string/ms.po new file mode 100755 index 0000000..f025ae8 --- /dev/null +++ b/src/osp-string/ms.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Batal" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Jenis aplikasi" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Aplikasi lalai" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Pilih aplikasi lalai" + diff --git a/src/osp-string/nl_NL.po b/src/osp-string/nl_NL.po new file mode 100755 index 0000000..1e5eaa3 --- /dev/null +++ b/src/osp-string/nl_NL.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Annuleren" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Applicatietype" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Standaardapplicatie" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Standaardapplicatie selecteren" + diff --git a/src/osp-string/no.po b/src/osp-string/no.po new file mode 100755 index 0000000..ea5aceb --- /dev/null +++ b/src/osp-string/no.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Avbryt" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Programtype" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Standardprogram" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Velg standardprogram" + diff --git a/src/osp-string/osp_string.xls b/src/osp-string/osp_string.xls new file mode 100755 index 0000000000000000000000000000000000000000..0d1fe936bb7883e545bf7bad2a7b911f3cb22cb9 GIT binary patch literal 14068 zcmVHc(c)>gvn{#IWZJXRLjHXmgYFAfUzy3 zw{pZ)q$G;im6GghUCUn7bokO10wCUtlSfFy9XEFwtLu(0s8fT`i_1uAnG~DGg{MY` znLggW**kgrjf@Yo8|wx+ZbbI_p25Oqb1V?0zpjm(pa8?rDovQs@$dy}`7yZ4qQ;&X zh{m0HN|?yEYMrA#eXAV8Cprp=@Dk`6+=@pGj=|xNdl}$q0IOE$Sw;Z|C7h%Im-kF8 zq@?|BGoV^t8x#tFD79c~rd&WcUT@pM^H4P1;D@ZZQKytuCqf*RCJhBK0Rx)f=^wqe zV7|}l}QyRy5(^BT6CX;Iga!> zNN|jE*g+!*Eam+vmzsZg8#KvcA*|X~@*Pk^Q40z5$-Yx@Dq9B<^bLMix`|S5R*ItE z+%S%-8Nd}#B8NRQDrejfxlv#D4yB>bP9LT5Bvj1K)C7-Y9^op~@}tVK9-Z!hoJyWb z)h-dYp57d6wEDk=wjBSlY?LE$(Cc|@> z%ee=~lv7GR@WtHDu|cq|=fA^~=WHuWr#8C_3eG`8${B)wqUZ9cJbSxGDq{Sd6jrCX z4z)IR+*~){%Wy#zMjYU3_sBy+z8y^0ZfPN*p1w-zLt83u2P_SKGiXd;>c@ zR}uG2HfR?+sD&w$n?xT_7x#iqlpM&*(fMv_hC8`W2PB07yPy1}cm!8G-K3#!? z-aboKW(1Eib4af%)Uot$^k)@=3UbH5bm5o`xNV zFx8ciTo_duWQbm;@2veoO-ROf4TS4F-NtmB@G@ZGxbl8_&ntVnU{mx8$>)9V0P1B5 zz6!S?g~dExl$tE~PJ-az>})b}A)fwKCyUC=e?9w_XE_it4eZHk8DgdRg2zea_;j==%t1BrvPOMdAcZ?A518#K@R(Qe*7M`6U)a<!}6$?ceT|A{FsS^~THN;hnZx8A)nW|_L!+ItTF7N?iz z!|g>I*=RA?mdOCP?ebH7L}Ibh*&fs4a23geXqlCJ#+^VUp;6~003V>3;tWmJnj`76 z;kAP#t}0)t>5k}@V_9h6BMaH;b-R2HaHCGj|;%(ej z?i|Suz*Jg$hd5qNUk&`_6D+`t2e89pn6^W;tt((Xtm^(ss|bUV9b!|HLk6gySaSanpVq})ff&rs8 zrye?-$|iAN)9BtB29D9iuCV&_F3^B(xt{mS2PrU#@|y>JBhD7hnyC>h zl7sfhS$pK&YM!9P%JuhY&X~JlOz{Y;_)v(XVTzBAzc*l zQ98>m2D!sXwN&Peur|xbyqFh2_G=2-GkI2ev~{aRqQgRa+nZ2*MCkVGnmFy1jZV7J|2) zAAP|!osN3M3(x(JzG82|>)+d88oJWh@^58AF7D|1tU_DBUo2jwcW|c_JNxKKlg%l< zHrq@2m!e9~&Y|-e^81X6?wt(X-s-EdVx4a?-HydtSL}vG5*)9t!&B~EL2^nE00+X z7l0tuitK1e*9X|Pwxu({;zoJYwS*J~yh9^)9CU!)2<9>G^qMfW&N~j!i(S%3qU-Yy zD+kT<&!I&rY5pHR=dI(4#l6ismqPQq(aFIdQKaH2xW~DcVjM;bj7m25YpL-I7j;HW z^Q}<`&Uah5> zmRIUvG}7($ewK4K0?Y~5$O|?t`uJoz|A_chop+x9z?#NMQYti*mn{Ez&*s<2Rume% zy@FRZX;oL+jrMW$yxp*1YJSiZOoc2T%UG5_^BXz~BsTeW_MZl0S&y17Ymhgo1v`Z7 z;cXcvH#}buw7z?oW?2BE%ho*8gI1At#N&y|6uxk~7~-8tVP5u2Vm~1p(u%nAPUFGK z!}fdiqe&p&gq9A5l!nWl-gUApiWu^P!zjtg-$MLmaaHWxRyO>C*FcrV4)n7+Wj@bs zr3sHbGnEo*wlTaCcL)g7ioPE{8O+*}=%5gVwYakR-0NuFL-#SIAl~gp;%X+shFyHW z0szHJx>~PT-n`HyUs>9Y$Uf;2$>~idm%>Glrxg+V0t7LE|5$29|c zs#4mE!|>@z&HKP9wuO#&6l&TQmAI19&nmq8wT2w1B^q2Jb`+mf>Of|c*!e9wLh}o^ zh9QWe(!{b`QCAI>dg)zQlH_ec+V>?j{tO^SPL8zGSszXmlll{i&MO2z|Tr* z{+IuWudFyF_h(nn;C^;mqT!DQw#GIOZbU#yT-OIx{r?6#iTtbvkW)_!wB}+;<3|WB z{JwmLY>8?mh(To)qNf|lH$M|rSCpWRfyCtpl;ffd1|b<4HQ|}DFyPbEFk&AizHfreR5B6ebF9;|<;sOHK3B04d6a2$oBVo7@YD=OVtp3P z_V=(jDFf88>*iwgc%nO4QuortH*(lmE z8V9{ih2s~f_c9V4b z1Yl51TaB>>j6_@JeutAf9V3Ta<(PeqJg_tpA4ec_`Z>ZQwkq2LA8&GbA^c*((>ifj zB~}{U@qqX))(llu#fB)IT^e*VhQ9sK&4kJgVwO4!9-3av zu=DHu7O%CPFE}D30Jx%h2RYs})g1CRB)TEI)0&p-vi((5+ZB~AAR#H9Lh_Hn-ru)n zjWEnB7I-1WyhnYT$v$$T;fF@#;o|x@qi@6X+j-0w$L0#*Sjhk7)7e#tD0W!mHskAt zSZo!W&$r|iVi6mexP^CzH0}8wR|}5|W1;g~L%NQAF9wwk5*ZKOg(@!H_5S7&lv;?Y zu-{HD?#sU|FVd%?mN;^`OO%;u;?w@4%;Rc+=U5$uK2!0QuP(*8n?$Hh2t!42?{#YQ z?L9tIigasHBykJ@t@h8=bChx-$AYl#)&$BnA?}@M9Sb;E`EcwDE}ck5CGstf1ccYg zZKggGnOTb#6KoD6jY!br$r-)!AUld0jGIvKWp23SMrXeN$BApBF!+D9;R$^Gw3o zzegV=Qni!2um7^xRQBHX2; z%oMPTL{eEFFBMp_H(WP*1FIT3+@kX$0{-vuS@6JQMDZ}z0=7?2PrqOrGmHqmFl>BX zlAxKJ9Vkmi_9hZ_#FB@J4P*hInNtJ>vcrsEajxzTN>GyRGqCP!8M8qNf-KThHkIeD zyA!)H;R6mOSe`5wfAyWUg&CX;9y;`zynLHfg{?^Nbxs1rKU{%UL85>}aO2Pu&oJLT z%@2Mj$!;Gw;HBh76<;LAO?>rS=p_hiN;{>F6pR>IL6HBzm7;}lZ)k61m_{iM+p*+2=Rxgj=^f~i30}Yak zO*{A!pdk_}V=MPB6gXikbu{xytVR5++6P8Mt?AHpZBI;q_0dRiFAnEUt5pU zBw{`zUn1RsCn^G+W@@K(iH6c86!P#rzFJc`ZyEy7t=E~nB|uQH@>VfN7UGVne`vw_ z9P(qNxT?6x5q;($Z(3fG1CeK)1gtZl5pFA$|zS zteK~^R*l3zEKxD2mht{^Qw2efy}7e$H^_{iXs8BV3BkI_EC(_n7-_dr>q!iVPn&n^ z6i1t)oRP}>svd!hKd;xdv-Pryordu9D7){Mhz!3wPy%IQ-(ap}y3!@GrCl&yJ6Lr2 z#}1MUfEf63kFkJ}!uA!SV=fi9nXWu~8cMZNFfyF~cqS?r?xx4Nf>`RhOdTXb5wfxp zyL~{l*C+6A7ujMf^ zMfJ8^t@2zsWokO%R+wB5$<0Xo44!2tvZJILzxWKVD~eUSWX7hpt)fJ4!sJyR899OO zX={zTH{8{z^e##*4O{q<+0y+ofsVQ!qGn2-Mj2Aq?e1^q->wqAts+5 z`TOU4&$;g=jJ0k*|Ep>fK@A|hu4@`K8#FyiGyqfnUS5mc=?Abv)~Nn!LgGK0LuWK& zM=t=@T+QE}yY6P!DyKiMWdbMTmQDVlh)8sdqP+))U-%%;=d)&Y6EX4UMIZ{5@iS*r zGuv}>ETIs+F`F+mvakeLo28-a+un(Nv3MD9qaSMQXq0=Q{(I+FA`=Gqk;nzJwTZ;$ zf9q7qJV_5iw(>*T9)$xKd&wAVLnc0;XmaxXV5w4K$yR#;TMTB+S5B=EGMsQ{K6WT= zc8yn$hWnRvmEg(}ARAH(H}&`7fX2G)=h~ z@%Sqd^8qm*WrqG3@_=#gE&70zI!Or?*PY-$Pov8$bc@}H0sH|JK#uegl#wUB0%9k` zMhLu1p^Sq|sb>UT$5}o=NMY&!`4$@VayZGC+fligi{RH>ridO# zS_EH6xGRiAA=H@JW;rDz<7u|26=EGCcIWlb&fu}%%opVa^>7WY3}^BJqO4fL@H0+n zaL;lwiA@n@2)BH?T=v(a^g}m7Ah=Fb99XoN3e{I0Pw^Yk@t^NnJ@TsXFCf*0Ga4FH zm_{8>#`frg)*#{MP+C@Ihh?rJ$##?BB6n>GkC>WcgYWqBc5ILVkUGolGW`XQqON9Xcy{34$I%ItF z8?=O=_zJw#FLwCRlzse!>pNg3R|G=A%|0~j@kGIe@xT6f_vnm1b*Vg5wusJOSe3G$ zsAhldEM2*iP-o?Gw^jZtcs{LM<7tCdhA8^j0>Gz;#C$XKse=6j_bo6-cPSi=eWqah zL6X+D6nZpgp{LU@Qaa=~R<{9?#UyTT>mxo7mC z)Dkp^8P=zc47?4SvtSMBt~toy1h5aN`$vsH$z&Hks!U9#x}Q|5S_yEmemP%hU#Rv1 z+a%bE(IqYHh3Iqji))lnCU3b~g}<)*@9<#7pv;Kv}8ke)B*E@gQq?O$)a zVyyl1;{lJAZV;45NyPejHs`PL99?1A(b7LR`s)%fac9y~Gu!}q`^20?Hcz@Bx@cTE z-=*K_99xVtm$`^GlxSo`opug8dhRXRBj;b_eq>4^ywbdB!nX{S>q4$FYjh3nOI^eh z_njwfq(|SGS_p=5o6s1-5$xmIfVWS~PpMUU&Yt_O)E_zCI968;@k2SfQ=MNT1vALN z3q?f{^*zN|N>QhafFB=0;^VL6il6arDFAWp z1&__&3H#UPgcOfBLIe~v!c162;l{3wUNtHu$Hjl@ctqJ)<)mje9O;cYlZhQ$Hv0>{ zr6BhEU^eBBrE;{l!v>Ss7Q_WE91Q40?nB+}n9+b+>|ckygO_$E&ik|{J_Q~IZzif9 zmoF$HgE|z*J$mSv5#SjRdWuH=?Rwjs7#>Sy%r{DN{kE3s!$#yLIx1^9K=Vlzt^b&k z2~9)p{fA?+C$~%oPHkuD=?q=~RqXvw%YnBmC>_GiUD#|m3Dgp%?6J)+SJPe1Mv{Zm zu#)&_hh&naTFOWq8L39iH+01OvMy=mWi5%-+`iCMq0gog7p_gbM6Tx$q` zI;1N2c3(b+`zc&jekag6;43#^A@9;=BJ)jU)EFDtlt*e2M5()*!qd1s8*p~LG&9w9 z{M1$?Tq?=cl*d${K_v6MT+p*(;MC1WT92Lz)h##!`3s|yoS*s5c4+MsY32!oZqp%` z^^QX@s82OVK%AocMJatsLVR{_E28h!&CIzErwb1;CfmD=5}ta4L7^?WCzZa{ZN0SY zdHma)S^+Q(C&_L0nKU5RneRDZMUTaHhY;r=V&q~n;{2?tUTj)&0~Z#m~x7q66dCIh@ZLm z_DS^B-)Ab?uEK=`-QWUq&i>gcf8_X^a_j%d!uxfNWUNJwKuPd0+MPbg4^J*d8^I8& zhpGxdrJEGz2cA9I4IB-U7B46ZmhU8XGUQYS1ez<3h5p9K)4DR@Zm}F}79}pN+1{*K zc`kPFSt`?o;&Bwh|2H>$`Z7-h;t1_wXYvs;TXQ$zoWeL!{=V!`G!-X88~Hq0C{*QP zkU&Cp<2JN!o9`U?6)NrwZ``=tHJG3C#J#=Ha+wH2tUA?|e-Y8t zf95aWQ6B-X9n6N92TZdF)6W%bypy#0+I<}Ua7L1un}`1e@Xb3I`!&^ zyiH%7qO9U7QL?KuFhk1oU*+VEUm_D^)w|hBo1h;jSea^NtuQz zs~-jsyE%VI5XWm+NRxg4dP@lG0pnsR;Iy`IGJy+aWDOB0BR%I3 z?}d4c!fimECGgqLuY!*Q5{1;K_(6A{ALPf_N2p~}@x42OygW=32`al`Ob@QHT>R-v zKF{YI9V{d~6_KBDZ}$X7h;XZsEqoqX(Q|{UE3)YwrN*V?tX8@&q`?T?_a-nC34!wv zQYzhsVkST(ulG<`0$M~0FkFo3Z*tycQ0X_%a~t+P!JUQg;F@Q}9i#cK-%vX0;Ywz> z>d48k^gvzcpA83ceV;o#WK&bS-fA1ddSB0A{|CH6O4@Jj>UL^0a*1ag$fh`1E8_5|0FI$Ga`t(v`zY3 zO)}so?9-We_jv~~?tSy8ND3&_vnDZGLS7#8=wc`ubdxZxc`}DYOJ9Q&5r%5OcENk` zuSfuP<_;0|sKvEZ;Z+AKK!jITO(Ykl-5Yhb|MA+qI}k#t%vGiH{Q6a@uT48~mX)P1 zzVI6Nv4ixg`9TtgS7ddM#WWw$2V;f=|IcPENv%|?ft*=A4Ahu`RD+hxm*0{c)>>91 z%}>%TZ9F7yj(Z|4;p5@E20#d1KV(oPEJG0fy#?dFK$Ag`{FZCP+*avKDq|H39)sNf zw?S7%24zeI>+>M4Ec1->Et>$};%V(yO3pMcaj<>PcviAM@FEW8ju^5%Ud;yF2Ze5#GIeneG^wY42=aYY4Af7tGR*~yYQekSinZVwsgm|`!6{jtN(X;~tEqgz zbOwG$b28w+J(^%yLyjn!R{KeV0u$(pIgWDIS_Sf@4uyWCm(6HmeM5s zfNFD?Aok^*2?mp;kuQCQvJNp*;@9R>w-VwT`gWyv7r_0thL(}y2Aw}8Nf63_w*ue1 zZtM~p6azJqi-OatP2QXxm+W!{r;I$Xg6t3c?^~Lwf7rs!=pnt3yl(b?%0-LfWZ*zr z+*EhpMH|4P*!`Jdfc1ekDZ1B7p4uzfoN5A7LbAt`nVolxE!n(FJ${g8Vd#=%B+KM_ z^m?$ibq(*X!0*z(Bs*N@GM!c*=-XRFb~sA3IGJ+>j&nDrlU)T_mggq+Hx;DlU`h$2 z(aF-G$EtR8^7`BnF*}g|8KBLRX}F!$>Ircxr`Nur?X~iyR^i*VM)Z`W5>)q@4!=?|^K_7)g7%VUHr~UIf$5x@x(5S95Pp_GD-j0n+E{33g5` z(RDsUac_-G49OePT9q0)!@E@lnHQpRDUsLcbdSthZa|G8f!EZ^$%*1vGIt-{=0qMu z+nwU6sR3_3?jPrFBD}<#Ak`WkwdNf{nJ33tuQ*sED?~|+s!I@#I8Vo$x``>3Z!?Wt zVijU*jxKGNjC!2tk#V%tV^U!(wqe-NG%WYe$xBQ$yXsG$K~!d*F?hGkWrUS+Cj$dz zY7o?9ZB4qEJ7pZ(n4~+?qbJ0>%l7t4YVIFS{Dz(2*GcZrtSx z!}UaNS~1?xwqFbgI--X-(pAVznt!j6(aAduKAD<#GJKPXj`8=_pCrY~`p==P&4XD~b=dyzZYUVU%8zSfrqnUEClz&-BbWnkHp&Fb45MhtGHdFeEEsF>lUNNqV!V6Y6dXI)<#) zGk9TCH|GLk(`mQcku{jqaiV1FgWSuwqNzO*Js+^ze$BmG`8vURXq0dv(3j%sDm@-H+UWO$~t3)0M4=BY)(W^I_EFwYf zWzETI-6mamAB#X&`G%sKz}BJ`hL)&giZ9FPHm6L|lkzhJtFoyt22oS4;Qrx)LoUIs zV|6NOiTEgpPC&a^($ybEz}jm0_hVur{o3>kutOGXD-T%~*&re&8_T}tT(57k(ZP>3 zB#JMGX-_p&AwvrWBAUQBx#xd^Po(3oQlK1}M70>fnfkUYRRP|!_E)|aH$n2e-ZlVq)i()8>OBB4EZtv=l_(l+h*(k8ikNrx z7;obqgRKaVZ3*p_%}!H`(zS*W#8{fqOr!p#2>ZU80o-BsyOp~;EKkCdc z0~+rSgLJ;(zES|gc6{6todD#O)1q2MSkdCqogrqYz=i7#Z8-F(n(uWj5V5&Ici>vd z7{}jaj2=aUJgQ>m$WiwBq1UatCYntbP@svL#MuNQ)45}NZ^V&C{;`|)TK7YsF)oLh zF)0k#VIk7q>n7s=^d_2ye1u?AjfxmJY)xMM*Z+K57JLm(*0Zb= zXO6VTzbq-cwddi>M~Ig6n-z)RGq!wtQIIp-l3#li;nN(vE~0lyZTOMm>eZeRLU)If zp@wv^G~6PFws%sgC;sB?nxZ`h>cy)jVVV>#=| zES1koG70jKCyS4k$tO`<3z6$K*d`^^6Me6%qrII1bAJVk&uPp~@5a$_Z-L=B{f=R; z>)t*QeXx!1xp}6hSzFazK6Yxnz3n-W&_ky)RnA8?U|Pz2_*&ZUYvcD7tIh--&_uIx zpyzQV*&Dn|q#82sO_Pcvni+}*K4L6bTF?N)Y9v0B6H{zMMUQ3Dl+w>?sR8yK;!P|l z8U3+DTb#F@0nE}m_aae5xw$sY{fuYGJ7=A4At(tGL)~&F?m#6yAKZvh7_rB3-J7ZNNdBG z{WP->QTzGfYxjMbeX$AzqafX3#8eWVOcfj33RpW<-SqBu44f_3Zq^`pbFk_K2l`r1 zKNy%#(zOOLlM~0h1#}HgfyA{5@Yk$y0gFVHHMIHZr=LJaX$Y!)TI_}rI5%|zDifkt zRSU^_61Ie#Oy=>r+u>(J5Il1?TN91SdXF^*_~J0OFf8IZ}V{b?Fg-fXodR zOP^6M&x~#a)QV*XAn4vBQ{TRUbQ&IPce1pO}_`tYtuU;Z>OwEh%50>V!(Dp8)?f%q)>^P>^HmIjbQOJuS-uV3cAv8l( z&avlBvy)gd59JTY4-4Mpi1l-;>fwx}KqMC4t9jm)=lF7u!#7-Vb{#q&i$yj6*ozHF820bN~P0ylb7-NbxGv=EWgDe9mu>Oy_`DjtTk9T;tykbQxGjOgr zx%q=LO}O*GVnNSdC!Ae2OI zI_FFc?9f^w6VZ$!rOy;OdlHSRv{lZH8JoW!Sl=-Dw5NQn6L}0g3h1yiJ_r-<5UU;_5lTFGV;Ck^6u+o>R4G(gMK}l%Cw{nkD-1@5<=W3J`tiM7o?UQ zJkAcZdzlV1fdu%g zq-G?df%u`d-r>aUKEos>cF6Z>M$BdNhpPOmq^?TnPcYDko)tYkQ4;}<=ijBnYimPF zw36JK!#{;`zlVumSC8FrMeg^S z52qSi8R%bvvw2LU*p(NHJ^y=96=)G~vlVZoQseLWm&ybX2}yCfAd#1V+sCcP*LVa@ z8-3wim16WP#=Px-eJ*b2oip9MKu`gaSsD&quH8zD6G*7#?rWzBO7nnd*e1*%p|pNaw#Vr4W94fB_whG@}HgjQQ04v>xvc`a8nBVnG&?KwU#aQ$Hyy6fF z4y%5H6BU#!_Y?Aa=?dankp|Nbfv1G{9et>pujg}%Tvg(MPk zYXAm*b2vl=tpb`d_O6^UFkh^~gXMn)uQaH&fk^4cM_d^~*`Byu^OLTDP@SXpo}7$Jo791nr_8AB8xT)_#;M_D?~sq@;1zB=_7tARzcy*7n8Ss3YYC013PEnNK$E`9O>G6 z=6Li3QXweQJKN#m^uZi4CX2ehJ~bm#bW1@ZMH$=uz*i`%fqgJbA2eu6F()&1PiSxB z(SKz)H=@4mHJ2!72$||P5Jl5i`-1OF3^m=u{LSp($4*eCJoxK)eR|bSzOP*fxEv4d)Hmkj>gTwV>HDx2Gm(N&KZTKE+n0!QqJ^MG# zckUHB&`@%4``}W7Z9MvFCpOBy=?Sp}Y>uq;rsBT?xy<>G>E+p{f+Vp9`d3U<>*23G zN_36h(t|?=(}Gm)##4rU+Oa354$AB+TiOEm{=s&r)K=0&~L{sgJ(^ z46!xV&e?%c-gNb}hE1FWt6Ns{c%8j07y??^B!;gt(HTh~ebzHjl?M>Wez`H02Ss5s zUp{Dv_$8goGfZobvNFH32YH)<_e@1f;+^dLvV77i7Uv>J=`kru2|M6zPlGgpmXNRN z8bnje=!%tdB_RWN`gCVK?T~#dFt1+AO+YQn7{c9GORZrd4~jXvoy%ISOikC`v8pQ~ zs`IfBpV@D4vf;Sv*u=oM?~tJwaq(90HVZR-D^-2|`(jEv;Qh;_L=WF*Ml`PNB2Zof zPeXPnjX=z^@p(SI%D`Hp-rr+T>iXB!IjGJ(U*Ia%`+`y4H~5y1bM#}li|~D+P6t^f zRU}zSz2dx7QIEFSDMy5}&;7p){;tNY585B&!6~j_?>M5BtF)!O^_Q6XM2K41;IAg6 zE7R%0(*gkg$ZHK*hz45fX!dOKfiTD@Mgl;P)99ZgrO{Ea)T_={5$}XmdOWN~P?>XA zb4{GQj?tYq^p-Hd7tfFI!t>r~7y{Zv_*%{^;^8$!>Tx$a(F#85P-I%3>Q@nOuj0Li z1aqyR+l@?v!9RBC6Zxiqd8Wf&zKwAf?Fn#YVfLM~u8f>2#9!WGNLZJQ-=3S2*B4Fj zwzQR!U~L+?qp;wkLe#Zz`OvX*A2oT(cl}x^uoVOiPzo0a#fIXhizHS~Sx%cu`+Hg7 zrr73o{jKTT;*oa|s6U0lFQile@|v;vT_dA|_rQMR-k&U^w}--2uwP8I{Q^p2rvoii zJ5pvva5ZKmiNY2{iOPw>!y9a5ZtS2=z7s>c0{9t~ec9Y=uErsPo;p&(I1q6yHg5&^ayWoa&XR`0TuLqMV8 zDe&Q6o`}!dxT0$F9AcYEWq*{l9$N>&N75NZ&nP7ujO7`55CHs?h#JHkJ)!|e!yiUw zQks>A{T&saw_|-s8A0XyPq+yHt~|k+w?&_iLmY0Q+|Gv2i+|#hb^y33staIh?r!@- ze;=r1|IdqeiHQcfJ~|Cso6s^uhX$~o1#!z1N>AvGR&#mEd*os1F)~)}YL=i>B_yn| zt~TjYEPE^2GD?J^2uKdilZBP{{}Dpv2BF&9JhdtDtosTG4<9k0<>uxX*!-$m_DTXhx_fjMx51238dhY5DG7nG=&8$`Eo@RwpW(In@34SoT zfc#LPIBC><4t?EOZvvZ!wuE$qw^br z7}>?35hR%iH(20O*`BNiM?;%!YFVM~=5kfn1=dgSoNq0tT(4VfuH_P@s0yxJ`^^Qz z4@rXeoVAP+rjp6zk#t(r^zcr+re%hK_%t6UV;y}OZih;2;R*xP>%dow*;`f5OSJic3p1tK zR(poL&1rYC=E*KRIZ@iF7&(tq5I8kk!f3cy;rL%gV+bQlSft4et|rLHydotOlydJ| zFC%)gceVsE*Z8y0{n=B|2k#j0Tx%r`&&pH&V$Ywm)x|zQ-fs~7aF?u*-j=Q;^k`07 zxj{f>cSm@LWHtMPiRw?JyOYm{q|t|4u@fKwJPMLR_vinUOg m2wVg4j!=P|Q>@kS10}cri?Qok#pOOmpV| literal 0 HcmV?d00001 diff --git a/src/osp-string/pl.po b/src/osp-string/pl.po new file mode 100755 index 0000000..4c6f2e7 --- /dev/null +++ b/src/osp-string/pl.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Anuluj" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Typ aplikacji" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Aplikacja domyślna" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Wybierz aplikację domyślną" + diff --git a/src/osp-string/pt_PT.po b/src/osp-string/pt_PT.po new file mode 100755 index 0000000..7660476 --- /dev/null +++ b/src/osp-string/pt_PT.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Cancelar" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Tipo de aplicação" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Aplicação padrão" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Seleccionar aplicação padrão" + diff --git a/src/osp-string/ro.po b/src/osp-string/ro.po new file mode 100755 index 0000000..da1b5c4 --- /dev/null +++ b/src/osp-string/ro.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Anulare" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Tip de aplicaÅ£ie" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "AplicaÅ£ie implicită" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Selectare aplicaÅ£ie implicită" + diff --git a/src/osp-string/ru_RU.po b/src/osp-string/ru_RU.po new file mode 100755 index 0000000..2b0b7b9 --- /dev/null +++ b/src/osp-string/ru_RU.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Отмена" + +msgid "IDS_COM_SK_OK" +msgstr "Да" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Тип приложения" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Приложение по умолчанию" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Выберите приложение по умолчанию" + diff --git a/src/osp-string/sk.po b/src/osp-string/sk.po new file mode 100755 index 0000000..748008d --- /dev/null +++ b/src/osp-string/sk.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "ZruÅ¡iÅ¥" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Typ aplikácie" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Predvolená aplikácia" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "VybraÅ¥ predvolenú aplikáciu" + diff --git a/src/osp-string/sl.po b/src/osp-string/sl.po new file mode 100755 index 0000000..bb788d2 --- /dev/null +++ b/src/osp-string/sl.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Prekliči" + +msgid "IDS_COM_SK_OK" +msgstr "V redu" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Vrsta programa" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Privzeti program" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Izberite privzeti program" + diff --git a/src/osp-string/sr.po b/src/osp-string/sr.po new file mode 100755 index 0000000..0ce9ce9 --- /dev/null +++ b/src/osp-string/sr.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "PoniÅ¡ti" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Tip aplikacije" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Podrazumevana aplikacija" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Izaberi podrazumevanu aplikaciju" + diff --git a/src/osp-string/sv.po b/src/osp-string/sv.po new file mode 100755 index 0000000..3586b79 --- /dev/null +++ b/src/osp-string/sv.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Avbryt" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Programtyp" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Standardprogram" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Välj standardprogram" + diff --git a/src/osp-string/th.po b/src/osp-string/th.po new file mode 100755 index 0000000..d5a30de --- /dev/null +++ b/src/osp-string/th.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "ยก​เลิก" + +msgid "IDS_COM_SK_OK" +msgstr "ตกลง" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "ชนิด​แอ​พพลิ​เค​ชั่น" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "แอ​พพลิ​เค​ชั่น​พื้น​ฐาน" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "เลือก​แอ​พพลิ​เค​ชั่น​พื้น​ฐาน" + diff --git a/src/osp-string/tr_TR.po b/src/osp-string/tr_TR.po new file mode 100755 index 0000000..727de30 --- /dev/null +++ b/src/osp-string/tr_TR.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Ä°ptal" + +msgid "IDS_COM_SK_OK" +msgstr "Tamam" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Uygulama tipi" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Varsayılan uygulama" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Varsayılan uygulamayı seç" + diff --git a/src/osp-string/uk.po b/src/osp-string/uk.po new file mode 100755 index 0000000..24e4e47 --- /dev/null +++ b/src/osp-string/uk.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Скасувати" + +msgid "IDS_COM_SK_OK" +msgstr "ОК" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Тип програми" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Стандартна програма" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Вибір стандартної програми" + diff --git a/src/osp-string/vi.po b/src/osp-string/vi.po new file mode 100755 index 0000000..be0031e --- /dev/null +++ b/src/osp-string/vi.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "Hủy" + +msgid "IDS_COM_SK_OK" +msgstr "OK" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "Loại ứng dụng" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "Ứng dụng mặc định" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "Chọn ứng dụng mặc định" + diff --git a/src/osp-string/zh_CN.po b/src/osp-string/zh_CN.po new file mode 100755 index 0000000..d840ea4 --- /dev/null +++ b/src/osp-string/zh_CN.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "取消" + +msgid "IDS_COM_SK_OK" +msgstr "确定" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "应用程序类型" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "默认应用程序" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "选择默认应用程序" + diff --git a/src/osp-string/zh_HK.po b/src/osp-string/zh_HK.po new file mode 100755 index 0000000..5ef5397 --- /dev/null +++ b/src/osp-string/zh_HK.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "取消" + +msgid "IDS_COM_SK_OK" +msgstr "確定" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "應用程式類型" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "預設應用程式" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "請選擇預設的應用程式" + diff --git a/src/osp-string/zh_TW.po b/src/osp-string/zh_TW.po new file mode 100755 index 0000000..3956840 --- /dev/null +++ b/src/osp-string/zh_TW.po @@ -0,0 +1,15 @@ +msgid "IDS_COM_SK_CANCEL" +msgstr "取消" + +msgid "IDS_COM_SK_OK" +msgstr "確定" + +msgid "IDS_COM_POP_APPLICATION_TYPE" +msgstr "應用程式種類" + +msgid "IDS_COM_POP_DEFAULT_APPLICATION" +msgstr "預設應用程式" + +msgid "IDS_COM_POP_SELECT_DEFAULT_APPLICATION" +msgstr "選擇預設的應用程序" + diff --git a/src/security/CMakeLists.txt b/src/security/CMakeLists.txt new file mode 100755 index 0000000..082a630 --- /dev/null +++ b/src/security/CMakeLists.txt @@ -0,0 +1,93 @@ +SET (this_target security) + +INCLUDE_DIRECTORIES( + ${SLP_INCLUDE_DIRS} + /usr/include/chromium + cert + inc + ./ + ${CMAKE_SOURCE_DIR}/inc + ${CMAKE_SOURCE_DIR}/src/base/inc + ${CMAKE_SOURCE_DIR}/src/net/inc + ${CMAKE_SOURCE_DIR}/src/io/inc + ${CMAKE_SOURCE_DIR}/src/app/inc + ${CMAKE_SOURCE_DIR}/src/system/inc + ) + +SET (${this_target}_SOURCE_FILES + crypto/FSecCryptoAesCipher.cpp + crypto/FSecCryptoDesEdeCipher.cpp + crypto/FSecCryptoDesCipher.cpp + crypto/FSecCryptoRc2Cipher.cpp + crypto/FSecCryptoRc4Cipher.cpp + crypto/FSecCryptoCastCipher.cpp + crypto/FSecCryptoMd5Hash.cpp + crypto/FSecCryptoSha1Hash.cpp + crypto/FSecCryptoSha2Hash.cpp + crypto/FSecCryptoMd5Hmac.cpp + crypto/FSecCryptoSha1Hmac.cpp + crypto/FSecCryptoSha2Hmac.cpp + crypto/FSecCryptoDhKeyExchange.cpp + crypto/FSecCryptoKeaKeyExchange.cpp + crypto/FSecCrypto_SymmetricCipher.cpp + crypto/FSecCrypto_SkipJackCore.cpp + crypto/FSecCrypto_KeaCore.cpp + crypto/FSecCrypto_SkipJackModes.cpp + crypto/FSecCryptoSkipJackCipher.cpp + crypto/FSecCryptoRsaCipher.cpp + crypto/FSecCryptoRsaSignature.cpp + cert/FSecCertX509Certificate.cpp + cert/FSecCertX509CertificatePath.cpp + cert/FSecCertX509CertificateSelector.cpp + cert/FSecCertX509CertificateStore.cpp + cert/FSecCert_X509CertificateStoreImpl.cpp + cert/FSecCert_CertServiceProxy.cpp + #pkcs/FSecPkcsAlgorithmIdentifier.cpp + #pkcs/FSecPkcsInitialVector.cpp + #pkcs/FSecPkcsPkcs05PbMacParameters.cpp + #pkcs/FSecPkcsRc2CbcParameters.cpp + #pkcs/FSecPkcs_PkcsUtility.cpp + #pkcs/FSecPkcsPkcs05PbKdf2Parameters.cpp + #pkcs/FSecPkcsPkcs05PbEs2Parameters.cpp + #pkcs/FSecPkcsPkcs05Schemes.cpp + #pkcs/FSecPkcsPkcs08PrivateKeyInfo.cpp + #pkcs/FSecPkcsPkcs08EncryptedPrivateKeyInfo.cpp + FSecSecretKey.cpp + FSecSecretKeyGenerator.cpp + FSecAesSecureRandom.cpp + FSecPrivateKey.cpp + FSecPublicKey.cpp + FSecKeyPair.cpp + FSecKeyPairGenerator.cpp + FSecDesSecureRandom.cpp + FSecDesEdeSecureRandom.cpp + FSecDhKeyParameters.cpp + FSecKeaKeyParameters.cpp + FSec_DeviceKeyGenerator.cpp + #FSec_DeviceKeyGeneratorMessage.cpp + FSecAccessController.cpp + FSec_AccessController.cpp + FSec_PrivilegeCache.cpp + FSec_PrivilegeManager.cpp + FSec_PrivilegeInfo.cpp + FSec_PrivilegeManagerMessage.cpp + FSec_Prng.cpp + FSec_GenerateParameters.cpp +) + +INCLUDE(${CMAKE_SOURCE_DIR}/src/security/cert/CMakeLists.txt) +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") + +## SET EXTRA COMPILER FLAGS +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fPIC" ) + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} STATIC ${${this_target}_SOURCE_FILES}) + +ADD_DEFINITIONS(-D__USE_SERVER_TIME) diff --git a/src/security/FSecAccessController.cpp b/src/security/FSecAccessController.cpp new file mode 100644 index 0000000..383e397 --- /dev/null +++ b/src/security/FSecAccessController.cpp @@ -0,0 +1,189 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecAccessController.cpp + * @brief This is the implementation for the AccessController class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSec_AccessControlTypes.h" +#include "FSec_PrivilegeManager.h" +#include "FSec_PrivilegeManagerMessage.h" +#include "FSec_PrivilegeInfo.h" + + +using namespace Tizen::App; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +static _IpcClient ipcClient; +static bool isConstructed = false; + +namespace Tizen { namespace Security +{ + +AccessController::AccessController(void) +{ + +} + +AccessController::~AccessController(void) +{ + +} + +static _PrivilegeInfo privilegeInfo; + + +void +AccessController::Initialize(void) +{ + result r = E_SUCCESS; + result ipcResult = E_SUCCESS; + + std::unique_ptr pEncryptedPrivileges(null); + std::unique_ptr pChecksum(null); + std::unique_ptr pEncryptedVisibility(null); + std::unique_ptr pVisibilityChecksum(null); + + std::unique_ptr pCipherPrivilegeMessage(null); + std::unique_ptr pCipherVisibilityMessage(null); + + + SysLog(NID_SEC, "Enter"); + + r = ipcClient.Construct(L"osp.security.ipcserver.privilegemanager", null); + SysTryReturnVoidResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "Failed to construct the instance of IPC."); + + pEncryptedPrivileges.reset(new (std::nothrow) String()); + SysTryReturnVoidResult(NID_SEC, pEncryptedPrivileges != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pChecksum.reset(new (std::nothrow) String()); + SysTryReturnVoidResult(NID_SEC, pChecksum != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pCipherPrivilegeMessage.reset(new (std::nothrow) PrivilegeManagerMsg_retrieve(pEncryptedPrivileges.get(), pChecksum.get(), &r)); + SysTryReturnVoidResult(NID_SEC, pCipherPrivilegeMessage != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + ipcResult = ipcClient.SendRequest(pCipherPrivilegeMessage.get()); + SysTryReturnVoidResult(NID_SEC, ipcResult == E_SUCCESS, E_SYSTEM, "Failed to send IPC message."); + SysTryReturnVoidResult(NID_SEC, r == E_SUCCESS, r, "Failed to retrieve privilege information"); + + pEncryptedVisibility.reset(new (std::nothrow) String()); + SysTryReturnVoidResult(NID_SEC, pEncryptedVisibility != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pVisibilityChecksum.reset(new (std::nothrow) String()); + SysTryReturnVoidResult(NID_SEC, pVisibilityChecksum != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pCipherVisibilityMessage.reset(new (std::nothrow) PrivilegeManagerMsg_retrieveEx(pEncryptedVisibility.get(), pVisibilityChecksum.get(), &r)); + SysTryReturnVoidResult(NID_SEC, pCipherVisibilityMessage != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + ipcResult = ipcClient.SendRequest(pCipherVisibilityMessage.get()); + SysTryReturnVoidResult(NID_SEC, ipcResult == E_SUCCESS, E_SYSTEM, "Failed to send IPC message."); + SysTryReturnVoidResult(NID_SEC, r == E_SUCCESS, r, "Failed to retrieve privilege information"); + + const PackageId& packageId = _AppInfo::GetPackageId(); + + r = privilegeInfo.Construct(packageId, *(pEncryptedPrivileges.get()), *(pChecksum.get()), *(pEncryptedVisibility.get()), *(pVisibilityChecksum.get())); + SysTryReturnVoidResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + isConstructed = true; + + SysLog(NID_SEC, "Exit"); + return; +} + +result +AccessController::CheckPrivilege(int privilege) +{ + result r = E_SUCCESS; + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + bool ret = false; + + SysLog(NID_SEC, "Enter."); + ClearLastResult(); + + SysTryReturnResult(NID_SEC, privilege < _MAX_PRIVILEGE_ENUM, E_INVALID_ARG, "The privilege enumerator is invalid"); + + if (!isConstructed) + { + pthread_once(&onceBlock, Initialize); + r = GetLastResult(); + if (IsFailed(r)) + { + if (r == E_DATA_NOT_FOUND) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + goto CATCH; + } + else + { + onceBlock = PTHREAD_ONCE_INIT; + SysLogException(NID_SEC, r, "[%s] Propagated.", GetErrorMessage(r)); + } + return r; + } + } + + if (privilegeInfo.GetAppId().IsEmpty()) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + r = E_DATA_NOT_FOUND; + goto CATCH; + } + else + { + SysLog(NID_SEC, "%ls is in the cache [client]", privilegeInfo.GetAppId().GetPointer()); + } + + ret = privilegeInfo.HasPrivilege(static_cast< _Privilege >(privilege)); + if (!ret) + { + r = E_PRIVILEGE_DENIED; + goto CATCH; + } + + SysLog(NID_SEC, "Exit."); + return r; + + +CATCH: + + SysLogException(NID_SEC, r, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + SysLog(NID_SEC, "Exit."); + + const PackageId& packageId = _AppInfo::GetPackageId(); + + _AppManagerImpl* pAppManagerImpl = _AppManagerImpl::GetInstance(); + pAppManagerImpl->TerminateApplications(packageId); + + return r; +} + +}} //Tizen::Security diff --git a/src/security/FSecAesSecureRandom.cpp b/src/security/FSecAesSecureRandom.cpp new file mode 100644 index 0000000..a738b99 --- /dev/null +++ b/src/security/FSecAesSecureRandom.cpp @@ -0,0 +1,67 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecAesSecureRandom.cpp + * @brief This is the implementation file for AesSecureRandom class. + */ +#include +#include +#include +#include +#include +#include +#include "FSec_Prng.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + + +namespace Tizen { namespace Security +{ + +AesSecureRandom::AesSecureRandom(void) + : __pAesSecureRandomImpl(null) +{ +} + +AesSecureRandom::~AesSecureRandom(void) +{ +} + +ByteBuffer* +AesSecureRandom::GenerateRandomBytesN(int numBytes) +{ + ByteBuffer* pRandomBytes = null; + + ClearLastResult(); + + SysTryReturn(NID_SEC, numBytes > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] The input number of bytes should be positive."); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[numBytes]); + SysTryReturn(NID_SEC, pTempBuf != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pTempBuf.get(), 0, numBytes); + + //call the GetRandomBytes of Prng class + pRandomBytes = _Prng::GetRandomBytesN(EVP_aes_128_ecb(), numBytes); + SysTryReturn(NID_SEC, pRandomBytes != null, null, GetLastResult(), "[%s]Failed to fill random bytes in buffer.", GetErrorMessage(GetLastResult())); + + return pRandomBytes; +} + +} } //Tizen::Security diff --git a/src/security/FSecDesEdeSecureRandom.cpp b/src/security/FSecDesEdeSecureRandom.cpp new file mode 100644 index 0000000..c61ea36 --- /dev/null +++ b/src/security/FSecDesEdeSecureRandom.cpp @@ -0,0 +1,67 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecDesEdeSecureRandom.cpp + * @brief This is the implementation file for DesEdeSecureRandom class. + */ +#include +#include +#include +#include +#include +#include +#include "FSec_Prng.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + + +namespace Tizen { namespace Security +{ + +DesEdeSecureRandom::DesEdeSecureRandom(void) + : __pDesEdeSecureRandomImpl(null) +{ +} + +DesEdeSecureRandom::~DesEdeSecureRandom(void) +{ +} + +ByteBuffer* +DesEdeSecureRandom::GenerateRandomBytesN(int numBytes) +{ + ByteBuffer* pRandomBytes = null; + + ClearLastResult(); + + SysTryReturn(NID_SEC, numBytes > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] The input number of bytes should be positive."); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[numBytes]); + SysTryReturn(NID_SEC, pTempBuf != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pTempBuf.get(), 0, numBytes); + + //call the GetRandomBytes of Prng class + pRandomBytes = _Prng::GetRandomBytesN(EVP_des_ede3_cbc(), numBytes); + SysTryReturn(NID_SEC, pRandomBytes != null, null, GetLastResult(), "[%s]Failed to fill random bytes in buffer.", GetErrorMessage(GetLastResult())); + + return pRandomBytes; +} + +} } //Tizen::Security diff --git a/src/security/FSecDesSecureRandom.cpp b/src/security/FSecDesSecureRandom.cpp new file mode 100644 index 0000000..c1fe768 --- /dev/null +++ b/src/security/FSecDesSecureRandom.cpp @@ -0,0 +1,67 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecDesSecureRandom.cpp + * @brief This is the implementation file for DesSecureRandom class. + */ +#include +#include +#include +#include +#include +#include +#include "FSec_Prng.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + + +namespace Tizen { namespace Security +{ + +DesSecureRandom::DesSecureRandom(void) + : __pDesSecureRandomImpl(null) +{ +} + +DesSecureRandom::~DesSecureRandom(void) +{ +} + +ByteBuffer* +DesSecureRandom::GenerateRandomBytesN(int numBytes) +{ + ByteBuffer* pRandomBytes = null; + + ClearLastResult(); + + SysTryReturn(NID_SEC, numBytes > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] The input number of bytes should be positive."); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[numBytes]); + SysTryReturn(NID_SEC, pTempBuf != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pTempBuf.get(), 0, numBytes); + + //call the GetRandomBytes of Prng class + pRandomBytes = _Prng::GetRandomBytesN(EVP_des_ecb(), numBytes); + SysTryReturn(NID_SEC, pRandomBytes != null, null, GetLastResult(), "[%s]Failed to fill random bytes in buffer.", GetErrorMessage(GetLastResult())); + + return pRandomBytes; +} + +} } //Tizen::Security diff --git a/src/security/FSecDhKeyParameters.cpp b/src/security/FSecDhKeyParameters.cpp new file mode 100644 index 0000000..883a644 --- /dev/null +++ b/src/security/FSecDhKeyParameters.cpp @@ -0,0 +1,107 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecDhKeyParameters.cpp + * @brief This header file contains the declaration of Tizen::Security::Crypto::DhKeyParameters. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security +{ + +DhKeyParameters::DhKeyParameters(void) + : __privateKeySize(0) + , __pDhKeyParametersImpl(null) +{ + +} + +DhKeyParameters::~DhKeyParameters(void) +{ + +} + +result +DhKeyParameters::Construct(const Tizen::Base::ByteBuffer& primeNumber, const Tizen::Base::ByteBuffer& generatorNumber, int privateKeySize) +{ + result r = E_SUCCESS; + + SysAssertf(__prime.GetPointer() == null && __prime.GetRemaining() == 0 && __generator.GetPointer() == null && __generator.GetRemaining() == 0, + "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + r = __prime.Construct(primeNumber); + SysTryReturn(NID_SEC, !IsFailed(r), r, r, "[%s] Input prime number is not valid.", GetErrorMessage(r)); + + r = __generator.Construct(generatorNumber); + SysTryReturn(NID_SEC, !IsFailed(r), r, r, "[%s] Input generator number is not valid.", GetErrorMessage(r)); + + __privateKeySize = privateKeySize; + + return E_SUCCESS; +} + +Tizen::Base::ByteBuffer* +DhKeyParameters::GetParameterValueN(KeyParameterType paramType) const +{ + result r = E_SUCCESS; + + ClearLastResult(); + + std::unique_ptr pOutput(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC, pOutput != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + switch (paramType) + { + case KEY_PARAMETER_DH_P: + r = pOutput->Construct(__prime); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Dh prime number should be valid.", GetErrorMessage(r)); + break; + + case KEY_PARAMETER_DH_G: + r = pOutput->Construct(__generator); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Dh generator number should be valid.", GetErrorMessage(r)); + break; + + default: + SysTryReturn(NID_SEC, false, null, E_UNSUPPORTED_TYPE, "[E_UNSUPPORTED_TYPE] The requested type is not supported"); + break; + } + + SetLastResult(r); + return pOutput.release(); +} + +int +DhKeyParameters::GetParameterSize(KeyParameterType paramType) const +{ + SysTryReturn(NID_SEC, paramType == KEY_PARAMETER_DH_PRIVATE_KEY_SIZE, 0, E_UNSUPPORTED_TYPE, "[E_UNSUPPORTED_TYPE] The input request is not supported."); + return __privateKeySize; +} + +} } //Tizen::Security diff --git a/src/security/FSecKeaKeyParameters.cpp b/src/security/FSecKeaKeyParameters.cpp new file mode 100644 index 0000000..2be92c1 --- /dev/null +++ b/src/security/FSecKeaKeyParameters.cpp @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecKeaKeyParameters.cpp + * @brief This header file contains the declaration of Tizen::Security::Crypto::KeaKeyParameters. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security +{ + +KeaKeyParameters::KeaKeyParameters(void) + : __privateKeySize(0) + , __pKeaKeyParametersImpl(null) +{ + +} + +KeaKeyParameters::~KeaKeyParameters(void) +{ + +} + +result +KeaKeyParameters::Construct(const Tizen::Base::ByteBuffer& primeNumber, const Tizen::Base::ByteBuffer& generatorNumber, int privateKeySize) +{ + result r = E_SUCCESS; + + SysAssertf(__prime.GetPointer() == null && __prime.GetRemaining() == 0 && __generator.GetPointer() == null && __generator.GetRemaining() == 0, + "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + r = __prime.Construct(primeNumber); + SysTryReturn(NID_SEC, !IsFailed(r), r, r, "[%s] Input prime number is not valid.", GetErrorMessage(r)); + + r = __generator.Construct(generatorNumber); + SysTryReturn(NID_SEC, !IsFailed(r), r, r, "[%s] Input generator number is not valid.", GetErrorMessage(r)); + + __privateKeySize = privateKeySize; + + return E_SUCCESS; +} + +Tizen::Base::ByteBuffer* +KeaKeyParameters::GetParameterValueN(KeyParameterType paramType) const +{ + result r = E_SUCCESS; + + ClearLastResult(); + + std::unique_ptr pOutput(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC, pOutput != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + switch (paramType) + { + case KEY_PARAMETER_KEA_P: + r = pOutput->Construct(__prime); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Kea prime number should be valid.", GetErrorMessage(r)); + break; + + case KEY_PARAMETER_KEA_G: + r = pOutput->Construct(__generator); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Kea generator number should be valid.", GetErrorMessage(r)); + break; + + default: + SysTryReturn(NID_SEC, false, null, E_UNSUPPORTED_TYPE, "[E_UNSUPPORTED_TYPE] The requested type is not supported"); + break; + } + + + SetLastResult(r); + return pOutput.release(); +} + +int +KeaKeyParameters::GetParameterSize(KeyParameterType paramType) const +{ + SysTryReturn(NID_SEC, paramType == KEY_PARAMETER_KEA_PRIVATE_KEY_SIZE, 0, E_UNSUPPORTED_TYPE, "[E_UNSUPPORTED_TYPE] The input request is not supported."); + return __privateKeySize; +} + +} } //Tizen::Security diff --git a/src/security/FSecKeyPair.cpp b/src/security/FSecKeyPair.cpp new file mode 100644 index 0000000..1cd90bb --- /dev/null +++ b/src/security/FSecKeyPair.cpp @@ -0,0 +1,116 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecKeyPair.cpp + * @brief This is the implementation file for KeyPair class. + */ +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Security; + + +namespace Tizen { namespace Security +{ + +KeyPair::KeyPair(void) + : __pPubKey(null) + , __pPriKey(null) + , __pKeyPairImpl(null) +{ +} + +KeyPair::~KeyPair(void) +{ + delete __pPubKey; + delete __pPriKey; +} + +result +KeyPair::Construct(IPublicKey& publicKey, IPrivateKey& privateKey) +{ + result r = E_SUCCESS; + + SysAssertf(__pPubKey == null && __pPriKey == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pPubKey = new (std::nothrow) PublicKey(); + SysTryReturn(NID_SEC, __pPubKey != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + __pPriKey = new (std::nothrow) PrivateKey(); + SysTryReturn(NID_SEC, __pPriKey != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + *__pPubKey = publicKey; + *__pPriKey = privateKey; + + return r; +} + +IPublicKey* +KeyPair::GetPublicKey(void) const +{ + return __pPubKey; +} + +IPrivateKey* +KeyPair::GetPrivateKey(void) const +{ + return __pPriKey; +} + +result +KeyPair::SetPublicKey(const ByteBuffer& pubKey) +{ + result r = E_SUCCESS; + + SysTryReturn(NID_SEC, static_cast< int >(pubKey.GetRemaining()) > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input public key size should be positive."); + + delete __pPubKey; + + __pPubKey = new (std::nothrow) PublicKey(); + SysTryReturn(NID_SEC, __pPubKey != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = __pPubKey->SetKey(pubKey); + SysTryReturn(NID_SEC, !IsFailed(r), r, r, "[%s] Failed to call set key operation.", GetErrorMessage(r)); + + return r; +} + +result +KeyPair::SetPrivateKey(const ByteBuffer& privKey) +{ + result r = E_SUCCESS; + + SysTryReturn(NID_SEC, privKey.GetRemaining() > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input private key size should be positive."); + + delete __pPriKey; + + __pPriKey = new (std::nothrow) PrivateKey(); + SysTryReturn(NID_SEC, __pPriKey != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = __pPriKey->SetKey(privKey); + SysTryReturn(NID_SEC, !IsFailed(r), r, r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + + return r; +} + +} } //Tizen::Security diff --git a/src/security/FSecKeyPairGenerator.cpp b/src/security/FSecKeyPairGenerator.cpp new file mode 100644 index 0000000..c44037b --- /dev/null +++ b/src/security/FSecKeyPairGenerator.cpp @@ -0,0 +1,413 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecKeyPairGenerator.cpp + * @brief This is the implementation file for KeyPairGenerator class. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSec_GenerateParameters.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + + +namespace Tizen { namespace Security +{ +static const int _BITS_IN_BYTE = 8; +static const int _PUBLIC_KEY_LENGTH = 1024; +static const char* _MAX_SECRET_E_VAL = "65537"; + +KeyPairGenerator::KeyPairGenerator(void) + : __modulusBitSize(0) + , __pKeyPairGeneratorImpl(null) +{ + __algorithm = L"RSA"; +} + +KeyPairGenerator::~KeyPairGenerator(void) +{ +} + +result +KeyPairGenerator::Construct(int modulusBitSize) +{ + result r = E_SUCCESS; + + SysTryReturn(NID_SEC, modulusBitSize, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The modulusBitSize should be positive."); + + __modulusBitSize = modulusBitSize; + + return r; + +} + +result +KeyPairGenerator::Construct(int modulusBitSize, Tizen::Base::String algorithm) +{ + SysTryReturn(NID_SEC, modulusBitSize, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input modulus bit size should be positive."); + SysTryReturn(NID_SEC, algorithm != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input algorithm value should be valid."); + SysTryReturn(NID_SEC, (algorithm.CompareTo(L"DH") == 0) || (algorithm.CompareTo(L"KEA") == 0) || (algorithm.CompareTo(L"RSA") == 0), E_UNSUPPORTED_ALGORITHM, E_UNSUPPORTED_ALGORITHM, "[E_UNSUPPORTED_ALGORITHM] The requested algorithm is not supported."); + + __modulusBitSize = modulusBitSize; + __algorithm = algorithm; + + return E_SUCCESS; + +} + +IKeyParameters* +KeyPairGenerator::GenerateKeyParametersN(int lInBits, int nInBits) const +{ + result r = E_SUCCESS; + int size = 0; + unsigned int dheSize = 0; + long seedLenInBytes = 0; + byte temp[_PUBLIC_KEY_LENGTH]; + ByteBuffer dhp; + ByteBuffer dhg; + IKeyParameters* pKeyParams = null; + DH* pDh = null; + + ClearLastResult(); + + seedLenInBytes = (nInBits / _BITS_IN_BYTE) + 1; + + SysTryReturn(NID_SEC, (__algorithm.CompareTo(L"DH") == 0) || (__algorithm.CompareTo(L"KEA") == 0), null, E_INVALID_ARG, "[E_INVALID_ARG] The requested algorithm is not supported."); + + pDh = DH_new(); + SysTryReturn(NID_SEC, pDh != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = _GenerateParameters::GenerateParametersX186(pDh, static_cast< long >(lInBits), static_cast< long >(nInBits), + seedLenInBytes); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "Failed to do generate parameters operation for prime and generator values."); + + SysTryCatch(NID_SEC, pDh->p != null && pDh->g != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Generated parameters prime and generator values should be valid."); + + memset(temp, 0, _PUBLIC_KEY_LENGTH); + + size = BN_bn2bin(pDh->p, temp); + SysTryCatch(NID_SEC, size > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = dhp.Construct(size); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = dhp.SetArray(temp, 0, size); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + dhp.Flip(); + + memset(temp, 0, _PUBLIC_KEY_LENGTH); + size = 0; + + size = BN_bn2bin(pDh->g, temp); + SysTryCatch(NID_SEC, size > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = dhg.Construct(size); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = dhg.SetArray(temp, 0, size); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + dhg.Flip(); + + dheSize = pDh->length; + + if (__algorithm.CompareTo(L"DH") == 0) + { + DhKeyParameters* pDHParams = new (std::nothrow) DhKeyParameters(); + SysTryCatch(NID_SEC, pDHParams != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pDHParams->Construct(dhp, dhg, static_cast< int >(dheSize)); + if (IsFailed(r)) + { + delete pDHParams; + SysLogException(NID_SEC, r, "Failed to do construct"); + goto CATCH; + } + pKeyParams = pDHParams; + } + else if (__algorithm.CompareTo(L"KEA") == 0) + { + KeaKeyParameters* pKeaParams = new (std::nothrow) KeaKeyParameters(); + SysTryCatch(NID_SEC, pKeaParams != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pKeaParams->Construct(dhp, dhg, static_cast< int >(dheSize)); + if (IsFailed(r)) + { + delete pKeaParams; + SysLogException(NID_SEC, r, "Failed to do construct"); + goto CATCH; + } + pKeyParams = pKeaParams; + } + +CATCH: + + if (pDh != null) + { + DH_free(pDh); + } + + SetLastResult(r); + return pKeyParams; +} + +KeyPair* +KeyPairGenerator::GenerateKeyPairN(Tizen::Security::IKeyParameters* pKeyParams) const +{ + result r = E_SUCCESS; + int ret = 0; + int paramSize = 0; + int size = 0; + byte* pBuffer = null; + byte temp[_PUBLIC_KEY_LENGTH]; + ByteBuffer privKey; + ByteBuffer pubKey; + KeyPair* pKeyPair = null; + BN_CTX* pCtx = null; + DH* pDh = null; + RSA* pRsa = null; + BIGNUM* pE = null; + EVP_PKEY* pEvpKey = null; + std::unique_ptr pDHp(null); + std::unique_ptr pDHg(null); + std::unique_ptr pPubKey(null); + std::unique_ptr pPriKey(null); + + ClearLastResult(); + + SysAssertf(__algorithm != null && __modulusBitSize > 0, "Not yet constructed. Construct() should be called before use."); + + SysTryReturn(NID_SEC, (__algorithm.CompareTo(L"DH") == 0) || (__algorithm.CompareTo(L"KEA") == 0) || (__algorithm.CompareTo(L"RSA") == 0), null, E_UNSUPPORTED_ALGORITHM, "[E_UNSUPPORTED_ALGORITHM] The requested algorithm is not supported."); + + if ((__algorithm.CompareTo(L"DH") == 0) || (__algorithm.CompareTo(L"KEA") == 0)) + { + if (__algorithm.CompareTo(L"DH") == 0) + { + DhKeyParameters* pDHParams = dynamic_cast< DhKeyParameters* >(pKeyParams); + SysTryReturn(NID_SEC, pDHParams != null, null, E_INVALID_ARG, " [E_INVALID_ARG] dh parameters value is not valid."); + + pDHp = std::unique_ptr (pDHParams->GetParameterValueN(KEY_PARAMETER_DH_P)); + SysTryReturn(NID_SEC, pDHp != null, null, GetLastResult(), " [%s] Dh prime value is not valid.", GetErrorMessage(GetLastResult())); + + pDHg = std::unique_ptr (pDHParams->GetParameterValueN(KEY_PARAMETER_DH_G)); + SysTryCatch(NID_SEC, pDHg != null, r = GetLastResult(), GetLastResult(), " [%s] Dh generator value is not valid.", GetErrorMessage(GetLastResult())); + + paramSize = pDHParams->GetParameterSize(KEY_PARAMETER_DH_PRIVATE_KEY_SIZE); + SysTryCatch(NID_SEC, paramSize > 0, r = GetLastResult(), GetLastResult(), " [%s] The dh private key size should be positive.", GetErrorMessage(GetLastResult())); + } + else + { + KeaKeyParameters* pKeaParams = dynamic_cast< KeaKeyParameters* >(pKeyParams); + SysTryReturn(NID_SEC, pKeaParams != null, null, E_INVALID_ARG, " [E_INVALID_ARG] kea parameters value is not valid."); + + pDHp = std::unique_ptr (pKeaParams->GetParameterValueN(KEY_PARAMETER_KEA_P)); + SysTryReturn(NID_SEC, pDHp != null, null, GetLastResult(), " [%s] Kea prime value is not valid.", GetErrorMessage(GetLastResult())); + + pDHg = std::unique_ptr (pKeaParams->GetParameterValueN(KEY_PARAMETER_KEA_G)); + SysTryCatch(NID_SEC, pDHg != null, r = GetLastResult(), GetLastResult(), " [%s] Kea generator value is not valid.", GetErrorMessage(GetLastResult())); + + paramSize = pKeaParams->GetParameterSize(KEY_PARAMETER_KEA_PRIVATE_KEY_SIZE); + SysTryCatch(NID_SEC, paramSize > 0, r = GetLastResult(), GetLastResult(), " [%s] The kea private key size should be positive.", GetErrorMessage(GetLastResult())); + } + + pDh = DH_new(); + SysTryCatch(NID_SEC, pDh != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pDh->p = BN_bin2bn(pDHp->GetPointer(), pDHp->GetRemaining(), null); + SysTryCatch(NID_SEC, pDh->p != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pDh->g = BN_bin2bn(pDHg->GetPointer(), pDHg->GetRemaining(), null); + SysTryCatch(NID_SEC, pDh->g != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pDh->length = paramSize * _BITS_IN_BYTE; + + ret = DH_generate_key(pDh); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + memset(temp, 0, _PUBLIC_KEY_LENGTH); + + size = BN_bn2bin(pDh->priv_key, temp); + SysTryCatch(NID_SEC, size > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = privKey.Construct(size); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = privKey.SetArray(temp, 0, size); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + privKey.Flip(); + + memset(temp, 0, _PUBLIC_KEY_LENGTH); + size = 0; + + size = BN_bn2bin(pDh->pub_key, temp); + SysTryCatch(NID_SEC, size > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = pubKey.Construct(size); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pubKey.SetArray(temp, 0, size); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pubKey.Flip(); + + pPubKey = std::unique_ptr (new (std::nothrow) PublicKey()); + SysTryCatch(NID_SEC, pPubKey != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pPubKey->SetKey(pubKey); + + pPriKey = std::unique_ptr (new (std::nothrow) PrivateKey()); + SysTryCatch(NID_SEC, pPriKey != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pPriKey->SetKey(privKey); + + } + else if (__algorithm.CompareTo(L"RSA") == 0) + { + pCtx = BN_CTX_new(); + SysTryReturn(NID_SEC, pCtx != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + BN_CTX_start(pCtx); + + pRsa = RSA_new(); + SysTryCatch(NID_SEC, pRsa != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pE = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pE != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + ret = BN_dec2bn(&pE, _MAX_SECRET_E_VAL); + SysTryCatch(NID_SEC, ret != 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = RSA_generate_key_ex(pRsa, __modulusBitSize, pE, null); + SysTryCatch(NID_SEC, ret != 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pEvpKey = EVP_PKEY_new(); + SysTryCatch(NID_SEC, pEvpKey != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + ret = EVP_PKEY_set1_RSA(pEvpKey, pRsa); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = i2d_PrivateKey(pEvpKey, &pBuffer); + SysTryCatch(NID_SEC, ret != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = privKey.Construct(ret); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = privKey.SetArray(pBuffer, 0, ret); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + privKey.Flip(); + + OPENSSL_free(pBuffer); + pBuffer = null; + + ret = i2d_PublicKey(pEvpKey, &pBuffer); + SysTryCatch(NID_SEC, ret != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = pubKey.Construct(ret); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pubKey.SetArray(pBuffer, 0, ret); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pubKey.Flip(); + + pPubKey = std::unique_ptr (new (std::nothrow) PublicKey()); + SysTryCatch(NID_SEC, pPubKey != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pPubKey->SetKey(pubKey); + + pPriKey = std::unique_ptr (new (std::nothrow) PrivateKey()); + SysTryCatch(NID_SEC, pPriKey != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pPriKey->SetKey(privKey); + + } + + pKeyPair = new (std::nothrow) KeyPair(); + SysTryCatch(NID_SEC, pKeyPair != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pKeyPair->SetPrivateKey(privKey); + SysTryCatch(NID_SEC, !IsFailed(r), , r, "[%s] Failed to do set private key operation.", GetErrorMessage(r)); + + r = pKeyPair->SetPublicKey(pubKey); + SysTryCatch(NID_SEC, !IsFailed(r), , r, "[%s] Failed to do set public key operation.", GetErrorMessage(r)); + +CATCH: + + if (pDh != null) + { + DH_free(pDh); + } + if (pCtx != null) + { + BN_CTX_end(pCtx); + BN_CTX_free(pCtx); + } + if (pEvpKey != null) + { + EVP_PKEY_free(pEvpKey); + } + if (pBuffer != null) + { + OPENSSL_free(pBuffer); + } + if (pRsa != null) + { + RSA_free(pRsa); + } + if (IsFailed(r)) + { + delete pKeyPair; + pKeyPair = null; + } + + return pKeyPair; +} + +KeyPair* +KeyPairGenerator::GenerateKeyPairN(void) const +{ + KeyPair* pKeyPair = null; + + ClearLastResult(); + + SysAssertf(__algorithm != null, "Not yet constructed. Construct() should be called before use."); + + SysTryReturn(NID_SEC, __algorithm.CompareTo(L"RSA") == 0, null, E_UNSUPPORTED_ALGORITHM, "[E_UNSUPPORTED_ALGORITHM] The requested algorithm is not supported."); + + pKeyPair = GenerateKeyPairN(null); + SysTryReturn(NID_SEC, pKeyPair != null, null, GetLastResult(), "[%s] Failed to retrieve key pair for rsa", GetErrorMessage(GetLastResult())); + + return pKeyPair; +} + +} } //Tizen::Security diff --git a/src/security/FSecPrivateKey.cpp b/src/security/FSecPrivateKey.cpp new file mode 100644 index 0000000..74a38d6 --- /dev/null +++ b/src/security/FSecPrivateKey.cpp @@ -0,0 +1,74 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecPrivateKey.cpp + * @brief This is the implementation file for PrivateKey class. + * + * This header file contains the implementation of PrivateKey class. + */ +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security +{ + +PrivateKey::PrivateKey(void) + : __pPrivateKeyImpl(null) +{ + __algorithm = L"RSA"; + __encodedFormat = L"ASN.1"; +} + +PrivateKey::~PrivateKey(void) +{ +} + +String +PrivateKey::GetFormat(void) const +{ + return __encodedFormat; +} + +ByteBuffer* +PrivateKey::GetEncodedN(void) const +{ + result r = E_SUCCESS; + + ClearLastResult(); + + std::unique_ptr pKeyBuffer(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC, pKeyBuffer != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pKeyBuffer->Construct(__keyBytes); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Input key buffer is not valid.", GetErrorMessage(r)); + + return pKeyBuffer.release(); +} + +result +PrivateKey::SetKey(const ByteBuffer& keyBuffer) +{ + return __keyBytes.Construct(keyBuffer); +} + +} } //Tizen::Security diff --git a/src/security/FSecPublicKey.cpp b/src/security/FSecPublicKey.cpp new file mode 100644 index 0000000..dfe4344 --- /dev/null +++ b/src/security/FSecPublicKey.cpp @@ -0,0 +1,74 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecPublicKey.cpp + * @brief This is the implementation file for PublicKey class. + * + * This header file contains the implementation of PublicKey class. + */ +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security +{ + +PublicKey::PublicKey(void) + : __pPublicKeyImpl(null) +{ + __algorithm = L"RSA"; + __encodedFormat = L"ASN.1"; +} + +PublicKey::~PublicKey(void) +{ +} + +String +PublicKey::GetFormat(void) const +{ + return __encodedFormat; +} + +ByteBuffer* +PublicKey::GetEncodedN(void) const +{ + result r = E_SUCCESS; + + ClearLastResult(); + + std::unique_ptr pKeyBuffer(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC, pKeyBuffer != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pKeyBuffer->Construct(__keyBytes); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Input key buffer is not valid.", GetErrorMessage(r)); + + return pKeyBuffer.release(); +} + +result +PublicKey::SetKey(const ByteBuffer& keyBuffer) +{ + return __keyBytes.Construct(keyBuffer); +} + +} } //Tizen::Security diff --git a/src/security/FSecSecretKey.cpp b/src/security/FSecSecretKey.cpp new file mode 100644 index 0000000..d0c5d66 --- /dev/null +++ b/src/security/FSecSecretKey.cpp @@ -0,0 +1,74 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecSecretKey.cpp + * @brief This is the implementation file for SecretKey class. + */ +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security +{ + +SecretKey::SecretKey(void) + : __pSecretKeyImpl(null) +{ +} + +SecretKey::~SecretKey(void) +{ +} + +String +SecretKey::GetFormat(void) const +{ + String encodedFormat = L"NONE"; + + return encodedFormat; +} + +ByteBuffer* +SecretKey::GetEncodedN(void) const +{ + result r = E_SUCCESS; + + ClearLastResult(); + + std::unique_ptr pKeyBuffer(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC, pKeyBuffer != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory"); + + r = pKeyBuffer->Construct(__keyBytes); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Input key buffer is not valid.", GetErrorMessage(r)); + + return pKeyBuffer.release(); +} + +result +SecretKey::SetKey(const ByteBuffer& keyBuffer) +{ + //Store the secret key + return __keyBytes.Construct(keyBuffer); +} + +} } //Tizen::Security diff --git a/src/security/FSecSecretKeyGenerator.cpp b/src/security/FSecSecretKeyGenerator.cpp new file mode 100644 index 0000000..42d4ac7 --- /dev/null +++ b/src/security/FSecSecretKeyGenerator.cpp @@ -0,0 +1,146 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecSecretKeyGenerator.cpp + * @brief This file contains the implementation of SecretKeyGenerator class. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security +{ +static const int _MAX_DES_KEY_GEN_SIZE = 8; +static const int _MAX_AES_KEY_GEN_SIZE = 16; +static const int _MAX_DES_EDE_KEY_GEN_SIZE = 24; +static const int _DEFAULT_KEY_SIZE = 32; + +SecretKeyGenerator::SecretKeyGenerator(void) + : __keyGenSize(0) + , __pRandom(null) + , __pSecretKeyGeneratorImpl(null) +{ +} + +SecretKeyGenerator::~SecretKeyGenerator(void) +{ + delete __pRandom; +} + +result +SecretKeyGenerator::Construct(const Tizen::Base::ByteBuffer& keyBuffer) +{ + result r = E_SUCCESS; + + SysAssertf(__keyBytes.GetPointer() == null && __keyBytes.GetRemaining() == 0, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + r = __keyBytes.Construct(keyBuffer); + SysTryReturn(NID_SEC, !IsFailed(r), r, r, "[%s] Input key data should be valid.", GetErrorMessage(r)); + + return r; +} + +result +SecretKeyGenerator::Construct(const Tizen::Base::String& algorithm) +{ + result r = E_SUCCESS; + + SysAssertf(__pRandom == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __algorithm = algorithm; + + if (!__algorithm.CompareTo(L"AES")) + { + __pRandom = new (std::nothrow) AesSecureRandom(); + __keyGenSize = _MAX_AES_KEY_GEN_SIZE; + } + else if (!__algorithm.CompareTo(L"DES")) + { + __pRandom = new (std::nothrow) DesSecureRandom(); + __keyGenSize = _MAX_DES_KEY_GEN_SIZE; + } + else if (!__algorithm.CompareTo(L"3DES")) + { + __pRandom = new (std::nothrow) DesEdeSecureRandom(); + __keyGenSize = _MAX_DES_EDE_KEY_GEN_SIZE; + } + else + { + return E_INVALID_ARG; + } + + SysTryReturn(NID_SEC, __pRandom != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + return r; +} + +result +SecretKeyGenerator::Construct(int keySize) +{ + result r = E_SUCCESS; + + SysAssertf(__pRandom == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + SysTryReturn(NID_SEC, keySize >= _DEFAULT_KEY_SIZE, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input key size should not be smaller then default key size(32)."); + + __pRandom = new (std::nothrow) AesSecureRandom(); + SysTryReturn(NID_SEC, __pRandom != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + __keyGenSize = keySize; + + return r; + +} + +ISecretKey* +SecretKeyGenerator::GenerateKeyN(void) +{ + result r = E_SUCCESS; + + ClearLastResult(); + + std::unique_ptr pSecKey(new (std::nothrow) SecretKey()); + SysTryReturn(NID_SEC, pSecKey != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + if (__pRandom != null) + { + std::unique_ptr pRandomBytes(__pRandom->GenerateRandomBytesN(__keyGenSize)); + SysTryReturn(NID_SEC, pRandomBytes, null, GetLastResult(), "[%s] Failed to generate random bytes.", GetErrorMessage(GetLastResult())); + + r = pSecKey->SetKey(*pRandomBytes.get()); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + } + else + { + r = pSecKey->SetKey(__keyBytes); + SysTryReturn(NID_SEC, !IsFailed(r), null, r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + } + + return pSecKey.release(); +} + +} } //Tizen::Security diff --git a/src/security/FSec_AccessController.cpp b/src/security/FSec_AccessController.cpp new file mode 100644 index 0000000..cd41a20 --- /dev/null +++ b/src/security/FSec_AccessController.cpp @@ -0,0 +1,272 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_AccessController.cpp + * @brief This is the implementation for the _AccessController class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSec_AccessController.h" +#include "FSec_PrivilegeManager.h" +#include "FSec_PrivilegeManagerMessage.h" +#include "FSec_PrivilegeInfo.h" + +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +static _IpcClient ipcClient; +static bool isConstructed = false; + +namespace Tizen { namespace Security +{ + +_PrivilegeManager* _AccessController::__pPrivilegeManager = null; + +_AccessController::_AccessController(void) +{ + +} + +_AccessController::~_AccessController(void) +{ + +} + +result +_AccessController::CheckSystemPrivilege(const AppId& appId, _Privilege privilege) +{ + result r = E_SUCCESS; + + bool ret = false; + std::unique_ptr<_PrivilegeInfo> pPrivilegeInfo(null); + String subAppId; + _PackageInfoImpl infoImpl; + String appType; + String webAppType(L"wgt"); + + SysLog(NID_SEC, "Enter."); + SysTryReturnResult(NID_SEC, privilege < _MAX_PRIVILEGE_ENUM, E_INVALID_ARG, "The privilege enumerator is invalid"); + + appId.SubString(0, MAX_APP_ID_SIZE, subAppId); + + r = infoImpl.Construct(subAppId); + if (r == E_APP_NOT_INSTALLED) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The package information does not exist."); + r = E_DATA_NOT_FOUND; + goto CATCH; + } + + appType = infoImpl.GetAppType(); + r = GetLastResult(); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + if (appType.Equals(webAppType, true)) + { + return E_SUCCESS; + } + + if (__pPrivilegeManager == null) + { + __pPrivilegeManager = _PrivilegeManager::GetInstance(); + } + SysTryReturnResult(NID_SEC, __pPrivilegeManager != null, E_SYSTEM, "An unexpected system error occurred."); + + pPrivilegeInfo.reset(__pPrivilegeManager->RetrievePrivilegeInfoN(subAppId)); + r = GetLastResult(); + + if (r == E_SUCCESS) + { + // nothing to do. + } + else if (r == E_DATA_NOT_FOUND) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + goto CATCH; + } + else + { + SysLogException(NID_SEC, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + return E_SYSTEM; + } + + ret = pPrivilegeInfo->HasPrivilege(privilege); + if (!ret) + { + r = E_PRIVILEGE_DENIED; + goto CATCH; + } + + SysLog(NID_SEC, "Exit."); + return r; + +CATCH: + + SysLogException(NID_SEC, r, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + SysLog(NID_SEC, "Exit."); + + _AppManagerImpl* pAppManagerImpl = _AppManagerImpl::GetInstance(); + pAppManagerImpl->TerminateApplications(appId); + + return r; +} + +static std::unique_ptr pEncryptedPrivileges(null); +static std::unique_ptr pChecksum(null); +static std::unique_ptr pEncryptedVisibility(null); +static std::unique_ptr pVisibilityChecksum(null); + +void +_AccessController::Initialize(void) +{ + result r = E_SUCCESS; + result ipcResult = E_SUCCESS; + + std::unique_ptr pCipherPrivilegeMessage(null); + std::unique_ptr pCipherVisibilityMessage(null); + + SysLog(NID_SEC, "Enter"); + + r = ipcClient.Construct(L"osp.security.ipcserver.privilegemanager", null); + SysTryReturnVoidResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "Failed to construct the instance of IPC."); + + pEncryptedPrivileges.reset(new (std::nothrow) String()); + SysTryReturnVoidResult(NID_SEC, pEncryptedPrivileges != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pChecksum.reset(new (std::nothrow) String()); + SysTryReturnVoidResult(NID_SEC, pChecksum != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pCipherPrivilegeMessage.reset(new (std::nothrow) PrivilegeManagerMsg_retrieve(pEncryptedPrivileges.get(), pChecksum.get(), &r)); + SysTryReturnVoidResult(NID_SEC, pCipherPrivilegeMessage != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + ipcResult = ipcClient.SendRequest(pCipherPrivilegeMessage.get()); + SysTryReturnVoidResult(NID_SEC, ipcResult == E_SUCCESS, E_SYSTEM, "Failed to send IPC message."); + SysTryReturnVoidResult(NID_SEC, r == E_SUCCESS, r, "Failed to retrieve privilege information"); + + pEncryptedVisibility.reset(new (std::nothrow) String()); + SysTryReturnVoidResult(NID_SEC, pEncryptedVisibility != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pVisibilityChecksum.reset(new (std::nothrow) String()); + SysTryReturnVoidResult(NID_SEC, pVisibilityChecksum != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + pCipherVisibilityMessage.reset(new (std::nothrow) PrivilegeManagerMsg_retrieveEx(pEncryptedVisibility.get(), pVisibilityChecksum.get(), &r)); + SysTryReturnVoidResult(NID_SEC, pCipherVisibilityMessage != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + ipcResult = ipcClient.SendRequest(pCipherVisibilityMessage.get()); + SysTryReturnVoidResult(NID_SEC, ipcResult == E_SUCCESS, E_SYSTEM, "Failed to send IPC message."); + SysTryReturnVoidResult(NID_SEC, r == E_SUCCESS, r, "Failed to retrieve privilege information"); + + isConstructed = true; + + SysLog(NID_SEC, "Exit"); + return; +} + +result +_AccessController::CheckUserPrivilege(_Privilege privilege) +{ + result r = E_SUCCESS; + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + bool ret = false; + + _AppType appType = _APP_TYPE_UI_APP; + _PrivilegeInfo privilegeInfo; + + SysLog(NID_SEC, "Enter."); + ClearLastResult(); + + SysTryReturnResult(NID_SEC, privilege < _MAX_PRIVILEGE_ENUM, E_INVALID_ARG, "The privilege enumerator is invalid"); + //SysAssertf(privilegeLevelListTable[privilege][_PRV_API_VER_2_0] == _PRV_LEVEL_USER, "System-level privilege is passed to CheckUserPrivilege."); + + appType = _AppInfo::GetAppType(); + const PackageId& packageId = _AppInfo::GetPackageId(); + + if ((appType & _APP_TYPE_WEB_APP) != _APP_TYPE_WEB_APP) + { + if (isConstructed != true) + { + pthread_once(&onceBlock, Initialize); + r = GetLastResult(); + if (IsFailed(r)) + { + if (r == E_DATA_NOT_FOUND) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + goto CATCH; + } + else + { + onceBlock = PTHREAD_ONCE_INIT; + SysLogException(NID_SEC, r, "[%s] Propagated.", GetErrorMessage(r)); + } + return r; + } + } + + if ((pEncryptedPrivileges != null) && (pChecksum != null) && (pEncryptedVisibility != null) && (pVisibilityChecksum != null)) + { + r = privilegeInfo.Construct(packageId, *(pEncryptedPrivileges.get()), *(pChecksum.get()), *(pEncryptedVisibility.get()), *(pVisibilityChecksum.get())); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred. %ls", packageId.GetPointer()); + + SysLog(NID_SEC, "%ls is in the cache [client]", privilegeInfo.GetAppId().GetPointer()); + } + else + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + r = E_DATA_NOT_FOUND; + goto CATCH; + } + + ret = privilegeInfo.HasPrivilege(privilege); + if (!ret) + { + r = E_PRIVILEGE_DENIED; + goto CATCH; + } + } + + SysLog(NID_SEC, "Exit."); + return r; + +CATCH: + + SysLogException(NID_SEC, r, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + SysLog(NID_SEC, "Exit."); + + _AppManagerImpl* pAppManagerImpl = _AppManagerImpl::GetInstance(); + pAppManagerImpl->TerminateApplications(packageId); + + return r; + +} + +}} //Tizen::Security diff --git a/src/security/FSec_DeviceKeyGenerator.cpp b/src/security/FSec_DeviceKeyGenerator.cpp new file mode 100644 index 0000000..ff218cc --- /dev/null +++ b/src/security/FSec_DeviceKeyGenerator.cpp @@ -0,0 +1,220 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_DeviceKeyGenerator.cpp + * @brief This file contains the implementation of DeviceKeyGenerator class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Security::Crypto; + + +namespace Tizen { namespace Security +{ + +static const int _HASH_LEN = 20; + +_DeviceKeyGenerator::_DeviceKeyGenerator(void) +{ + +} + +_DeviceKeyGenerator::~_DeviceKeyGenerator(void) +{ + +} + +ISecretKey* +_DeviceKeyGenerator::GenerateDeviceKeyN(int keySize) +{ + result r = E_SUCCESS; + String deviceInfo; + ByteBuffer deviceInfoBuffer; + std::unique_ptr pHashValue(null); + std::unique_ptr pKey(null); + ByteBuffer* pTempValue = null; + ByteBuffer* pTempInfoBuffer = null; + Sha1Hash hash; + int count = 0; + char* pDeviceInfo = null; + + SysLog(NID_SEC, "GenerateDeviceKeyN called."); + + SysTryReturn(NID_SEC, keySize > 0, null, E_INVALID_ARG, + "[E_INVALID_ARG] The device key size MUST be a valid integer greater than 0."); + deviceInfo.Append(L"1234567890abcdefghijklmnopqrstuvwxyz"); + if (keySize % _HASH_LEN == 0) + { + count = keySize / _HASH_LEN; + } + else + { + count = keySize / _HASH_LEN + 1; + } + + pHashValue.reset(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC, pHashValue != null, null, r = E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + r = pHashValue->Construct(count * _HASH_LEN); + SysTryReturn(NID_SEC, r == E_SUCCESS, null, r = E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pDeviceInfo = _StringConverter::CopyToCharArrayN(deviceInfo); + deviceInfoBuffer.Construct(deviceInfo.GetLength()); + deviceInfoBuffer.SetArray(reinterpret_cast (pDeviceInfo), 0, deviceInfo.GetLength()); + deviceInfoBuffer.Flip(); + delete[] pDeviceInfo; + + for (int i = 0; i < count; i++) + { + if (i == 0) + { + pTempValue = hash.GetHashN(deviceInfoBuffer); + } + else + { + pTempValue = hash.GetHashN(*pTempInfoBuffer); + } + SysTryCatch(NID_SEC, pTempValue != null, , GetLastResult(), "[%s] Failed to generate hash code.", + GetErrorMessage(GetLastResult())); + + if (pTempInfoBuffer != null) + delete pTempInfoBuffer; + pTempInfoBuffer = new (std::nothrow) ByteBuffer(); + r = pTempInfoBuffer->Construct(*pTempValue); + delete pTempValue; + SysTryCatch(NID_SEC, r == E_SUCCESS, , r, "[%s] A system error has occurred.", GetErrorMessage(r)); + r = pHashValue->CopyFrom(*pTempInfoBuffer); + SysTryCatch(NID_SEC, r == E_SUCCESS, , r, "[%s] A system error has occurred.", GetErrorMessage(r)); + } + + pHashValue->Flip(); + pHashValue->SetLimit(keySize); + pKey.reset(new (std::nothrow) SecretKey()); + SysTryCatch(NID_SEC, pKey != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + r = pKey->SetKey(*(pHashValue.get())); + SysTryCatch(NID_SEC, r == E_SUCCESS, , r, "[%s] Failed to generate device unique key.", GetErrorMessage(r)); + +CATCH: + SetLastResult(r); + delete pTempInfoBuffer; + + return pKey.release(); +} + +ISecretKey* +_DeviceKeyGenerator::GenerateDeviceKeyN(String& appId, int keySize) +{ + result r = E_SUCCESS; + String deviceInfo; + ByteBuffer deviceInfoBuffer; + std::unique_ptr pHashValue(null); + std::unique_ptr pHmacKey(null); + std::unique_ptr pSecretKey(null); + std::unique_ptr pKey(null); + ByteBuffer* pTempValue = null; + ByteBuffer* pTempInfoBuffer = null; + Sha1Hmac hmac; + int count = 0; + char* pDeviceInfo = null; + + SysLog(NID_SEC, "GenerateDeviceKeyN called."); + + SysTryReturn(NID_SEC, keySize > 0 && appId.GetLength() > 0, null, E_INVALID_ARG, + "[E_INVALID_ARG] The device key size MUST be a valid integer greater than 0."); + +//ToDo +//Add slp API + + deviceInfo.Append(L"1234567890abcdefghijklmnopqrstuvwxyz"); + if (keySize % _HASH_LEN == 0) + { + count = keySize / _HASH_LEN; + } + else + { + count = keySize / _HASH_LEN + 1; + } + + pHashValue.reset(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC, pHashValue != null, null, r = E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + r = pHashValue->Construct(count * _HASH_LEN); + SysTryCatch(NID_SEC, r == E_SUCCESS, , r, "[%s] A system error has occurred.", GetErrorMessage(r)); + + pDeviceInfo = _StringConverter::CopyToCharArrayN(deviceInfo); + deviceInfoBuffer.Construct(deviceInfo.GetLength()); + deviceInfoBuffer.SetArray(reinterpret_cast (pDeviceInfo), 0, deviceInfo.GetLength()); + deviceInfoBuffer.Flip(); + delete[] pDeviceInfo; + + pHmacKey.reset(StringUtil::StringToUtf8N(appId)); + + pSecretKey.reset(new (std::nothrow) SecretKey()); + r = pSecretKey->SetKey(*(pHmacKey.get())); + SysTryCatch(NID_SEC, r == E_SUCCESS, , r, "[%s] A system error has occurred.", GetErrorMessage(r)); + hmac.SetKey(*(pSecretKey.get())); + + for (int i = 0; i < count; i++) + { + if (i == 0) + { + pTempValue = hmac.GetHmacN(deviceInfoBuffer); + } + else + { + pTempValue = hmac.GetHmacN(*pTempInfoBuffer); + } + SysTryCatch(NID_SEC, pTempValue != null, , GetLastResult(), "[%s] Failed to generate hash code.", + GetErrorMessage(GetLastResult())); + + if (pTempInfoBuffer != null) + delete pTempInfoBuffer; + pTempInfoBuffer = new (std::nothrow) ByteBuffer(); + r = pTempInfoBuffer->Construct(*pTempValue); + delete pTempValue; + SysTryCatch(NID_SEC, r == E_SUCCESS, , r, "[%s] A system error has occurred.", GetErrorMessage(r)); + r = pHashValue->CopyFrom(*pTempInfoBuffer); + SysTryCatch(NID_SEC, r == E_SUCCESS, , r, "[%s] A system error has occurred.", GetErrorMessage(r)); + } + + pHashValue->Flip(); + pHashValue->SetLimit(keySize); + pKey.reset(new (std::nothrow) SecretKey()); + SysTryCatch(NID_SEC, pKey != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + r = pKey->SetKey(*(pHashValue.get())); + SysTryCatch(NID_SEC, r == E_SUCCESS, , r, "[%s] Failed to generate device unique key.", GetErrorMessage(r)); + +CATCH: + SetLastResult(r); + delete pTempInfoBuffer; + + return pKey.release(); +} + +} //Tizen::Security +} //Osp diff --git a/src/security/FSec_GenerateParameters.cpp b/src/security/FSec_GenerateParameters.cpp new file mode 100644 index 0000000..771602d --- /dev/null +++ b/src/security/FSec_GenerateParameters.cpp @@ -0,0 +1,385 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_GenerateParameters.cpp + * @brief This file contains implementation of Generating Key Exchange Parameters p and g using ANSFS X9.31 Standard. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSec_GenerateParameters.h" +#include "FSec_Prng.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security +{ + +static const int _MAX_FACTOR_PRIVATE_KEY = 4; +static const int _BITS_IN_BYTE = 8; +static const int _SHA_DIGEST_LENGTH = 32; +static const int _MAX_SHA_DIGEST_LENGTH = 64; +static const int _MAX_NUMBER_OF_CHECKS = 64; +static const int _PRIVATE_KEY_LENGTH_PAIR_1 = 160; +static const int _PRIVATE_KEY_LENGTH_PAIR_2 = 224; +static const int _PRIVATE_KEY_LENGTH_PAIR_3 = 256; +static const int _PUBLIC_KEY_LENGTH_PAIR_1 = 1024; +static const int _PUBLIC_KEY_LENGTH_PAIR_2 = 2048; +static const int _PUBLIC_KEY_LENGTH_PAIR_3 = 3072; + +result +_GenerateParameters::GenerateParametersX186(void* pDh, long primeNumberLength, long generatorLength, long seedLengthInBytes) +{ + result r = E_SUCCESS; + int ret = 0; + long tempVal = 0; + unsigned long count = 0; + unsigned long counter = 0; + unsigned long offset = 0; + unsigned long seedLengthInBits = 0; + unsigned long hashSize = SHA_DIGEST_LENGTH; + unsigned long outlen = 0; + unsigned long index = 0; + unsigned long power = 0; + byte val1[_MAX_SHA_DIGEST_LENGTH] = {0, }; + std::unique_ptr pSeedBuffer; + const EVP_CIPHER* pAlgorithm = null; + BN_CTX* pCtx = null; + BIGNUM* pBn = null; + BIGNUM* pBnTemp = null; + BIGNUM* pValueBn = null; + BIGNUM* pSeedBn = null; + BIGNUM* pU = null; + BIGNUM* pTwoPower = null; + BIGNUM* pV = null; + BIGNUM* pTemp = null; + BIGNUM* pjBn = null; + BIGNUM* pBnTemp1 = null; + BIGNUM* pW = null; + BIGNUM* pX = null; + byte* (*shaSelected)(const byte* pData, size_t dataLen, byte* pOutBuf) = SHA1; + + pCtx = BN_CTX_new(); + SysTryReturn(NID_SEC, pCtx != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + BN_CTX_init(pCtx); + + //STEP 1. Check that the (primeNumberLength, generatorLength) pair is in the list of acceptable (primeNumberLength, generatorLength pairs) (see Section 4.2). If + //the pair is not in the list, then return INVALID. + if (!(((primeNumberLength == _PUBLIC_KEY_LENGTH_PAIR_1) && (generatorLength == _PRIVATE_KEY_LENGTH_PAIR_1)) || ((primeNumberLength == _PUBLIC_KEY_LENGTH_PAIR_2) && (generatorLength == _PRIVATE_KEY_LENGTH_PAIR_2)) || ((primeNumberLength == _PUBLIC_KEY_LENGTH_PAIR_2) && (generatorLength == _PRIVATE_KEY_LENGTH_PAIR_3)) || ((primeNumberLength == _PUBLIC_KEY_LENGTH_PAIR_3) && (generatorLength == _PRIVATE_KEY_LENGTH_PAIR_3)))) + { + BN_CTX_free(pCtx); + return E_INVALID_ARG; + } + + //STEP 2. If (seedlen < generatorLength), then return INVALID. + tempVal = generatorLength / _BITS_IN_BYTE; + SysTryCatch(NID_SEC, pDh != null && seedLengthInBytes >= tempVal, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Input data should be valid."); + + if (generatorLength > _PRIVATE_KEY_LENGTH_PAIR_1) + { + shaSelected = SHA256; + hashSize = _SHA_DIGEST_LENGTH; + + } + + outlen = hashSize * _BITS_IN_BYTE; + + //STEP 3. index = primeNumberLength / outlen ?1. + index = (primeNumberLength / outlen) - 1; + if (primeNumberLength % outlen) + { + index++; + } + + //STEP 4. power = primeNumberLength ?1 ?(index * outlen). + power = primeNumberLength - 1 - (index * outlen); + + pBn = BN_new(); + SysTryCatch(NID_SEC, pBn != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pBnTemp = BN_new(); + SysTryCatch(NID_SEC, pBnTemp != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pSeedBuffer = std::unique_ptr (new (std::nothrow) byte[seedLengthInBytes]); + SysTryCatch(NID_SEC, pSeedBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + BN_CTX_start(pCtx); + + pValueBn = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pValueBn != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pSeedBn = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pSeedBn != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pU = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pU != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pTwoPower = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pTwoPower != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pTemp = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pTemp != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + do + { + //STEP 5. Get an arbitrary sequence of seedlen bits as the domain_parameter_seed. + //if (GetRandomBytes(SEC_BCIPHER_AES_ECB_128 , seedBuffer, seedLengthInBytes) == FALSE) + + pAlgorithm = EVP_aes_128_ecb(); + + std::unique_ptr pBuffer (_Prng::GetRandomBytesN(pAlgorithm, seedLengthInBytes)); + SysTryCatch(NID_SEC, pBuffer != null, , GetLastResult(), "[%s] Allocating new ByteBuffer failed.", GetErrorMessage(GetLastResult())); + + memcpy(pSeedBuffer.get(), pBuffer->GetPointer(), pBuffer->GetRemaining()); + + BN_bin2bn(pSeedBuffer.get(), seedLengthInBytes, pSeedBn); + SysTryCatch(NID_SEC, pSeedBn != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //STEP 5. Set U = 0 + ret = BN_zero(pU); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //STEP 6. U = Hash (domain_parameter_seed) mod 2^generatorLength?. + + //Hash (domain_parameter_seed) + shaSelected(pSeedBuffer.get(), seedLengthInBytes, val1); + + BN_bin2bn(val1, hashSize, pTemp); + SysTryCatch(NID_SEC, pTemp != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //2^generatorLength?. + ret = BN_lshift(pTwoPower, BN_value_one(), generatorLength - 1); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //U = Hash mod 2^generatorLength?. + ret = BN_mod(pU, pTemp, pTwoPower, pCtx); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //generate q + //STEP 7. q = 2^generatorLength? + U + 1 ?( U mod 2). + //( U mod 2). + if (BN_is_bit_set(pU, 0)) + { + //q = 2^generatorLength? + U + 1 - 1 + ret = BN_add(pBnTemp, pTwoPower, pU); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + else + { + //q = 2^generatorLength? + U + 1 + ret = BN_add(pTemp, pU, BN_value_one()); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = BN_add(pBnTemp, pTwoPower, pTemp); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + + //STEP 8.Test whether or not q is prime as specified in Appendix C.3. + //STEP 9. If q is not prime then go to 4 + } + while (BN_is_prime_fasttest_ex(pBnTemp, _MAX_NUMBER_OF_CHECKS, pCtx, 1, null) <= 0); + + //generate p + //STEP 10: offset = 1 + offset = 1; + pW = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pW != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pV = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pV != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pX = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pX != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + seedLengthInBits = BN_num_bits(pSeedBn); + + //STEP 11. For counter = 0 to (4L ?1) do + for (counter = 0; counter < ((_MAX_FACTOR_PRIVATE_KEY * primeNumberLength) - 1); counter++) + { + ret = BN_zero(pW); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //STEP 11.1 For count = 0 to index do + //Vj = Hash ((domain_parameter_seed + offset + count) mod 2^seedlen)). + for (count = 0; count <= index; count++) + { + ret = BN_set_word(pValueBn, offset + count); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = BN_add(pTemp, pSeedBn, pValueBn); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //2^seedLen. + ret = BN_lshift(pTwoPower, BN_value_one(), seedLengthInBits); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //U = Hash mod 2^seedLen. + ret = BN_mod(pValueBn, pTemp, pTwoPower, pCtx); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = BN_bn2bin(pValueBn, pSeedBuffer.get()); + SysTryCatch(NID_SEC, pSeedBuffer != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + shaSelected(pSeedBuffer.get(), seedLengthInBytes, val1); + + BN_bin2bn(val1, hashSize, pV); + SysTryCatch(NID_SEC, pV != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + if (count == index) + { + //2^power. + ret = BN_lshift(pTwoPower, BN_value_one(), power); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //Vn mod 2^power + ret = BN_mod(pTemp, pV, pTwoPower, pCtx); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + BN_copy(pV, pTemp); + SysTryCatch(NID_SEC, pTemp != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + + //STEP 11.2 W = V0 + (V1 * 2^outlen) + ?+ (Vn? * 2^(index?) * outlen) + ((Vn mod 2b) * 2^(index * outlen)). + //BN_lshift(pTwoPower, BN_value_one(), (count * outlen)); + //BN_mul(pTemp, pV, pTwoPower); + + ret = BN_lshift(pTemp, pV, (count * outlen)); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = BN_add(pW, pW, pTemp); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + + //11.3 X = W + 2^primeNumberLength?. Comment: 0 = W < 2L?; hence, 2L? = X < 2L. + //=> 2^(primeNumberLength-1) + ret = BN_lshift(pTwoPower, BN_value_one(), (primeNumberLength - 1)); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //X = W + 2^(primeNumberLength-1) + ret = BN_add(pX, pW, pTwoPower); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //STEP 11.4 c = X mod 2q. + //(2*q) + ret = BN_lshift(pTemp, pBnTemp, 1); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //(X mod (2*q)) + ret = BN_mod(pValueBn, pX, pTemp, pCtx); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //(c - 1) + ret = BN_sub(pTemp, pValueBn, BN_value_one()); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //STEP 11.5 p = X ?(c ?1). Comment: p = 1 (mod 2q). + ret = BN_sub(pBn, pX, pTemp); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + if ((BN_num_bits(pBn) > (primeNumberLength - 1)) && BN_is_prime_fasttest_ex(pBn, _MAX_NUMBER_OF_CHECKS, pCtx, 1, null) > 0) + { + break; + } + + offset += index + 1; + } + + tempVal = (_MAX_FACTOR_PRIVATE_KEY * primeNumberLength) - 1; + SysTryCatch(NID_SEC, counter < static_cast< unsigned long >(tempVal), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed in evaluating proper values."); + + //generate g + pjBn = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC, pjBn != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + //STEP 1. Let count = (p - 1)/q. + ret = BN_sub(pTemp, pBn, BN_value_one()); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = BN_div(pjBn, null, pTemp, pBnTemp, pCtx); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pBnTemp1 = BN_new(); + SysTryCatch(NID_SEC, pBnTemp1 != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + seedLengthInBytes = (BN_num_bits(pBn) - 1) / _BITS_IN_BYTE; + + pSeedBuffer = std::unique_ptr (new (std::nothrow) byte[seedLengthInBytes]); + SysTryCatch(NID_SEC, pSeedBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + do + { + //STEP 2. Set h = any integer, where 1 < h < p - 1 and h differs + //from any value previously tried. + //if (GetRandomBytes(SEC_BCIPHER_AES_ECB_128 , seedBuffer, seedLengthInBytes) == FALSE) // -1 to ensure h is smaller then p + + pAlgorithm = EVP_aes_128_ecb(); + + std::unique_ptr pBuffer (_Prng::GetRandomBytesN(pAlgorithm, seedLengthInBytes)); + SysTryCatch(NID_SEC, pBuffer != null, , GetLastResult(), "[%s] Allocating new ByteBuffer failed.", GetErrorMessage(GetLastResult())); + + memcpy(pSeedBuffer.get(), pBuffer->GetPointer(), pBuffer->GetRemaining()); + + BN_bin2bn(pSeedBuffer.get(), seedLengthInBytes, pSeedBn); //pSeedBn <=> h + SysTryCatch(NID_SEC, pSeedBn != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //3. Set g = h^count mod p + ret = BN_mod_exp(pBnTemp1, pSeedBn, pjBn, pBn, pCtx); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //4. If g == 1 go to step 2 + } + while (BN_is_one(pBnTemp1)); + + (static_cast< DH* >(pDh))->g = pBnTemp1; + (static_cast< DH* >(pDh))->p = pBn; + (static_cast< DH* >(pDh))->length = BN_num_bytes(pBnTemp); + +CATCH: + if (IsFailed(r) && pBnTemp1 != null) + { + BN_free(pBnTemp1); + } + + if (IsFailed(r) && pBn != null) + { + BN_free(pBn); + } + + if (pBnTemp != null) + { + BN_free(pBnTemp); + } + + if (pCtx != null) + { + BN_CTX_end(pCtx); + BN_CTX_free(pCtx); + } + + return r; +} + +} } // Tizen::Security diff --git a/src/security/FSec_GenerateParameters.h b/src/security/FSec_GenerateParameters.h new file mode 100644 index 0000000..1c18484 --- /dev/null +++ b/src/security/FSec_GenerateParameters.h @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_GenerateParameters.h + * @brief This file contains implementation of Generating Key Exchange Parameters p and g using ANSFS X9.31 Standard. + */ +#ifndef _FSEC_INTERNAL_GENERATE_PARAMETERS_H_ +#define _FSEC_INTERNAL_GENERATE_PARAMETERS_H_ + + +namespace Tizen { namespace Security +{ + +/** + * @class _GenerateParameters + * @brief This class generates a pseudo random number as per X9.31 specification using algorithm passed as input. + * @since 2.1 + * + * This file contains implementation of Generating Key Exchange Parameters p and g using ANSFS X9.31 Standard. + * + */ +class _GenerateParameters +{ + +public: + /** + * Generate key Exchange Parameters as per X9.31 specification using algorithm passed as input. + * + * @since 2.1 + * @return Returns 0 in case of error otherwise success. + * @param[out] pDh Pointer to output DH structure which includes the generated parameters p and g. + * @param[in] primeNumberLength Length of the prime that is to be generated. + * @param[in] generatorLength Length of the generator that is to be generated. + * @param[in] seedLengthInBytes Length of the seed that is required to Generate Key Exchange Parameters p and g. + * + */ + static result GenerateParametersX186(void* pDh, long primeNumberLength, long generatorLength, long seedLengthInBytes); + +private: + _GenerateParameters(void); + _GenerateParameters(const _GenerateParameters& rhs); + _GenerateParameters& operator =(const _GenerateParameters& rhs); + ~_GenerateParameters(void); + +}; //_GenerateParameters + +} } // Tizen::Security + +#endif //_FSEC_INTERNAL_GENERATE_PARAMETERS_H_ diff --git a/src/security/FSec_PrivilegeCache.cpp b/src/security/FSec_PrivilegeCache.cpp new file mode 100644 index 0000000..b760451 --- /dev/null +++ b/src/security/FSec_PrivilegeCache.cpp @@ -0,0 +1,204 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecurity_PrivilegeCache.cpp + * @brief This is the implementation for the Privilege Manager class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FSec_AccessControlTypes.h" +#include "FSec_PrivilegeCache.h" +#include "FSec_PrivilegeInfo.h" + +using namespace Tizen::App; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Security +{ + +std::unique_ptr _PrivilegeCache::__pMutex(null); + +_PrivilegeCache::_PrivilegeCache(void) + : __pPrivilegeList(null) +{ + +} + +_PrivilegeCache::~_PrivilegeCache(void) +{ + __pPrivilegeList->RemoveAll(true); +} + +result +_PrivilegeCache::Construct(void) +{ + result r = E_SUCCESS; + + SysLog(NID_SEC, "Enter."); + + std::unique_ptr pPrivilegeList(new (std::nothrow) HashMap()); + SysTryReturnResult(NID_SEC, pPrivilegeList != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + + r = pPrivilegeList->Construct(32, 0.75); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + std::unique_ptr pMutex(new (std::nothrow) Mutex()); + SysTryReturnResult(NID_SEC, pMutex != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + + r = pMutex->Create(); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + __pPrivilegeList = std::move(pPrivilegeList); + __pMutex = std::move(pMutex); + + SysLog(NID_SEC, "Exit."); + return r; +} + +result +_PrivilegeCache::AddPrivilegeInfo(const _PrivilegeInfo& privilegeInfo) +{ + result r = E_SUCCESS; + result mutexResult = E_SUCCESS; + + std::unique_ptr<_PrivilegeInfo> pPrivilegeInfo(null); + std::unique_ptr pKey(null); + + SysLog(NID_SEC, "Enter."); + + SysTryReturnResult(NID_SEC, privilegeInfo.GetAppId().GetLength() == MAX_APP_ID_SIZE, E_INVALID_ARG, "The argument is invalid."); + + pPrivilegeInfo.reset(privilegeInfo.CloneN()); + SysTryReturnResult(NID_SEC, pPrivilegeInfo != null, E_SYSTEM, "An unexpected system error occurred."); + + pKey.reset(new String(pPrivilegeInfo->GetAppId())); + SysTryReturnResult(NID_SEC, pKey != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + + mutexResult = __pMutex->Acquire(); + SysTryCatch(NID_SEC, mutexResult == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = __pPrivilegeList->Add(*(pKey.release()), *(pPrivilegeInfo.release())); + SysTryCatchLabel(NID_SEC, r == E_SUCCESS, r = E_SYSTEM, CATCH2, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + mutexResult = __pMutex->Release(); + SysTryCatch(NID_SEC, mutexResult == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + SysLog(NID_SEC, "Exit."); + return r; + +CATCH2: + + mutexResult = __pMutex->Release(); + SysTryCatch(NID_SEC, mutexResult == E_SUCCESS, mutexResult = E_SYSTEM, E_SYSTEM, "An unexpected system error occurred."); + + + SysLog(NID_SEC, "Exit."); + return r; + +CATCH: + + SysLog(NID_SEC, "Exit."); + return r; +} + +result +_PrivilegeCache::RemovePrivilegeInfo(const AppId& appId) +{ + result r = E_SUCCESS; + result mutextResult = E_SUCCESS; + + SysLog(NID_SEC, "Enter."); + + mutextResult = __pMutex->Acquire(); + SysTryReturnResult(NID_SEC, mutextResult == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = __pPrivilegeList->Remove(appId, true); + if ((r == E_SUCCESS) || (r == E_OBJ_NOT_FOUND)) + { + r = E_SUCCESS; + SetLastResult(r); + } + else + { + r = E_SYSTEM; + SysLogException(NID_SEC, r, "[E_SYSTEM] An unexpected system error occurred."); + } + + mutextResult = __pMutex->Release(); + SysTryReturnResult(NID_SEC, mutextResult == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + SysLog(NID_SEC, "Exit."); + return r; +} + +_PrivilegeInfo* +_PrivilegeCache::GetPrivilegeInfoN(const AppId& appId) const +{ + result r = E_SUCCESS; + result mutexResult = E_SUCCESS; + + std::unique_ptr<_PrivilegeInfo> pPrivilegeInfo(null); + + SysLog(NID_SEC, "Enter."); + ClearLastResult(); + + mutexResult = __pMutex->Acquire(); + SysTryReturn(NID_SEC, mutexResult == E_SUCCESS, null, E_SYSTEM, "An unexpected system error occurred."); + + _PrivilegeInfo* pTempInfo = static_cast< _PrivilegeInfo* >(__pPrivilegeList->GetValue(appId)); + r = GetLastResult(); + + mutexResult = __pMutex->Release(); + SysTryReturn(NID_SEC, mutexResult == E_SUCCESS, null, E_SYSTEM, "An unexpected system error occurred."); + + if (r == E_SUCCESS) + { + pPrivilegeInfo.reset(new (std::nothrow) _PrivilegeInfo()); + SysTryReturn(NID_SEC, pPrivilegeInfo != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation is failed."); + + r = pPrivilegeInfo->Construct(*pTempInfo); + SysTryReturn(NID_SEC, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + SysLog(NID_SEC, "%ls is in the cacheList [server]", pPrivilegeInfo->GetAppId().GetPointer()); + } + else if (r == E_OBJ_NOT_FOUND) + { + SetLastResult(E_DATA_NOT_FOUND); + } + else + { + SysLogException(NID_SEC, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + + SysLog(NID_SEC, "Exit."); + return pPrivilegeInfo.release(); +} + +}} //Tizen::Security diff --git a/src/security/FSec_PrivilegeCache.h b/src/security/FSec_PrivilegeCache.h new file mode 100644 index 0000000..740c33d --- /dev/null +++ b/src/security/FSec_PrivilegeCache.h @@ -0,0 +1,109 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecurity_PrivilegeCache.h + * @brief This is the header file for the _PrivilegeCache. + * + * This header file contains the declarations of the _PrivilegeCache. + */ + +#ifndef _FSEC_INTERNAL_PRIVILEGE_CACHE_H_ +#define _FSEC_INTERNAL_PRIVILEGE_CACHE_H_ + +#include +#include +#include "FSec_AccessControlTypes.h" + +namespace Tizen { namespace Base { namespace Runtime +{ +class Mutex; +}}} + +namespace Tizen { namespace Security +{ + +class _PrivilegeInfo; + +/** + * @class _PrivilegeCache + * @brief This class provides a way to access the privilege cache. + * @since 2.0 + * + * This class provides a way to access the privilege cache. + * + */ +class _PrivilegeCache + : public Tizen::Base::Object +{ + +public: + + _PrivilegeCache(void); + virtual ~_PrivilegeCache(void); + + result Construct(void); + + /** + * Adds the specified privilege information to the privilege cache. + * + * @since 2.0 + * @return An error code + * @param[in] privilegeInfo An instance of _PrivilegeInfo. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error occurred. + */ + result AddPrivilegeInfo(const _PrivilegeInfo& privilegeInfo); + + /** + * Removes the specified information in the privilege cache. + * + * @since 2.0 + * @return An error code + * @param[in] appId The application ID. + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM An unexpected system error occurred. + */ + result RemovePrivilegeInfo(const Tizen::App::AppId& appId); + + /** + * Gets the privilege information of the specified application. + * + * @since 2.0 + * @return A _PrivilegeInfo instance + * @param[in] appId The application ID. + * @param[out] privilegeInfo An instance of _PrivilegeInfo. + * @exception E_SUCCESS The method is successful. + * @exception E_DATA_NOT_FOUND The privilege information does not exist. + * @exception E_SYSTEM An unexpected system error occurred. + */ + _PrivilegeInfo* GetPrivilegeInfoN(const Tizen::App::AppId& appId) const; +private: + + _PrivilegeCache(const _PrivilegeCache& rhs); + _PrivilegeCache& operator =(const _PrivilegeCache& rhs); + +private: + std::unique_ptr __pPrivilegeList; + static std::unique_ptr __pMutex; + +}; // _PrivilegeCache + +}} // Tizen::Security + +#endif // _FSEC_INTERNAL_PRIVILEGE_CACHE_H_ diff --git a/src/security/FSec_PrivilegeInfo.cpp b/src/security/FSec_PrivilegeInfo.cpp new file mode 100644 index 0000000..08a4ec6 --- /dev/null +++ b/src/security/FSec_PrivilegeInfo.cpp @@ -0,0 +1,586 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_PrivilegeManagerInfo.cpp + * @brief This is the implementation for the Privilege Information class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FSec_DeviceKeyGenerator.h" +#include "FSec_PrivilegeInfo.h" + +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Security::Crypto; +using namespace Tizen::Text; + +namespace Tizen { namespace Security +{ + +_PrivilegeInfo::_PrivilegeInfo(void) +{ + memset(__bitwisePrivilege, 0, MAX_BITWISE_PRIV_SIZE); + __bitwiseLength = 0; + __apiVisibility = 0; +} + +_PrivilegeInfo::~_PrivilegeInfo(void) +{ + +} + +result +_PrivilegeInfo::Construct(const AppId& appId, const byte* pBitwisePrivilege) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC, (pBitwisePrivilege != null), E_INVALID_ARG, "One of the argument is invalid."); + SysTryReturnResult(NID_SEC, + appId.GetLength() > 0 && appId.GetLength() == MAX_APP_ID_SIZE, E_INVALID_ARG, + "One of the argument is invalid."); + + // Set base length of privilege information to max + __bitwiseLength = MAX_BITWISE_PRIV_SIZE; + + __appId = appId; + memcpy(__bitwisePrivilege, pBitwisePrivilege, __bitwiseLength); + + return r; +} + +result +_PrivilegeInfo::Construct(const AppId& appId, const String& encryptedPrivileges, const String& checksum) +{ + result r = E_SUCCESS; + byte* pDecrytpedBitwisePrivilege = null; + + std::unique_ptr pBitwisePrivilege(null); + _PackageInfoImpl infoImpl; + + SysLog(NID_SEC, "Enter."); + + SysTryReturnResult(NID_SEC, + appId.GetLength() > 0 && appId.GetLength() == MAX_APP_ID_SIZE, E_INVALID_ARG, + "One of the argument is invalid."); + SysTryReturnResult(NID_SEC, encryptedPrivileges.GetLength() > 0, E_INVALID_ARG, "One of the argument is invalid."); + SysTryReturnResult(NID_SEC, checksum.GetLength() > 0, E_INVALID_ARG, "One of the argument is invalid."); + + pBitwisePrivilege.reset(StringUtil::DecodeBase64StringN(encryptedPrivileges)); + SysTryReturnResult(NID_SEC, pBitwisePrivilege != null, E_SYSTEM, "An unexpected system error occurred."); + + pDecrytpedBitwisePrivilege = const_cast (pBitwisePrivilege->GetPointer()); + SysTryReturnResult(NID_SEC, pDecrytpedBitwisePrivilege != null, E_SYSTEM, "An unexpected system error occurred."); + + r = VerifyIntegrity(appId, pDecrytpedBitwisePrivilege, checksum, pBitwisePrivilege->GetLimit()); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_INVALID_ARG, "The checksum is abnormal."); + + // Set base length of privilege information + __bitwiseLength = pBitwisePrivilege->GetLimit(); + + memcpy(__bitwisePrivilege, pDecrytpedBitwisePrivilege, __bitwiseLength); + __appId = appId; + + r = infoImpl.Construct(appId); + if (r == E_APP_NOT_INSTALLED) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The package information does not exist."); + return E_DATA_NOT_FOUND; + } + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + __apiVisibility = infoImpl.GetApiVisibility(); + SysTryReturnResult(NID_SEC, __apiVisibility >= 0, E_SYSTEM, "An unexpected system error occurred."); + + SysLog(NID_SEC, "Exit."); + return r; +} + +result +_PrivilegeInfo::Construct(const AppId& appId, const String& encryptedPrivileges, const String& checksum, const String& encryptedVisibiliity, const String& visibilityChecksum) +{ + result r = E_SUCCESS; + byte* pDecrytpedBitwisePrivilege = null; + int visibility = 0; + + ByteBuffer ivByte; + std::unique_ptr pKey(null); + std::unique_ptr pEncryptedBitwisePrivilege(null); + std::unique_ptr pBitwisePrivilege(null); + std::unique_ptr pEncryptedVisibility(null); + std::unique_ptr pVisibility(null); + AesCipher cipherDec; + _PackageInfoImpl infoImpl; + const byte ivector[_IV_LEN] = + { + 0x3E, 0xB5, 0x01, 0x45, 0xE4, 0xF8, 0x75, 0x3F, + 0x08, 0x9D, 0x9F, 0x57, 0x3B, 0x63, 0xEF, 0x4B + }; + + SysLog(NID_SEC, "Enter."); + + SysTryReturnResult(NID_SEC, + appId.GetLength() > 0 && appId.GetLength() == MAX_APP_ID_SIZE, E_INVALID_ARG, + "One of the argument is invalid."); + SysTryReturnResult(NID_SEC, encryptedPrivileges.GetLength() > 0, E_INVALID_ARG, "One of the argument is invalid."); + SysTryReturnResult(NID_SEC, checksum.GetLength() > 0, E_INVALID_ARG, "One of the argument is invalid."); + + pEncryptedBitwisePrivilege.reset(StringUtil::DecodeBase64StringN(encryptedPrivileges)); + SysTryReturnResult(NID_SEC, pEncryptedBitwisePrivilege != null, E_SYSTEM, "An unexpected system error occurred."); + + pEncryptedVisibility.reset(StringUtil::DecodeBase64StringN(encryptedVisibiliity)); + SysTryReturnResult(NID_SEC, pEncryptedVisibility != null, E_SYSTEM, "An unexpected system error occurred."); + + r = ivByte.Construct(_IV_LEN); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = ivByte.SetArray(ivector, 0, _IV_LEN); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + ivByte.Flip(); + + r = cipherDec.Construct(L"CBC/128/PKCS7PADDING", CIPHER_DECRYPT); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + pKey.reset(_DeviceKeyGenerator::GenerateDeviceKeyN(_KEY_LEN)); + SysTryReturnResult(NID_SEC, pKey != null, E_SYSTEM, "An unexpected system error occurred."); + + r = cipherDec.SetKey(*pKey.get()); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = cipherDec.SetInitialVector(ivByte); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + pBitwisePrivilege.reset(cipherDec.DecryptN(*pEncryptedBitwisePrivilege.get())); + SysTryReturnResult(NID_SEC, pBitwisePrivilege != null, E_SYSTEM, "An unexpected system error occurred."); + + pVisibility.reset(cipherDec.DecryptN(*pEncryptedVisibility.get())); + SysTryReturnResult(NID_SEC, pBitwisePrivilege != null, E_SYSTEM, "An unexpected system error occurred."); + + pDecrytpedBitwisePrivilege = const_cast (pBitwisePrivilege->GetPointer()); + SysTryReturnResult(NID_SEC, pDecrytpedBitwisePrivilege != null, E_SYSTEM, "An unexpected system error occurred."); + + visibility = static_cast(*(pVisibility->GetPointer())); + + r = VerifyIntegrity(appId, pDecrytpedBitwisePrivilege, checksum, pBitwisePrivilege->GetLimit(), visibility, visibilityChecksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_INVALID_ARG, "The checksum is abnormal."); + + // Set base length of privilege information + __bitwiseLength = pBitwisePrivilege->GetLimit(); + + memcpy(__bitwisePrivilege, pDecrytpedBitwisePrivilege, __bitwiseLength); + __appId = appId; + + __apiVisibility = visibility; + + SysLog(NID_SEC, "Exit."); + return r; +} + +_PrivilegeInfo* +_PrivilegeInfo::CloneN(void) const +{ + _PrivilegeInfo* pPrivilegeInfo = null; + + ClearLastResult(); + + pPrivilegeInfo = new (std::nothrow) _PrivilegeInfo(); + SysTryReturn(NID_SEC, pPrivilegeInfo != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + pPrivilegeInfo->__bitwiseLength = this->__bitwiseLength; + + pPrivilegeInfo->__appId.Clear(); + pPrivilegeInfo->__appId.Append(this->__appId); + memcpy(pPrivilegeInfo->__bitwisePrivilege, this->__bitwisePrivilege, pPrivilegeInfo->__bitwiseLength); + + return pPrivilegeInfo; +} + +result +_PrivilegeInfo::Construct(const _PrivilegeInfo& privilegeInfo) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC, privilegeInfo.__appId.GetLength() > 0 && privilegeInfo.__appId.GetLength() == MAX_APP_ID_SIZE, E_INVALID_ARG, "The argument is invalid."); + + __bitwiseLength = privilegeInfo.__bitwiseLength; + + __appId = privilegeInfo.__appId; + memcpy(__bitwisePrivilege, privilegeInfo.__bitwisePrivilege, __bitwiseLength); + + __apiVisibility = privilegeInfo.__apiVisibility; + + return r; +} + +const String +_PrivilegeInfo::GetAppId(void) const +{ + return __appId; +} + +result +_PrivilegeInfo::GetBitwisePrivilegeN(byte*& pBitwisePrivilege) const +{ + byte* pReturn = null; + result r = E_SUCCESS; + + SysLog(NID_SEC, "Enter."); + + pReturn = (byte*) malloc(sizeof(byte) * MAX_BITWISE_PRIV_SIZE); + SysTryReturnResult(NID_SEC, pReturn != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + memcpy(pReturn, __bitwisePrivilege, MAX_BITWISE_PRIV_SIZE); + + pBitwisePrivilege = pReturn; + + SysLog(NID_SEC, "Exit."); + return r; +} + +result +_PrivilegeInfo::GetEncryptedBitwise(String& encryptedPrivileges) const +{ + result r = E_SUCCESS; + ByteBuffer ivByte; + std::unique_ptr pKey(null); + std::unique_ptr pEncryptedBitwisePrivilege(null); + std::unique_ptr pBitwisePrivilege(null); + AesCipher cipherEnc; + const byte ivector[_IV_LEN] = { 0x3E, 0xB5, 0x01, 0x45, 0xE4, 0xF8, 0x75, 0x3F, 0x08, 0x9D, 0x9F, 0x57, 0x3B, 0x63, 0xEF, 0x4B}; + + SysLog(NID_SEC, "Enter."); + + pBitwisePrivilege.reset(new (std::nothrow) ByteBuffer()); + SysTryReturnResult(NID_SEC, pBitwisePrivilege != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + + r = pBitwisePrivilege->Construct(__bitwiseLength); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = ivByte.Construct(_IV_LEN); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = ivByte.SetArray(ivector, 0, _IV_LEN); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + ivByte.Flip(); + + r = pBitwisePrivilege->SetArray(__bitwisePrivilege, 0, __bitwiseLength); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + pBitwisePrivilege->Flip(); + + r = cipherEnc.Construct(L"CBC/128/PKCS7PADDING", CIPHER_ENCRYPT); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + pKey.reset(_DeviceKeyGenerator::GenerateDeviceKeyN(_KEY_LEN)); + SysTryReturnResult(NID_SEC, pKey != null, E_SYSTEM, "An unexpected system error occurred."); + + r = cipherEnc.SetKey(*(pKey.get())); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = cipherEnc.SetInitialVector(ivByte); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + pEncryptedBitwisePrivilege.reset(cipherEnc.EncryptN(*(pBitwisePrivilege.get()))); + SysTryReturnResult(NID_SEC, pEncryptedBitwisePrivilege != null, E_SYSTEM, "An unexpected system error occurred."); + + r = StringUtil::EncodeToBase64String(*(pEncryptedBitwisePrivilege.get()), encryptedPrivileges); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + SysLog(NID_SEC, "Exit."); + return r; +} + +result +_PrivilegeInfo::GetChecksum(String& checksum) const +{ + result r = E_SUCCESS; + byte tempChecksumString[MAX_BITWISE_PRIV_SIZE + MAX_APP_ID_SIZE]; + + ByteBuffer ivByte; + ByteBuffer input; + std::unique_ptr pKey(null); + std::unique_ptr pHmac(null); + std::unique_ptr pChecksumByteBuffer(null); + std::unique_ptr pAppId(null); + + pAppId.reset(_StringConverter::CopyToCharArrayN(__appId)); + SysTryReturnResult(NID_SEC, pAppId != null, E_SYSTEM, "An unexpected system error occurred."); + + memcpy(tempChecksumString, pAppId.get(), MAX_APP_ID_SIZE); + memcpy(tempChecksumString + MAX_APP_ID_SIZE, __bitwisePrivilege, __bitwiseLength); + + pAppId.reset(null); + + r = input.Construct(MAX_APP_ID_SIZE + __bitwiseLength); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = input.SetArray(tempChecksumString, 0, MAX_APP_ID_SIZE + __bitwiseLength); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + input.Flip(); + + pHmac.reset(new (std::nothrow) Sha1Hmac()); + SysTryReturnResult(NID_SEC, pHmac != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Memory allocation is failed."); + + pKey.reset(_DeviceKeyGenerator::GenerateDeviceKeyN(_KEY_LEN)); + SysTryReturnResult(NID_SEC, pKey != null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = pHmac->SetKey(*(pKey.get())); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pChecksumByteBuffer.reset(pHmac->GetHmacN(input)); + SysTryReturnResult(NID_SEC, pChecksumByteBuffer != null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = StringUtil::EncodeToBase64String(*(pChecksumByteBuffer.get()), checksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return r; +} + +bool +_PrivilegeInfo::HasPrivilege(_Privilege privilege) const +{ + bool ret = false; + int targetIndex = static_cast< int >(privilege) / _BITS_IN_BYTE; + byte privilegeBit = (byte) (static_cast< int >(privilege) % _BITS_IN_BYTE); + byte bitwiseTargetPrivilege = 0; + byte tempBitwisePrivilege = 0; + + if (__apiVisibility != _API_VISIBILITY_NONE) // To be removed + { + if (visibilityLevelListTable[privilege][_PRV_API_VER_2_0] > __apiVisibility) + { + SysLog(NID_SEC, "Result : FALSE [Visibility]"); + return ret; + } + } + + bitwiseTargetPrivilege = bitwiseTargetPrivilege | (1 << privilegeBit); + tempBitwisePrivilege = __bitwisePrivilege[targetIndex] & bitwiseTargetPrivilege; + + if (bitwiseTargetPrivilege == tempBitwisePrivilege) + { + SysLog(NID_SEC, "Result : TRUE"); + ret = true; + } + else + { + SysLogException(NID_SEC, E_PRIVILEGE_DENIED, "Result : FALSE [%ls, %ls]", __appId.GetPointer(), privilegeListTable[privilege].privilegeString); + } + + return ret; +} + +result +_PrivilegeInfo::VerifyIntegrity(const AppId& appId, const byte* targetBitwisePrivilege, const Tizen::Base::String& storedChecksum, int length) +{ + result r = E_SUCCESS; + bool verifyResult = false; + byte tempChecksumString[MAX_BITWISE_PRIV_SIZE + MAX_APP_ID_SIZE]; + String base64EncodedChecksum; + ByteBuffer input; + std::unique_ptr pHash(null); + std::unique_ptr pChecksumByteBuffer(null); + std::unique_ptr pAppId(null); + + SysLog(NID_SEC, "Enter."); + + SysTryReturnResult(NID_SEC, length <= MAX_BITWISE_PRIV_SIZE, E_INVALID_ARG, "The privilege information of %ls is invalid.", appId.GetPointer()); + + pAppId.reset(_StringConverter::CopyToCharArrayN(appId)); + SysTryReturnResult(NID_SEC, pAppId != null, E_SYSTEM, "An unexpected system error occurred."); + + memcpy(tempChecksumString, pAppId.get(), MAX_APP_ID_SIZE); + memcpy(tempChecksumString + MAX_APP_ID_SIZE, targetBitwisePrivilege, length); + + pAppId.reset(null); + + r = input.Construct(MAX_APP_ID_SIZE + length); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = input.SetArray(tempChecksumString, 0, MAX_APP_ID_SIZE + length); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + input.Flip(); + + pHash.reset(new (std::nothrow) Sha1Hash()); + SysTryReturnResult(NID_SEC, pHash != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + + pChecksumByteBuffer.reset(pHash->GetHashN(input)); + SysTryReturnResult(NID_SEC, pChecksumByteBuffer != null, E_SYSTEM, "An unexpected system error occurred."); + + r = StringUtil::EncodeToBase64String(*(pChecksumByteBuffer.get()), base64EncodedChecksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + verifyResult = storedChecksum.Equals(base64EncodedChecksum, true); + if (verifyResult != true) + { + r = E_INVALID_ARG; + } + + SysLog(NID_SEC, "Exit."); + return r; +} + +result +_PrivilegeInfo::VerifyIntegrityEx(const AppId& appId, const byte* targetBitwisePrivilege, const Tizen::Base::String& storedChecksum, int length) +{ + result r = E_SUCCESS; + bool verifyResult = false; + byte tempChecksumString[MAX_BITWISE_PRIV_SIZE + MAX_APP_ID_SIZE]; + String base64EncodedChecksum; + ByteBuffer ivByte; + ByteBuffer input; + std::unique_ptr pHmac(null); + std::unique_ptr pChecksumByteBuffer(null); + std::unique_ptr pKey(null); + std::unique_ptr pAppId(null); + + SysLog(NID_SEC, "Enter."); + SysTryReturnResult(NID_SEC, length <= MAX_BITWISE_PRIV_SIZE, E_INVALID_ARG, "The privilege information of [%ls] is invalid.", appId.GetPointer()); + + pAppId.reset(_StringConverter::CopyToCharArrayN(appId)); + SysTryReturnResult(NID_SEC, pAppId != null, E_SYSTEM, "An unexpected system error occurred."); + + memcpy(tempChecksumString, pAppId.get(), MAX_APP_ID_SIZE); + memcpy(tempChecksumString + MAX_APP_ID_SIZE, targetBitwisePrivilege, length); + + pAppId.reset(null); + + r = input.Construct(MAX_APP_ID_SIZE + length); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = input.SetArray(tempChecksumString, 0, MAX_APP_ID_SIZE + length); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + input.Flip(); + + pHmac.reset(new (std::nothrow) Sha1Hmac()); + SysTryReturnResult(NID_SEC, pHmac != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + + pKey.reset(_DeviceKeyGenerator::GenerateDeviceKeyN(_KEY_LEN)); + SysTryReturnResult(NID_SEC, pKey != null, E_SYSTEM, "An unexpected system error occurred."); + + r = pHmac->SetKey(*(pKey.get())); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + pChecksumByteBuffer.reset(pHmac->GetHmacN(input)); + SysTryReturnResult(NID_SEC, pChecksumByteBuffer != null, E_SYSTEM, "An unexpected system error occurred."); + + r = StringUtil::EncodeToBase64String(*(pChecksumByteBuffer.get()), base64EncodedChecksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + verifyResult = storedChecksum.Equals(base64EncodedChecksum, true); + if (verifyResult != true) + { + r = E_INVALID_ARG; + } + + SysLog(NID_SEC, "Exit."); + return r; +} + +result +_PrivilegeInfo::VerifyIntegrity(const AppId& appId, const byte* targetBitwisePrivilege, const Tizen::Base::String& storedChecksum, int length, int visibility, const Tizen::Base::String& storedVisibilityChecksum) +{ + result r = E_SUCCESS; + bool verifyResult = false; + byte tempChecksumString[MAX_BITWISE_PRIV_SIZE + MAX_APP_ID_SIZE]; + byte tempVisibilityChecksumString[sizeof(int) + MAX_APP_ID_SIZE]; + String base64EncodedChecksum; + String base64EncodedVisibilityChecksum; + ByteBuffer ivByte; + ByteBuffer input; + ByteBuffer visibilityInput; + std::unique_ptr pHmac(null); + std::unique_ptr pChecksumByteBuffer(null); + std::unique_ptr pVisibilityChecksumByteBuffer(null); + std::unique_ptr pKey(null); + std::unique_ptr pAppId(null); + + SysLog(NID_SEC, "Enter."); + SysTryReturnResult(NID_SEC, length <= MAX_BITWISE_PRIV_SIZE, E_INVALID_ARG, "The privilege information of [%ls] is invalid.", appId.GetPointer()); + + pAppId.reset(_StringConverter::CopyToCharArrayN(appId)); + SysTryReturnResult(NID_SEC, pAppId != null, E_SYSTEM, "An unexpected system error occurred."); + + memcpy(tempChecksumString, pAppId.get(), MAX_APP_ID_SIZE); + memcpy(tempChecksumString + MAX_APP_ID_SIZE, targetBitwisePrivilege, length); + + memcpy(tempVisibilityChecksumString, pAppId.get(), MAX_APP_ID_SIZE); + memcpy(tempVisibilityChecksumString + MAX_APP_ID_SIZE, (byte*)(&visibility), sizeof(int)); + + pAppId.reset(null); + + r = input.Construct(MAX_APP_ID_SIZE + length); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = input.SetArray(tempChecksumString, 0, MAX_APP_ID_SIZE + length); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + input.Flip(); + + r = visibilityInput.Construct(MAX_APP_ID_SIZE + sizeof(int)); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = visibilityInput.SetArray(tempVisibilityChecksumString, 0, MAX_APP_ID_SIZE + sizeof(int)); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + visibilityInput.Flip(); + + pHmac.reset(new (std::nothrow) Sha1Hmac()); + SysTryReturnResult(NID_SEC, pHmac != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + + pKey.reset(_DeviceKeyGenerator::GenerateDeviceKeyN(_KEY_LEN)); + SysTryReturnResult(NID_SEC, pKey != null, E_SYSTEM, "An unexpected system error occurred."); + + r = pHmac->SetKey(*(pKey.get())); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + pChecksumByteBuffer.reset(pHmac->GetHmacN(input)); + SysTryReturnResult(NID_SEC, pChecksumByteBuffer != null, E_SYSTEM, "An unexpected system error occurred."); + + r = StringUtil::EncodeToBase64String(*(pChecksumByteBuffer.get()), base64EncodedChecksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + verifyResult = storedChecksum.Equals(base64EncodedChecksum, true); + if (verifyResult != true) + { + r = E_INVALID_ARG; + } + + pVisibilityChecksumByteBuffer.reset(pHmac->GetHmacN(visibilityInput)); + SysTryReturnResult(NID_SEC, pChecksumByteBuffer != null, E_SYSTEM, "An unexpected system error occurred."); + + r = StringUtil::EncodeToBase64String(*(pVisibilityChecksumByteBuffer.get()), base64EncodedVisibilityChecksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + verifyResult = storedVisibilityChecksum.Equals(base64EncodedVisibilityChecksum, true); + if (verifyResult != true) + { + r = E_INVALID_ARG; + } + + SysLog(NID_SEC, "Exit."); + return r; +} + +}} //Tizen::Security diff --git a/src/security/FSec_PrivilegeInfo.h b/src/security/FSec_PrivilegeInfo.h new file mode 100644 index 0000000..1c33b70 --- /dev/null +++ b/src/security/FSec_PrivilegeInfo.h @@ -0,0 +1,191 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_PrivilegeManagerInfo.h + * @brief This is the header file for the FSec_PrivilegeInfo. + * This header file contains the declarations of the FSec_PrivilegeInfo. + */ + +#ifndef _FSEC_INTERNAL_PRIVILEGE_INFO_H_ +#define _FSEC_INTERNAL_PRIVILEGE_INFO_H_ + +#include +#include "FSec_AccessControlTypes.h" + +namespace Tizen { namespace Security +{ + +/** + * @class _PrivilegeInfo + * @brief This class provides a basic information of privilege manager. + * @since 2.0 + * + * This class provides a basic information of privilege manager. + * + */ +class _PrivilegeInfo + : public Tizen::Base::Object +{ + +public: + /** + * This is the default constructor for this class. @n + * This method creates an uninitialized instance of _PrivilegeCache. + * + * @since 2.0 + */ + _PrivilegeInfo(void); + + /** + * This is the destructor for this class. + * + * @since 2.0 + */ + virtual ~_PrivilegeInfo(void); + + /** + * Initializes an instance of _PrivilegeInfo and sets its base information directly. + * + * @since 2.0 + * @return An error code + * @param[in] appId The application ID. + * @param[in] pBitwisePrivilege The bitwise privilege information. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + */ + result Construct(const Tizen::App::AppId& appId, const byte* pBitwisePrivilege); + + /** + * Initializes an instance of _PrivilegeInfo and sets its base information using stored information. + * + * @since 2.0 + * @return An error code + * @param[in] appId The application ID. + * @param[in] encryptedPrivileges A string containing encrypted privilege information. + * @param[in] checksum A string containing checksum of privilege information. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + */ + result Construct(const Tizen::App::AppId& appId, const Tizen::Base::String& encryptedPrivileges, const Tizen::Base::String& checksum); + result Construct(const Tizen::App::AppId& appId, const Tizen::Base::String& encryptedPrivileges, const Tizen::Base::String& checksum, const Tizen::Base::String& encryptedVisibiliity, const Tizen::Base::String& visibilityChecksum); + + /** + * Initializes an instance of _PrivilegeInfo and sets its base information using _PrivilegeInfo instance. + * + * @since 2.0 + * @return An error code + * @param[in] privilegeInfo An instance of _PrivilegeInfo. + * @exception E_SUCCESS The method is successful. + * @exception E_AUTHENTICATION The authentication has failed. + * @exception E_INVALID_ARG A specified input parameter is invalid. + */ + result Construct(const _PrivilegeInfo& privilegeInfo); + + /** + * CCreates and returns a polymorphic copy of _PrivilegeInfo instance. + * + * @return The clone of this instance + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + + _PrivilegeInfo* CloneN(void) const; + + /** + * Gets the application ID. + * + * @since 2.0 + * @return The application id + */ + const Tizen::Base::String GetAppId(void) const; + + /** + * Gets the bitwise privilege information. + * + * @since 2.0 + * @return An error code + * @param[out] pBitwisePrivilege The bitwise privilege information. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + result GetBitwisePrivilegeN(byte*& pBitwisePrivilege) const; + + /** + * Gets the encrypted string of bitwise privilege information. + * + * @since 2.0 + * @return An error code + * @param[out] encryptedPrivileges A string containing encrypted privilege information. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error occurred. + */ + result GetEncryptedBitwise(Tizen::Base::String& encryptedPrivileges) const; + + /** + * Gets the checksum of bitwise privilege information. + * + * @since 2.0 + * @return An error code + * @param[out] checksum A string containing checksum of privilege information. + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM An unexpected system error occurred. + */ + result GetChecksum(Tizen::Base::String& checksum) const; + + /** + * Checks whether the application has a privilege to invoke. + * + * @since 2.0 + * @return A boolean value of the result + * @param[int] privilege A value of enumerator of the specified privilege group. + */ + bool HasPrivilege(_Privilege privilege) const; + +private: + /** + * Verify the checksum string. + * + * @since 2.0 + * @return E_SUCCESS if the checksum is normal + * @param[in] appId The application ID. + * @param[int] targetBitwisePrivilege The bitwise privilege information. + * @param[in] storedChecksum The stored checksum. + * @param[out] pResult A boolean value of the result. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The checksum is abnormal. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error occurred. + */ + result VerifyIntegrity(const Tizen::App::AppId& appId, const byte* targetBitwisePrivilege, const Tizen::Base::String& storedChecksum, int length); + result VerifyIntegrityEx(const Tizen::App::AppId& appId, const byte* targetBitwisePrivilege, const Tizen::Base::String& storedChecksum, int length); + result VerifyIntegrity(const Tizen::App::AppId& appId, const byte* targetBitwisePrivilege, const Tizen::Base::String& storedChecksum, int length, int visibility, const Tizen::Base::String& storedVisibilityChecksum); + + _PrivilegeInfo(const _PrivilegeInfo& rhs); + _PrivilegeInfo& operator =(const _PrivilegeInfo& rhs); + +private: + Tizen::App::AppId __appId; + int __apiVisibility; + byte __bitwisePrivilege[MAX_BITWISE_PRIV_SIZE]; + int __bitwiseLength; + +}; // _PrivilegeInfo + +}} // Tizen::Security + +#endif // _FSEC_INTERNAL_PRIVILEGE_INFO_H_ diff --git a/src/security/FSec_PrivilegeManager.cpp b/src/security/FSec_PrivilegeManager.cpp new file mode 100644 index 0000000..c92d947 --- /dev/null +++ b/src/security/FSec_PrivilegeManager.cpp @@ -0,0 +1,387 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_PrivilegeManager.cpp + * @brief This is the implementation for the _PrivilegeManager class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSec_AccessControlTypes.h" +#include "FSec_PrivilegeManager.h" +#include "FSec_PrivilegeManagerMessage.h" +#include "FSec_PrivilegeCache.h" +#include "FSec_PrivilegeInfo.h" + + +using namespace Tizen::App; +using namespace Tizen::App::Package; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +namespace Tizen { namespace Security +{ + +_PrivilegeManager* _PrivilegeManager::__pPrivilegeManagerInstance = null; + +_PrivilegeManager::_PrivilegeManager(void) + : __pPrivilegeCache(null) +{ + return; +} + +_PrivilegeManager::~_PrivilegeManager(void) +{ + delete __pPrivilegeCache; + return; +} + +result +_PrivilegeManager::Construct(void) +{ + result r = E_SUCCESS; + + SysLog(NID_SEC, "Enter."); + + _PackageManagerImpl* pPackageManagerImpl = null; + + pPackageManagerImpl = _PackageManagerImpl::GetInstance(); + SysTryReturnResult(NID_SEC, pPackageManagerImpl != null, E_SYSTEM, "An unexpected system error occurred."); + + //pPackageManagerImpl->RemoveEventListener(this); + r = pPackageManagerImpl->AddEventListener(this); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + __pPrivilegeCache = new (std::nothrow) _PrivilegeCache(); + SysTryReturnResult(NID_SEC, __pPrivilegeCache != null, E_OUT_OF_MEMORY, "Memory allocation is failed."); + + r = __pPrivilegeCache->Construct(); + SysTryCatch(NID_SEC, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + SysLog(NID_SEC, "Exit."); + return r; + +CATCH: + + delete __pPrivilegeCache; + + SysLog(NID_SEC, "Exit."); + return r; +} + +void +_PrivilegeManager::InitInstance(void) +{ + result r = E_SUCCESS; + static _PrivilegeManager instance; + + SysLog(NID_SEC, "Enter"); + ClearLastResult(); + + r = instance.Construct(); + SysTryReturnVoidResult(NID_SEC, r == E_SUCCESS, r, "[%s] Propagating.", GetErrorMessage(r)); + + __pPrivilegeManagerInstance = &instance; + + SysLog(NID_SEC, "Exit"); +} + +_PrivilegeManager* +_PrivilegeManager::GetInstance(void) +{ + result r = E_SUCCESS; + static pthread_once_t onceBlock = PTHREAD_ONCE_INIT; + + SysLog(NID_SEC, "Enter"); + ClearLastResult(); + + if (__pPrivilegeManagerInstance == null) + { + pthread_once(&onceBlock, InitInstance); + + r = GetLastResult(); + if (IsFailed(r)) + { + onceBlock = PTHREAD_ONCE_INIT; + } + } + + SysLog(NID_SEC, "Exit"); + + return __pPrivilegeManagerInstance; +} + + +IList* +_PrivilegeManager::GetPrivilegeListN(const AppId& appId) +{ + result r = E_SUCCESS; + _PrivilegeInfo privilegeInfo; + byte* pTargetBitwisePrivilege = null; + IList* pPrivilegeList = null; + String encryptedPrivileges; + String checksum; + + SysLog(NID_SEC, "Enter."); + ClearLastResult(); + + r = RetrieveCipherPrivilege(appId, encryptedPrivileges, checksum); + if (r == E_DATA_NOT_FOUND) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + return null; + } + SysTryReturn(NID_SEC, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = privilegeInfo.Construct(appId, encryptedPrivileges, checksum); + SysTryCatch(NID_SEC, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = privilegeInfo.GetBitwisePrivilegeN(pTargetBitwisePrivilege); + SysTryCatch(NID_SEC, r == E_SUCCESS, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pPrivilegeList = UnpackPrivilegeN(pTargetBitwisePrivilege); + SysTryCatch(NID_SEC, pPrivilegeList != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + // fall through + +CATCH: + + if (pTargetBitwisePrivilege) + { + free(pTargetBitwisePrivilege); + pTargetBitwisePrivilege = null; + } + + SysLog(NID_SEC, "Exit."); + return pPrivilegeList; +} + +result +_PrivilegeManager::RetrieveCipherPrivilege(const AppId& appId, Tizen::Base::String& encryptedPrivileges, Tizen::Base::String& checksum) +{ + result r = E_SUCCESS; + + SysLog(NID_SEC, "Enter."); + + encryptedPrivileges.Clear(); + checksum.Clear(); + + _PackageInfoImpl infoImpl; + r = infoImpl.Construct(appId); + if (r == E_APP_NOT_INSTALLED) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + return E_DATA_NOT_FOUND; + } + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = infoImpl.GetPrivileges(encryptedPrivileges, checksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + SysTryReturnResult(NID_SEC, encryptedPrivileges.IsEmpty() != true, E_DATA_NOT_FOUND, "The privilege information does not exist."); + SysTryReturnResult(NID_SEC, checksum.IsEmpty() != true, E_SYSTEM, "An unexpected system error occurred."); + + SysLog(NID_SEC, "Exit."); + return r; +} + +result +_PrivilegeManager::RetrieveCipherPrivilegeEx(const AppId& appId, Tizen::Base::String& encryptedPrivileges, Tizen::Base::String& checksum) +{ + result r = E_SUCCESS; + + SysLog(NID_SEC, "Enter."); + + encryptedPrivileges.Clear(); + checksum.Clear(); + + String tempEncryptedPrivileges; + String tempChecksum; + + _PackageInfoImpl infoImpl; + r = infoImpl.Construct(appId); + if (r == E_APP_NOT_INSTALLED) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + return E_DATA_NOT_FOUND; + } + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = infoImpl.GetPrivileges(tempEncryptedPrivileges, tempChecksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + SysTryReturnResult(NID_SEC, tempEncryptedPrivileges.IsEmpty() != true, E_DATA_NOT_FOUND, "The privilege information does not exist."); + SysTryReturnResult(NID_SEC, tempChecksum.IsEmpty() != true, E_SYSTEM, "An unexpected system error occurred."); + + _PrivilegeInfo privilegeInfo; + + r = privilegeInfo.Construct(appId, tempEncryptedPrivileges, tempChecksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = privilegeInfo.GetEncryptedBitwise(encryptedPrivileges); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + r = privilegeInfo.GetChecksum(checksum); + SysTryReturnResult(NID_SEC, r == E_SUCCESS, E_SYSTEM, "An unexpected system error occurred."); + + SysLog(NID_SEC, "Exit."); + return r; +} + +_PrivilegeInfo* +_PrivilegeManager::RetrievePrivilegeInfoN(const AppId& appId) const +{ + result r = E_SUCCESS; + + String encryptedPrivileges; + String checksum; + std::unique_ptr<_PrivilegeInfo> pPrivilegeInfo(null); + _PackageInfoImpl infoImpl; + + SysLog(NID_SEC, "Enter."); + ClearLastResult(); + + pPrivilegeInfo.reset(__pPrivilegeCache->GetPrivilegeInfoN(appId)); + r = GetLastResult(); + + if (r == E_SUCCESS) + { + // nothing to do. + } + else if (r == E_DATA_NOT_FOUND) + { + r = RetrieveCipherPrivilege(appId, encryptedPrivileges, checksum); + if (r == E_DATA_NOT_FOUND) + { + SysLogException(NID_SEC, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] The privilege information does not exist."); + return null; + } + SysTryReturn(NID_SEC, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pPrivilegeInfo.reset(new (std::nothrow) _PrivilegeInfo()); + SysTryReturn(NID_SEC, pPrivilegeInfo != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pPrivilegeInfo->Construct(appId, encryptedPrivileges, checksum); + SysTryReturn(NID_SEC, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + r = __pPrivilegeCache->AddPrivilegeInfo(*(pPrivilegeInfo.get())); + SysTryReturn(NID_SEC, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + else + { + r = E_SYSTEM; + SysLogException(NID_SEC, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + return null; + } + + SysLog(NID_SEC, "Exit."); + return pPrivilegeInfo.release(); +} + + +IList* +_PrivilegeManager::UnpackPrivilegeN(const byte* pBitwisePrivilege) +{ + result r = E_SUCCESS; + byte maskFlag = 0; + int bitPosition = 0; + int bytePosition = 0; + int index = 0; + int privilegeBit = 0; + int privilegeEnum = 0; + std::unique_ptr pPrivilegeList(null); + + SysLog(NID_SEC, "Enter."); + ClearLastResult(); + + SysTryReturn(NID_SEC, pBitwisePrivilege != null, null, E_INVALID_ARG, "One of the argument is invalid."); + + pPrivilegeList.reset(new (std::nothrow) ArrayList()); + SysTryReturn(NID_SEC, pPrivilegeList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = pPrivilegeList->Construct(); + SysTryReturn(NID_SEC, r == E_SUCCESS, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + for (bytePosition = 0; bytePosition < MAX_BITWISE_PRIV_SIZE; bytePosition++) + { + maskFlag = 1; + + if (!(pBitwisePrivilege[bytePosition] & 0xFF)) + { + // Pass the checking of empty byte filed. + continue; + } + + for (bitPosition = 0; bitPosition < _BITS_IN_BYTE; bitPosition++) + { + privilegeBit = (int) (pBitwisePrivilege[bytePosition] & maskFlag); + if (!privilegeBit) + { + // Shift the maskFlag by 1 bit when face the empty bit. + maskFlag = maskFlag << 1; + continue; + } + + privilegeEnum = (bytePosition * _BITS_IN_BYTE) + bitPosition; + + for (index = 0; index < _MAX_PRIVILEGE_ENUM; index++) + { + if (privilegeEnum == privilegeListTable[index].privilege) + { + String* privilegeString = new (std::nothrow) String(privilegeListTable[index].privilegeString); + SysTryCatch(NID_SEC, privilegeString != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, + "[E_OUT_OF_MEMORY]The memory is insufficient."); + + pPrivilegeList->Add(*privilegeString); + break; + } + } + + // Shift the maskFlag by 1 bit to check the next byte filed. + maskFlag = maskFlag << 1; + } + } + + SysLog(NID_SEC, "Exit."); + return pPrivilegeList.release(); + +CATCH: + + pPrivilegeList->RemoveAll(true); + return null; +} + +void +_PrivilegeManager::OnPackageInstallationCompleted(const PackageId& packageId, PackageInstallationResult installationResult) +{ + SysLog(NID_SEC, "Enter."); + + __pPrivilegeCache->RemovePrivilegeInfo(packageId); + SysLog(NID_SEC, "%ls is removed.", packageId.GetPointer()); + + SysLog(NID_SEC, "Exit."); + + return; +} + +}} //Tizen::Security diff --git a/src/security/FSec_PrivilegeManagerMessage.cpp b/src/security/FSec_PrivilegeManagerMessage.cpp new file mode 100644 index 0000000..6aaf70b --- /dev/null +++ b/src/security/FSec_PrivilegeManagerMessage.cpp @@ -0,0 +1,46 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_PrivilegeManagerMessage.cpp + * @brief This is the message type of the IPC communication of _PrivilegeManager daemon. + */ + +#define IPC_MESSAGE_IMPL +#include "FSec_PrivilegeManagerMessage.h" + +// Generate constructors. +#include +#include "FSec_PrivilegeManagerMessage.h" +// Generate destructors. + +#include +#include "FSec_PrivilegeManagerMessage.h" + +// Generate param traits write methods. +#include +namespace IPC +{ +#include "FSec_PrivilegeManagerMessage.h" +} // namespace IPC + +// Generate param traits read methods. +#include +namespace IPC +{ +#include "FSec_PrivilegeManagerMessage.h" +} // namespace IPC diff --git a/src/security/FSec_Prng.cpp b/src/security/FSec_Prng.cpp new file mode 100644 index 0000000..8081cc5 --- /dev/null +++ b/src/security/FSec_Prng.cpp @@ -0,0 +1,329 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_Prng.cpp + * @brief This file contains implementation of Pseudo Random Function based on ANSI X9.31 Appendix A.2.4. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSec_Prng.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security +{ + +ByteBuffer* +_Prng::GetRandomBytesN(const EVP_CIPHER* pAlg, long outLen) +{ + result r = E_SUCCESS; + + ClearLastResult(); + + SysTryReturn(NID_SEC, pAlg != null && outLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data are not valid."); + + std::unique_ptr pPrng (_Prng::CreatePrngContextN()); + SysTryReturn(NID_SEC, pPrng != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new PrngContext object failed."); + + std::unique_ptr pOutBuf (new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC, pOutBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new ByteBuffer failed."); + + // init pAlg details + pPrng->pAlg = pAlg; + pPrng->lenKey = pAlg->key_len; + pPrng->blockSize = pAlg->block_size; + pPrng->lenSeed = pPrng->blockSize; + + r = GenerateKey(*pPrng); + SysTryCatch(NID_SEC, !IsFailed(r), , r, "[%s] Failed to generate key.", GetErrorMessage(r)); + + r = GenerateSeed(*pPrng); + SysTryCatch(NID_SEC, !IsFailed(r), , r, "[%s] Failed to do generate seed.", GetErrorMessage(r)); + + r = pOutBuf->Construct(outLen); + SysTryCatch(NID_SEC, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pPrng->pRand = const_cast< byte* >(pOutBuf->GetPointer()); + pPrng->randSize = outLen; + pPrng->curOffset = 0; + + r = GenerateRandomBytes(*pPrng, null); + SysTryCatch(NID_SEC, !IsFailed(r), , r, "[%s] Failed to generate random bytes.", GetErrorMessage(r)); + +CATCH: + + return pOutBuf.release(); +} + +result +_Prng::GenerateKey(PrngContext& prng) +{ + result r = E_SUCCESS; + unsigned long index = 0; + unsigned long offset = 0; + clock_t tick = null; + + prng.pKey = std::unique_ptr (new (std::nothrow) byte[prng.lenKey]); + SysTryReturn(NID_SEC, prng.pKey != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + offset = 0; + index = sizeof(clock_t); + + while (offset < prng.lenKey) + { + if ((offset + sizeof(clock_t)) > prng.lenKey) + { + index = prng.lenKey - offset; + } + tick = clock(); + PerformXor(prng.pKey.get() + offset, reinterpret_cast< byte* >(&tick), index, prng.pKey.get() + offset); + offset += index; + } + + prng.lenKey = offset; + return r; +} + +result +_Prng::GenerateSeed(PrngContext& prng) +{ + result r = E_SUCCESS; + unsigned long offset = 0; + unsigned long index = 0; + clock_t tick = 0; + time_t miliSecond = 0; + + miliSecond = time(null); + + prng.pSeed = std::unique_ptr (new (std::nothrow) byte[prng.lenSeed]); + SysTryReturn(NID_SEC, prng.pSeed != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + offset = 0; + index = sizeof(clock_t); + + while (offset < prng.lenSeed) + { + if ((offset + sizeof(clock_t)) > prng.lenSeed) + { + index = prng.lenSeed - offset; + } + + tick = clock(); + tick = tick + miliSecond; + PerformXor(prng.pSeed.get() + offset, reinterpret_cast< byte* >(&tick), index, prng.pSeed.get() + offset); + offset += index; + } + + prng.lenSeed = offset; + return r; +} + +void +_Prng::PerformXor(byte* pIn1, byte* pIn2, unsigned long inLen, byte* pOut) +{ + unsigned long index = 0; + + for (index = 0; index < inLen; index++) + { + pOut[index] = pIn1[index] ^ pIn2[index]; + } + +} + +result +_Prng::GenerateRandomBytes(PrngContext& prng, ByteBuffer* pSeed) +{ + result r = E_SUCCESS; + unsigned int ret = 0; + unsigned long tmp = 0; + unsigned long offset = 0; + unsigned long lenInterVal1 = 0; + unsigned long lenInterVal2 = 0; + unsigned long dtLen = 0; + unsigned long blockSize = prng.blockSize; + unsigned long randSize = prng.randSize; + unsigned long lenInterVal1XorBlockLen = 0; + unsigned long lenInterVal2XorInterVal1 = 0; + std::unique_ptr pBlock; + std::unique_ptr pInterVal1; + std::unique_ptr pInterVal2; + std::unique_ptr pInterVal1XorBlock; + std::unique_ptr pInterVal2XorInterVal1; + byte* pDt = null; + clock_t tick = null; + EVP_CIPHER_CTX cipherCtx; + const EVP_CIPHER* pEncryptionAlgorithm = null; + + if (pSeed != null) + { + pDt = const_cast< byte* >(pSeed->GetPointer()); + dtLen = pSeed->GetRemaining(); + } + + pBlock = std::unique_ptr (new (std::nothrow) byte[blockSize]); + SysTryCatch(NID_SEC, pBlock != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + pInterVal1 = std::unique_ptr (new (std::nothrow) byte[blockSize]); + SysTryCatch(NID_SEC, pInterVal1 != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + pInterVal2 = std::unique_ptr (new (std::nothrow) byte[blockSize]); + SysTryCatch(NID_SEC, pInterVal2 != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + pInterVal1XorBlock = std::unique_ptr (new (std::nothrow) byte[blockSize]); + SysTryCatch(NID_SEC, pInterVal1XorBlock != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + pInterVal2XorInterVal1 = std::unique_ptr (new (std::nothrow) byte[blockSize]); + SysTryCatch(NID_SEC, pInterVal2XorInterVal1 != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + lenInterVal1 = blockSize; + lenInterVal2 = blockSize; + lenInterVal1XorBlockLen = blockSize; + lenInterVal2XorInterVal1 = blockSize; + + while (prng.curOffset < randSize) + { + blockSize = prng.blockSize; + + if (pDt == null) + { + time_t sttime = null; + sttime = time(null); + + //get D and append with xor of clock tick and random value in buffer till block size is reached + memcpy(pBlock.get(), reinterpret_cast< byte* >(&sttime), sizeof(time_t)); + + offset += sizeof(time_t); + tmp = sizeof(clock_t); + while (offset < blockSize) + { + if ((offset + sizeof(clock_t)) > blockSize) + { + tmp = blockSize - offset; + } + + tick = clock(); + PerformXor(pBlock.get() + offset, reinterpret_cast< byte* >(&tick), tmp, pBlock.get() + offset); + offset += tmp; + } + } + else + { + if (dtLen != blockSize) + { + r = E_INVALID_ARG; + SysLogException(NID_SEC, r, "The seed length do not match the data block size."); + goto CATCH; + } + + memcpy(pBlock.get(), pDt, dtLen); + } + + // Selects the encryption algorithm using prng.pAlg + pEncryptionAlgorithm = prng.pAlg; + + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, pEncryptionAlgorithm, prng.pKey.get(), null, 0); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, 0); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, pInterVal1.get(), reinterpret_cast< int* >(&lenInterVal1), pBlock.get(), blockSize); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + //////////////////////////////////////////////////////////////////////////////////////////////////// + + SysTryCatch(NID_SEC, lenInterVal1 == blockSize, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input and output data lengths do not match."); + + PerformXor(pInterVal1.get(), prng.pSeed.get(), blockSize, pInterVal1XorBlock.get()); + lenInterVal1XorBlockLen = lenInterVal1; + + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, pEncryptionAlgorithm, prng.pKey.get(), null, 0); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, 0); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, pInterVal2.get(), reinterpret_cast< int* >(&lenInterVal2), pInterVal1XorBlock.get(), lenInterVal1XorBlockLen); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + //////////////////////////////////////////////////////////////////////////////////////////////////// + + SysTryCatch(NID_SEC, lenInterVal2 == blockSize, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input and output data lengths do not match."); + + PerformXor(pInterVal2.get(), pInterVal1.get(), blockSize, pInterVal2XorInterVal1.get()); + lenInterVal2XorInterVal1 = blockSize; + + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, pEncryptionAlgorithm, prng.pKey.get(), null, 0); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, 0); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, prng.pSeed.get(), reinterpret_cast< int* >(&prng.lenSeed), pInterVal2XorInterVal1.get(), lenInterVal2XorInterVal1); + SysTryCatch(NID_SEC, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + //////////////////////////////////////////////////////////////////////////////////////////////////// + + SysTryCatch(NID_SEC, prng.lenSeed == blockSize, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input and output data lengths do not match."); + + if ((prng.curOffset + lenInterVal2) > prng.randSize) + { + lenInterVal2 = prng.randSize - prng.curOffset; + } + + memcpy(prng.pRand + prng.curOffset, pInterVal2.get(), lenInterVal2); + prng.curOffset += lenInterVal2; + } + +CATCH: + + EVP_CIPHER_CTX_cleanup(&cipherCtx); + + return r; +} + +_Prng::PrngContext* +_Prng::CreatePrngContextN(void) +{ + ClearLastResult(); + + std::unique_ptr pPrng (new (std::nothrow) PrngContext()); + SysTryReturn(NID_SEC, pPrng != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new PrngContext object failed."); + + memset(pPrng.get(), 0, sizeof(PrngContext)); + + return pPrng.release(); +} + +} } //Tizen::Security diff --git a/src/security/FSec_Prng.h b/src/security/FSec_Prng.h new file mode 100644 index 0000000..9428317 --- /dev/null +++ b/src/security/FSec_Prng.h @@ -0,0 +1,140 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_Prng.h + * @brief This header file contains declarations of Pseudo Random Function based on ANSI X9.31 Appendix A.2.4. + */ +#ifndef _FSEC_INTERNAL_PRNG_H_ +#define _FSEC_INTERNAL_PRNG_H_ + +#include +#include + +struct evp_cipher_st; + + +namespace Tizen { namespace Security +{ + +/** + * @class _Prng + * @brief This class generates a pseudo random number as per X9.31 specification using algorithm passed as input.. + * @since 2.1 + * + * Generate random numbers as per X9.31 specification using algorithm passed as input. + * + * @see ISecureRandom, AesSecureRandom, DesSecureRandom, DesEdeSecureRandom + */ +class _Prng +{ + +public: + /** + * Generate random numbers as per X9.31 specification using algorithm passed as input. + * + * @since 2.1 + * @return Returns pointer to byte buffer containing generated random number. + * @param[in] pAlg Pointer to algorithm used for random number generation. Supports EVP_des_ecb(), EVP_des_ede3_ecb() and EVP_AES_128_ecb(). + * @param[in] requiredLength Integer type indicating required size of random number. + */ + static Tizen::Base::ByteBuffer* GetRandomBytesN(const evp_cipher_st* pAlg, long requiredLength); + +private: + + _Prng(void); + _Prng(const _Prng& rhs); + _Prng& operator =(const _Prng& rhs); + ~_Prng(void); + + /** + * Defines the Prng context structure. + * + * @since 2.1 + */ + struct PrngContext + { + unsigned long lenSeed; //seed length + unsigned long blockSize; //block size + unsigned long randSize; + unsigned long curOffset; + unsigned long lenKey; //key length + std::unique_ptr pKey; //key + std::unique_ptr pSeed; //seed + byte* pRand; //holds only reference - memory pointer by this variable to be freed by caller + const evp_cipher_st* pAlg; //algorithm type + }; + + /** + * Generate and fill keys in PrngContext. + * + * @since 2.1 + * @return An error code. + * @param[in] prng Reference to PRNG context structure. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + static result GenerateKey(PrngContext& prng); + + /** + * Generate and fill seed in PrngContext. + * + * @since 2.1 + * @return An error code. + * @param[in] prng Reference to PRNG context. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + static result GenerateSeed(PrngContext& prng); + + /** + * Perform XOR operation using content in in1 and in2 and store output in out. + * + * @since 2.1 + * @param[in] pIn1 Pointer to input buffer 1. + * @param[in] pIn2 Pointer to input buffer 2. + * @param[in] inLen Length of input buffer. + * @param[out] pOut Pointer to out buffer to which output is stored. + * @exception E_SUCCESS The method is successful. + */ + static void PerformXor(byte* pIn1, byte* pIn2, unsigned long inLen, byte* pOut); + + /** + * Generate random number. + * + * @since 2.1 + * @return An error code. + * @param[in] prng Reference to PRNG context. + * @param[in] pSeed Pointer to byte buffer containing date factor . + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + static result GenerateRandomBytes(PrngContext& prng, Tizen::Base::ByteBuffer* pSeed); + + /** + * Create PRNG context. + * + * @since 2.1 + * @return Returns pointer to PRNG context on success,NULL on failure. + */ + static PrngContext* CreatePrngContextN(void); + +}; //_Prng + +} } //Tizen::Security + +#endif //_FSEC_INTERNAL_PRNG_H_ diff --git a/src/security/cert/CMakeLists.txt b/src/security/cert/CMakeLists.txt new file mode 100755 index 0000000..e9834b2 --- /dev/null +++ b/src/security/cert/CMakeLists.txt @@ -0,0 +1,33 @@ +SET (MODULE_DIR ${CMAKE_SOURCE_DIR}/src/security/cert) + +INCLUDE_DIRECTORIES( + ${SLP_INCLUDE_DIRS} + /usr/include/chromium + ${CMAKE_SOURCE_DIR}/inc + ${CMAKE_SOURCE_DIR}/src/base/inc + ${CMAKE_SOURCE_DIR}/src/io/inc + ${CMAKE_SOURCE_DIR}/src/app/inc + ${CMAKE_SOURCE_DIR}/src/system/inc + ${CMAKE_SOURCE_DIR}/src/security/cert + ) + +LIST (APPEND ${this_target}_SOURCE_FILES +#Certificate Manager Files + ${MODULE_DIR}/FSecCert_Asn1Parser.cpp + ${MODULE_DIR}/FSecCert_CertDbStore.cpp + ${MODULE_DIR}/FSecCert_Base64.cpp + ${MODULE_DIR}/FSecCert_CertDbManager.cpp + ${MODULE_DIR}/FSecCert_CertManager.cpp + ${MODULE_DIR}/FSecCert_CertService.cpp + ${MODULE_DIR}/FSecCert_CertFileStore.cpp + ${MODULE_DIR}/FSecCert_CertChain.cpp + ${MODULE_DIR}/FSecCert_Certificate.cpp + ${MODULE_DIR}/FSecCert_CertList.cpp + ${MODULE_DIR}/FSecCert_CertPrivateKeyInfo.cpp + ${MODULE_DIR}/FSecCert_CertSignature.cpp + ${MODULE_DIR}/FSecCert_CertExtension.cpp + ${MODULE_DIR}/FSecCert_CertTime.cpp + ${MODULE_DIR}/FSecCert_CertMgrMessages.cpp + ${MODULE_DIR}/FSecCert_CertServiceStub.cpp +) + diff --git a/src/security/cert/FSecCertX509Certificate.cpp b/src/security/cert/FSecCertX509Certificate.cpp new file mode 100755 index 0000000..3601e95 --- /dev/null +++ b/src/security/cert/FSecCertX509Certificate.cpp @@ -0,0 +1,457 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertCertificate.cpp + * @brief This is the implementation file for X509Certificate class. + * + * This header file contains the implementation of X509Certificate class. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Cert +{ + +static const int _MAX_PUBLIC_KEY_BUFFER_SIZE = 4096; +static const int _MAX_SIGNATURE_BUFFER_SIZE = 1024; + +X509Certificate::X509Certificate(void) + : __certHandle(0) + , __pX509CertificateImpl(null) +{ + __certFormat = L""; +} + +X509Certificate::~X509Certificate(void) +{ + + if (__certHandle != 0) + { + _CertService::CloseCertificate(&__certHandle); + } + + +} + +result +X509Certificate::Construct(const Tizen::Base::ByteBuffer& input) +{ + result r = E_SUCCESS; + int length = 0; + byte* pBuffer = null; + + SysAssertf(__certHandle == 0, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + pBuffer = const_cast< byte* >(input.GetPointer()); + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input argument passed."); + + length = input.GetRemaining(); + SysTryReturnResult(NID_SEC_CERT, length > 0, E_INVALID_ARG, "Input buffer length is not positive."); + + r = _CertService::OpenCertificate(reinterpret_cast< char* >(pBuffer), length, &__certHandle); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to open certificates."); + + __certFormat = L"X509"; + + return r; +} + +Tizen::Base::String +X509Certificate::GetFormat(void) const +{ + ClearLastResult(); + + return L"X509"; +} + +CertificateType +X509Certificate::GetType(void) const +{ + result r = E_SUCCESS; + CertificateType certType = UNKNOWN_TYPE; + _CaCertType type = _CERT_TYPE_NOT_BOUNDED; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::CheckCertType(__certHandle, &type); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate type."); + + switch (type) + { + case _CERT_TYPE_ROOT_CA: + // fall through + case _CERT_TYPE_DEV_ROOT_CA: + // fall through + case _CERT_TYPE_ROOT_CA_BY_USER: + certType = ROOT_CA; + break; + + case _CERT_TYPE_ROOT_DOMAIN1: + // fall through + case _CERT_TYPE_SIM_ROOT_DOMAIN1: + // fall through + case _CERT_TYPE_DEV_ROOT_DOMAIN1: + certType = OPERATOR_DOMAIN; + break; + + case _CERT_TYPE_ROOT_DOMAIN3: + // fall through + case _CERT_TYPE_SIM_ROOT_DOMAIN3: + // fall through + case _CERT_TYPE_DEV_ROOT_DOMAIN3: + certType = TRUSTED_THIRD_PARTY_DOMAIN; + break; + + default: + certType = UNKNOWN_TYPE; + break; + } +CATCH: + return certType; + +} + +ByteBuffer* +X509Certificate::GetEncodedDataN(void) const +{ + result r = E_SUCCESS; + int length = 0; + char* pBufferValue = null; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertBufferN(__certHandle, pBufferValue, &length); + + std::unique_ptr< char[] > pBuffer(pBufferValue); + + SysTryReturn(NID_SEC_CERT, pBuffer != null, null, E_SYSTEM, "[E_SYSTEM] Failed to get encoded data of certificate."); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] Failed to get encoded data of certificate."); + SysTryReturn(NID_SEC_CERT, length > 0, null, E_SYSTEM, "[E_SYSTEM] Failed to get encoded data of certificate."); + + std::unique_ptr< ByteBuffer > pEncCert(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CERT, pEncCert != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory"); + + r = pEncCert->Construct(length); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = pEncCert->SetArray(reinterpret_cast< byte* >(pBuffer.get()), 0, length); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pEncCert->Flip(); + + return pEncCert.release(); +} + +bool +X509Certificate::Verify(const Tizen::Security::IPublicKey& publicKey) +{ + result r = E_SUCCESS; + int keyLen = 0; + byte* pPublickey = null; + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + std::unique_ptr< ByteBuffer > pPubKeyBuffer(publicKey.GetEncodedN()); + SysTryReturn(NID_SEC_CERT, pPubKeyBuffer != null, false, GetLastResult(), "[%s] Propagated.", GetErrorMessage(GetLastResult())); + + pPublickey = const_cast< byte* >(pPubKeyBuffer->GetPointer()); + SysTryReturn(NID_SEC_CERT, pPublickey != null, false, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument passed."); + + keyLen = pPubKeyBuffer->GetRemaining(); + SysTryReturn(NID_SEC_CERT, keyLen > 0, false, E_INVALID_ARG, "[E_INVALID_ARG] Public key buffer length is not positive."); + + r = _CertService::VerifyCert(__certHandle, pPublickey, keyLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Certificate verification failed."); + + return true; +} + +int +X509Certificate::GetSpecVersion(void) const +{ + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + return _CertService::GetCertVersion(__certHandle); + +} + +ValidityPeriod +X509Certificate::CheckValidityPeriod(void) +{ + result r = E_SUCCESS; + _CertValidityType type = _CERT_VALIDITY_UNKNOWN; + ValidityPeriod validity = VALIDITY_PERIOD_EXPIRED; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::CheckCertValidity(__certHandle, &type); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate validity information."); + + switch (type) + { + case _CERT_VALIDITY_VALID: + validity = VALIDITY_PERIOD_VALID; + break; + + case _CERT_VALIDITY_EXPIRED: + validity = VALIDITY_PERIOD_EXPIRED; + break; + + case _CERT_VALIDITY_NOT_YET_VALID: + validity = VALIDITY_PERIOD_NOT_YET_VALID; + break; + + default: + break; + } + +CATCH: + + return validity; +} + +String +X509Certificate::GetSerialNumber(void) const +{ + result r = E_SUCCESS; + _CertFieldInfos certInfo; + Tizen::Base::String dataString; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertInfo(__certHandle, _CERT_FIELD_SERIAL, &certInfo); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate serial number information."); + + dataString = certInfo.serialNo; + +CATCH: + return dataString; +} + +String +X509Certificate::GetSignatureAlgorithm(void) const +{ + result r = E_SUCCESS; + _CertFieldInfos certInfo; + Tizen::Base::String dataString; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertInfo(__certHandle, _CERT_FIELD_SIGALGORITHM, &certInfo); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate signature algorithm information."); + + dataString = certInfo.sigAlgorithm; + +CATCH: + return dataString; +} + +String +X509Certificate::GetNotBefore(void) const +{ + result r = E_SUCCESS; + _CertFieldInfos certInfo; + Tizen::Base::String dataString; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertInfo(__certHandle, _CERT_FIELD_VALIDITY, &certInfo); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate validity information."); + + dataString = certInfo.validityFrom; + +CATCH: + return dataString; +} + +String +X509Certificate::GetNotAfter(void) const +{ + result r = E_SUCCESS; + _CertFieldInfos certInfo; + Tizen::Base::String dataString; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertInfo(__certHandle, _CERT_FIELD_VALIDITY, &certInfo); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate validity information."); + + dataString = certInfo.validityTo; + +CATCH: + return dataString; + +} + +String +X509Certificate::GetSubject(void) const +{ + result r = E_SUCCESS; + _CertFieldInfos certInfo; + Tizen::Base::String dataString; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertInfo(__certHandle, _CERT_FIELD_SUBJECT, &certInfo); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate issuer information."); + + dataString = certInfo.subjectName; + +CATCH: + return dataString; +} + +String +X509Certificate::GetIssuer(void) const +{ + result r = E_SUCCESS; + _CertFieldInfos certInfo; + Tizen::Base::String dataString; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertInfo(__certHandle, _CERT_FIELD_ISSUER, &certInfo); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate issuer information."); + + dataString = certInfo.issuerName; + +CATCH: + return dataString; + +} + +ByteBuffer* +X509Certificate::GetSignatureN(void) const +{ + result r = E_SUCCESS; + byte buffer[_MAX_SIGNATURE_BUFFER_SIZE] = {0, }; + int bufLen = sizeof(buffer); + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertSignature(__certHandle, reinterpret_cast< char* >(buffer), &bufLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] Failed to get certificate signature."); + + std::unique_ptr< ByteBuffer > pSignatureBuffer(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CERT, pSignatureBuffer != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pSignatureBuffer->Construct(bufLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = pSignatureBuffer->SetArray(static_cast< const byte* >(buffer), 0, bufLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pSignatureBuffer->Flip(); + + return pSignatureBuffer.release(); +} + +ByteBuffer* +X509Certificate::GetFingerprintN(void) const +{ + result r = E_SUCCESS; + _CertFieldInfos certInfo; + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertInfo(__certHandle, _CERT_FIELD_FINGERPRINT, &certInfo); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] Failed To get certificate fingerprint information."); + + std::unique_ptr< ByteBuffer > pFingerprint(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CERT, pFingerprint != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pFingerprint->Construct(certInfo.fingerPrintLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = pFingerprint->SetArray(reinterpret_cast< const byte* >(certInfo.fingerPrint), 0, certInfo.fingerPrintLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pFingerprint->Flip(); + + return pFingerprint.release(); +} + +Tizen::Security::IPublicKey* +X509Certificate::GetPublicKeyN(void) const +{ + result r = E_SUCCESS; + ByteBuffer keyBuffer; + byte buffer[_MAX_PUBLIC_KEY_BUFFER_SIZE] = {0, }; + int bufLen = sizeof(buffer); + + ClearLastResult(); + + SysAssertf(__certHandle != 0, "Not yet constructed. Construct() should be called before use."); + + r = _CertService::GetCertPublicKey(__certHandle, reinterpret_cast< char* >(buffer), static_cast< int* >(&bufLen)); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Failed to get certificate public key information."); + + r = keyBuffer.Construct(bufLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = keyBuffer.SetArray(static_cast< const byte* >(buffer), 0, bufLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + keyBuffer.Flip(); + + std::unique_ptr< IPublicKey > pPubKey(dynamic_cast< IPublicKey* >(new (std::nothrow) PublicKey())); + SysTryReturn(NID_SEC_CERT, pPubKey != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pPubKey->SetKey(keyBuffer); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return pPubKey.release(); +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCertX509CertificatePath.cpp b/src/security/cert/FSecCertX509CertificatePath.cpp new file mode 100755 index 0000000..307c9d9 --- /dev/null +++ b/src/security/cert/FSecCertX509CertificatePath.cpp @@ -0,0 +1,256 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertX509CertificatePath.cpp + * @brief This is the implementation file for X509CertificatePath class. + * + * This header file contains the implementation of X509CertificatePath class. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Cert +{ + + +X509CertificatePath::X509CertificatePath(void) + : __certCtx(0) + , __depth(0) + , __trustAnchorIndex(-1) + , __pX509CertificatePathImpl(null) +{ + +} + +X509CertificatePath::~X509CertificatePath(void) +{ + if (__certCtx != 0) + { + _CertService::CloseContext(__certCtx); + } +} + +Tizen::Base::String +X509CertificatePath::GetFormat(void) const +{ + ClearLastResult(); + return L"X509"; +} + +result +X509CertificatePath::AddCertificate(const Tizen::Security::Cert::ICertificate& certificate) +{ + result r = E_SUCCESS; + byte* pCert = null; + int certLen = 0; + + SysTryReturnResult(NID_SEC_CERT, ((certificate.GetFormat()).CompareTo(L"X509")) == 0, E_INVALID_ARG, "Certificate format is not valid."); + + if (__certCtx == 0) + { + r = _CertService::OpenContext(_CERT_CONTEXT_CERT, &__certCtx); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create certificate chain context.", GetErrorMessage(r)); + } + + std::unique_ptr pBuffer(certificate.GetEncodedDataN()); + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Failed to get encoded certificate buffer."); + + pCert = const_cast< byte* >(pBuffer->GetPointer()); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid input certificate passed."); + + certLen = pBuffer->GetRemaining(); + SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Input certificate length is not positive."); + + r = _CertService::AddCertificate(__certCtx, pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate chain context.", GetErrorMessage(r)); + + __depth++; + + return r; +} + +int +X509CertificatePath::GetLength(void) const +{ + ClearLastResult(); + SysTryReturn(NID_SEC_CERT, __certCtx != 0, -1, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + return __depth; + +} + +Tizen::Security::Cert::ICertificate* +X509CertificatePath::GetCertificateN(int nth) const +{ + result r = E_SUCCESS; + CertificateHandle certHandle = 0; + char* pCertBufferValue = null; + ByteBuffer certInput; + int certLen = 0; + + ClearLastResult(); + + SysTryReturn(NID_SEC_CERT, nth >= 0 && nth < __depth, null, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument."); + SysTryReturn(NID_SEC_CERT, __certCtx != 0, null, E_SYSTEM, "[E_SYSTEM] Certificate list is empty, call AddCertificate() function."); + + r = _CertService::GetNthCert(__certCtx, nth, &certHandle); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] Failed to get nth certificate."); + SysTryReturn(NID_SEC_CERT, certHandle != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Certificate not found."); + + r = _CertService::GetCertBufferN(certHandle, pCertBufferValue, &certLen); + std::unique_ptr< char[] > pCertBuffer(pCertBufferValue); + + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer."); + SysTryReturn(NID_SEC_CERT, pCertBuffer != null, null, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer."); + + r = certInput.Construct(certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = certInput.SetArray(reinterpret_cast< byte* >(pCertBuffer.get()), 0, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + certInput.Flip(); + + std::unique_ptr< X509Certificate > pCert(new (std::nothrow) X509Certificate()); + SysTryReturn(NID_SEC_CERT, pCert != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pCert->Construct(certInput); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + return pCert.release(); +} + +Tizen::Security::Cert::ValidationResult +X509CertificatePath::Validate(void) +{ + result r = E_SUCCESS; + int depth = 0; + _CertDomainType domain = _CERT_INVALID_DOMAIN; + Tizen::Security::Cert::ValidationResult validationResult = VALIDATION_ERROR_INVALID_PATH; + ClearLastResult(); + + SysTryReturn(NID_SEC_CERT, __certCtx != 0, validationResult, E_SYSTEM, "[E_SYSTEM] Certificate list is empty, call AddCertificate() function."); + + r = _CertService::VerifyChain(__certCtx, &domain); + switch (r) + { + case E_SUCCESS: + validationResult = VALIDATION_SUCCESS; + SysLog(NID_SEC_CERT, "validation result = success"); + break; + + case E_DATA_NOT_FOUND: + validationResult = VALIDATION_ERROR_NO_ROOT; + SysLog(NID_SEC_CERT, "validation result = no root cert "); + break; + + case E_INVALID_CERTIFICATE: + validationResult = VALIDATION_ERROR_CERT_EXPIRED; + SysLog(NID_SEC_CERT, "validation result = cert expired"); + break; + + case E_CERTIFICATE_VERIFICATION_FAILED: + validationResult = VALIDATION_ERROR_INVALID_SIGNATURE; + SysLog(NID_SEC_CERT, "validation result = invalid signature"); + break; + + default: + validationResult = VALIDATION_ERROR_INVALID_PATH; + SysLog(NID_SEC_CERT, "validation result = invalid path"); + break; + + } + SysTryReturn(NID_SEC_CERT, !IsFailed(r), validationResult, E_SYSTEM, "[E_SYSTEM] Verification of certificate chain failed."); + + r = _CertService::GetChainDepth(__certCtx, &depth); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), VALIDATION_ERROR_INVALID_PATH, E_SYSTEM, "[E_SYSTEM] Failed to get certificate chain depth."); + + __trustAnchorIndex = depth - 1; + SysTryReturn(NID_SEC_CERT, __trustAnchorIndex > 0, VALIDATION_ERROR_INVALID_PATH, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred, trusted anchor not found."); + + return validationResult; + +} + +Tizen::Security::Cert::ValidationResult +X509CertificatePath::Validate(const ICertificate& trustAnchor) +{ + result r = E_SUCCESS; + + ClearLastResult(); + + r = AddCertificate(trustAnchor); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), VALIDATION_ERROR_INVALID_PATH, r, "[%s] Failed to add certificate.", GetErrorMessage(r)); + + return Validate(); +} + +Tizen::Security::Cert::ICertificate* +X509CertificatePath::GetTrustAnchorN(void) const +{ + result r = E_SUCCESS; + CertificateHandle certHandle = 0; + char* pTempCertValue = null; + int certLen = 0; + ByteBuffer certBuffer; + + ClearLastResult(); + + SysTryReturn(NID_SEC_CERT, __certCtx != 0, null, E_SYSTEM, "[E_SYSTEM] Certificate list is empty, call AddCertificate() function."); + SysTryReturn(NID_SEC_CERT, __trustAnchorIndex != -1, null, E_SYSTEM, "[E_SYSTEM] Certificate list is empty, call Validate() function."); + + r = _CertService::GetNthCert(__certCtx, __trustAnchorIndex, &certHandle); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] Failed to get nth certificate."); + SysTryReturn(NID_SEC_CERT, certHandle != null, null, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Certificate not found."); + + r = _CertService::GetCertBufferN(certHandle, pTempCertValue, &certLen); + + std::unique_ptr< char[] > pTempCert(pTempCertValue); + + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer."); + SysTryReturn(NID_SEC_CERT, pTempCert != null, null, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer."); + + r = certBuffer.Construct(certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = certBuffer.SetArray(reinterpret_cast< const byte* >(pTempCert.get()), 0, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + certBuffer.Flip(); + + std::unique_ptr< X509Certificate > pCert(new (std::nothrow) X509Certificate()); + SysTryReturn(NID_SEC_CERT, pCert != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pCert->Construct(certBuffer); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Propagated.", GetErrorMessage(r)); + + return pCert.release(); +} + +} } } // Tizen::Security::Cert diff --git a/src/security/cert/FSecCertX509CertificateSelector.cpp b/src/security/cert/FSecCertX509CertificateSelector.cpp new file mode 100644 index 0000000..df290dc --- /dev/null +++ b/src/security/cert/FSecCertX509CertificateSelector.cpp @@ -0,0 +1,63 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertX509CertificateSelector.cpp + * @brief This is the implementation file for X509CertificateSelector class. + * + * + * This header file contains the implementation of X509CertificateSelector class. + * + */ +#include +#include +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Cert +{ + +X509CertificateSelector::X509CertificateSelector(void) + : __certType(ROOT_CA) + , __pX509CertificateSelectorImpl(null) +{ + +} + +X509CertificateSelector::~X509CertificateSelector(void) +{ + +} + +void +X509CertificateSelector::SetType(CertificateType certificateType) +{ + ClearLastResult(); + + __certType = certificateType; +} + +CertificateType +X509CertificateSelector::GetType() const +{ + ClearLastResult(); + return __certType; +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCertX509CertificateStore.cpp b/src/security/cert/FSecCertX509CertificateStore.cpp new file mode 100644 index 0000000..823e819 --- /dev/null +++ b/src/security/cert/FSecCertX509CertificateStore.cpp @@ -0,0 +1,169 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCertX509CertificateStore.cpp + * @brief This is the implementation file for X509CertificateStore class. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::App; + +namespace Tizen { namespace Security { namespace Cert +{ + +X509CertificateStore::X509CertificateStore(void) + : __pX509CertificateStoreImpl(null) +{ + __pX509CertificateStoreImpl = new (std::nothrow) _X509CertificateStoreImpl(); + SysTryReturnVoidResult(NID_SEC_CERT, __pX509CertificateStoreImpl != null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + +} + +X509CertificateStore::~X509CertificateStore(void) +{ + + delete __pX509CertificateStoreImpl; +} + +result +X509CertificateStore::GetName(String& name) const +{ + result r = E_SUCCESS; + + SysAssertf(__pX509CertificateStoreImpl != null, "Not yet constructed. Reconstructor the object."); + + r = __pX509CertificateStoreImpl->GetName(name); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] An internal system error occurred.", GetErrorMessage(r)); + + return r; +} + +result +X509CertificateStore::SetCertificateSelector(const Tizen::Security::Cert::ICertificateSelector& selector) +{ + result r = E_SUCCESS; + + SysAssertf(__pX509CertificateStoreImpl != null, "Not yet constructed. Reconstructor the object."); + + r = __pX509CertificateStoreImpl->SetCertificateSelector(selector); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] An internal system error occurred.", GetErrorMessage(r)); + + return r; + +} + +result +X509CertificateStore::GetCertificateCount(int& count) const +{ + result r = E_SUCCESS; + + SysAssertf(__pX509CertificateStoreImpl != null, "Not yet constructed. Reconstructor the object."); + + r = __pX509CertificateStoreImpl->GetCertificateCount(count); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] An internal system error occurred.", GetErrorMessage(r)); + + return r; + +} + + +Tizen::Security::Cert::ICertificate* +X509CertificateStore::GetNextCertificateN(void) const +{ + result r = E_SUCCESS; + ICertificate* pCert = null; + ClearLastResult(); + + SysAssertf(__pX509CertificateStoreImpl != null, "Not yet constructed. Reconstructor the object."); + + pCert = __pX509CertificateStoreImpl->GetNextCertificateN(); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pCert != null, null, r, "[%s] An internal system error occurred.", GetErrorMessage(r)); + + return pCert; +} + + +result +X509CertificateStore::Insert(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate) +{ + result r = E_SUCCESS; + + SysAssertf(__pX509CertificateStoreImpl != null, "Not yet constructed. Reconstructor the object."); + + r = __pX509CertificateStoreImpl->Insert(certificateType, certificate); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] An internal system error occurred.", GetErrorMessage(r)); + + return r; +} + + +result +X509CertificateStore::InsertPkcs12(const String& filePath, const String& password) +{ + result r = E_SUCCESS; + + SysAssertf(__pX509CertificateStoreImpl != null, "Not yet constructed. Reconstructor the object."); + + r = __pX509CertificateStoreImpl->InsertPkcs12(filePath, password); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] An internal system error occurred.", GetErrorMessage(r)); + + return r; +} + + +result +X509CertificateStore::Update(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& oldCert, const Tizen::Security::Cert::ICertificate& newCert) +{ + result r = E_SUCCESS; + + SysAssertf(__pX509CertificateStoreImpl != null, "Not yet constructed. Reconstructor the object."); + + r = __pX509CertificateStoreImpl->Update(certificateType, oldCert, newCert); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] An internal system error occurred.", GetErrorMessage(r)); + + return r; + +} + + +result +X509CertificateStore::Remove(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate) +{ + result r = E_SUCCESS; + + SysAssertf(__pX509CertificateStoreImpl != null, "Not yet constructed. Reconstructor the object."); + + r = __pX509CertificateStoreImpl->Remove(certificateType, certificate); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] An internal system error occurred.", GetErrorMessage(r)); + + return r; +} + +} } } // Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_Asn1Parser.cpp b/src/security/cert/FSecCert_Asn1Parser.cpp new file mode 100644 index 0000000..9f25582 --- /dev/null +++ b/src/security/cert/FSecCert_Asn1Parser.cpp @@ -0,0 +1,117 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_Asn1Parser.cpp + * @brief This file contains implementation of base class Asn1 parser. +*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "FSecCert_Asn1Parser.h" +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Security { namespace Cert +{ + + +_Asn1Parser::_Asn1Parser(void) + : _pX509Buff(null) + , _x509BuffSize(0) +{ + +} + +_Asn1Parser::~_Asn1Parser(void) +{ +} + +result +_Asn1Parser::Parse(byte* pAsnBuffer, int bufferSize) +{ + _pX509Buff.reset(null); + _x509BuffSize = 0; + + SysTryReturnResult(NID_SEC_CERT, pAsnBuffer != null, E_INVALID_ARG, "Invalid input arguments, null buffer passed as arugment."); + SysTryReturnResult(NID_SEC_CERT, bufferSize > 0, E_INVALID_ARG, "Invalid input arguments, length must be greater than zero."); + + std::unique_ptr pX509Buff(new (std::nothrow) byte[bufferSize]); + SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memcpy(pX509Buff.get(), pAsnBuffer, bufferSize); + _x509BuffSize = bufferSize; + + _pX509Buff = std::move(pX509Buff); + + return ParseObject(); + +} + +result +_Asn1Parser::Parse(char* pFilePath) +{ + result r = E_SUCCESS; + int readCnt = 0; + long flieSize = 0; + Tizen::Base::String fileName(pFilePath); + Tizen::Io::FileAttributes attr; + Tizen::Io::File file; + + _pX509Buff.reset(null); + _x509BuffSize = 0; + + SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid input argument, file path passed is null."); + + r = Tizen::Io::File::GetAttributes(fileName, attr); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r)); + + flieSize = attr.GetFileSize(); + SysTryReturnResult(NID_SEC_CERT, (flieSize >= 0), E_SYSTEM, "Input file size must be greater zero."); + SysTryReturnResult(NID_SEC_CERT, (flieSize < _MAX_CERTIFICATE_SIZE), E_SYSTEM, "File size exceeds maximum specified length."); + + // Open file + r = file.Construct(fileName, L"r"); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct file.", GetErrorMessage(r)); + + std::unique_ptr pX509Buff(new (std::nothrow) byte[flieSize]); + SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + readCnt = file.Read(pX509Buff.get(), flieSize); + SysTryReturn(NID_SEC_CERT, readCnt == flieSize, GetLastResult(), GetLastResult(), "[%s] Failed to read from a file.", GetErrorMessage(GetLastResult())); + + _x509BuffSize = readCnt; + + _pX509Buff = std::move(pX509Buff); + + return ParseObject(); +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_Asn1Parser.h b/src/security/cert/FSecCert_Asn1Parser.h new file mode 100755 index 0000000..d522928 --- /dev/null +++ b/src/security/cert/FSecCert_Asn1Parser.h @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_Asn1Parser.h + * @brief This header file contains the declarations of base class for Asn1 parsing. + * + * This header file contains the declarations of base class for Asn1 parsing. + */ + +#ifndef _FSEC_CERT_INTERNAL_ASN1_PARSER_H_ +#define _FSEC_CERT_INTERNAL_ASN1_PARSER_H_ + +#include +#include + +namespace Tizen { namespace Security { namespace Cert +{ + +class _Asn1Parser + : public Tizen::Base::Object +{ + +public: + _Asn1Parser(void); + + virtual ~_Asn1Parser(void); + + result Parse(byte* pAsnBuffer, int bufferSize); + + result Parse(char* pFilePath); + +protected: + virtual result ParseObject(void) = 0; + +private: + _Asn1Parser(const _Asn1Parser& rhs); + + _Asn1Parser& operator =(const _Asn1Parser& rhs); + +protected: + std::unique_ptr _pX509Buff; + int _x509BuffSize; + + +}; //_Asn1Parser + +} } } //Tizen::Security::Cert + +#endif //_FSEC_CERT_INTERNAL_ASN1_PARSER_H_ diff --git a/src/security/cert/FSecCert_Base64.cpp b/src/security/cert/FSecCert_Base64.cpp new file mode 100755 index 0000000..ea1b970 --- /dev/null +++ b/src/security/cert/FSecCert_Base64.cpp @@ -0,0 +1,142 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_Base64.cpp + * @brief This file contains implementation of Base64 Encode/Decode functions. +*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_Base64.h" + +using namespace Tizen::Base; +using namespace Tizen::Io; + +namespace Tizen { namespace Security { namespace Cert +{ + +int +_Base64::Decode(char* pIn, int inSize, byte* pOut, int& outSize) +{ + String encodedStr; + + ClearLastResult(); + SysTryReturn(NID_SEC_CERT, pIn != null, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument, null buffer passed."); + SysTryReturn(NID_SEC_CERT, inSize > 0, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument, input size must be greater than zero."); + + SysTryReturn(NID_SEC_CERT, pOut != null, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument, out buffer is passed null."); + + if (pIn[inSize - 1] != '\0' && pIn[inSize] != '\0') + { + std::unique_ptr pTmp(new (std::nothrow) char[inSize + 1]); + SysTryReturn(NID_SEC_CERT, pTmp != null, -1, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memcpy(pTmp.get(), pIn, inSize); + pTmp[inSize] = '\0'; + + encodedStr.Append(pTmp.get()); + } + else + { + encodedStr.Append(pIn); + } + + std::unique_ptr pDecodedBuffer (Tizen::Base::Utility::StringUtil::DecodeBase64StringN(encodedStr)); + SysTryReturn(NID_SEC_CERT, pDecodedBuffer != null, -1, E_SYSTEM, "[E_SYSTEM] Failed to perform base64 decoding."); + + if (outSize > pDecodedBuffer->GetRemaining()) + { + outSize = pDecodedBuffer->GetRemaining(); + } + + memcpy(pOut, pDecodedBuffer->GetPointer(), outSize); + + return outSize; +} + +result +_Base64::Encode(byte* pIn, int inSize, char* pOut, int outSize) +{ + result r = E_SUCCESS; + String encodedStr(_MAX_CERTIFICATE_SIZE); + ByteBuffer buffer; + + SysTryReturnResult(NID_SEC_CERT, pIn != null, E_INVALID_ARG, "Invalid input argument, input buffer is null."); + SysTryReturnResult(NID_SEC_CERT, inSize > 0, E_INVALID_ARG, "Invalid input argument, input size is less than zero."); + SysTryReturnResult(NID_SEC_CERT, pOut != null, E_INVALID_ARG, "Invalid input argument."); + + r = buffer.Construct(inSize); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + r = buffer.SetArray(pIn, 0, inSize); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set bytes for encoding."); + + buffer.Flip(); + + r = Tizen::Base::Utility::StringUtil::EncodeToBase64String(buffer, encodedStr); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to encode base 64 data."); + + std::unique_ptr pEncodedBuffer (Tizen::Base::_StringConverter::CopyToCharArrayN(encodedStr)); + SysTryReturn(NID_SEC_CERT, pEncodedBuffer != null, GetLastResult(), GetLastResult(), "[%s] Failed to convert string to char buffer.", GetErrorMessage(GetLastResult())); + + if (outSize > encodedStr.GetLength()) + { + strcpy(pOut, pEncodedBuffer.get()); + } + else + { + memcpy(pOut, pEncodedBuffer.get(), outSize); + } + + outSize = encodedStr.GetLength(); + + return E_SUCCESS; +} + +int +_Base64::GetEncodedSize(int length) +{ + ClearLastResult(); + SysTryReturn(NID_SEC_CERT, length > 0, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument, length is less than zero."); + + return (length + 2) / 3 * 4; +} + +int +_Base64::GetDecodedSize(int length) +{ + ClearLastResult(); + SysTryReturn(NID_SEC_CERT, length > 0, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument, length is less than zero."); + + return (length + 3) / 4 * 3; +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_Base64.h b/src/security/cert/FSecCert_Base64.h new file mode 100755 index 0000000..624a3fd --- /dev/null +++ b/src/security/cert/FSecCert_Base64.h @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_Base64.h + * @brief This header file contains the declarations of Base64 Encode/Decode. + * + * This header file contains the declarations of Base64 Encode/Decode. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_BASE64_H_ +#define _FSEC_CERT_INTERNAL_CERT_BASE64_H_ + +#include "FSecCert_CertTypes.h" +#include "FBaseByteBuffer.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +const int _MAX_BASE64_CODE_SIZE = 64; +const int _MAX_BASE64_MAP_SIZE = 128; + +class _Base64 +{ + +public: + static int Decode(char* pIn, int inSize, byte* pOut, int& outSize); + + static result Encode(byte* pIn, int inSize, char* pOut, int outSize); + + static int GetEncodedSize(int length); + + static int GetDecodedSize(int length); + +private: + _Base64(void); + + _Base64(const _Base64& rhs); + + ~_Base64(void); + + _Base64& operator =(const _Base64& rhs); + + static byte GetBase64Code(byte c); + +}; //_Base64 + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_BASE64_H_ diff --git a/src/security/cert/FSecCert_CertChain.cpp b/src/security/cert/FSecCert_CertChain.cpp new file mode 100644 index 0000000..a4a8266 --- /dev/null +++ b/src/security/cert/FSecCert_CertChain.cpp @@ -0,0 +1,993 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertChain.cpp + * @brief This file contains implementation of X509 Certificate Chains. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertChain.h" +#include "FSecCert_CertDbManager.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +_CertChain::_CertChain(void) + : __pos(0) + , __pPrivateKey(null) + , __certFormat(_CERT_X509) + , __rootCertType(_CERT_TYPE_NOT_BOUNDED) + , __contextType(_CERT_CONTEXT_CERT) + , __checkValidity(true) +{ + __certChain.Construct(); +} + +_CertChain::~_CertChain(void) +{ + Clear(); +} + +void +_CertChain::Clear(void) +{ + __certChain.RemoveAll(true); +} + +result +_CertChain::AddCertificate(_CertFormat certFormat, char* pFileName) //added pCert format +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_INVALID_ARG, "Input file path is null."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Input cert format is not X509."); + + std::unique_ptr<_X509Certificate> pCert(new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pCert->Parse(pFileName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing of certificate failed.", GetErrorMessage(r)); + + r = __certChain.Add(*pCert.release()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[r] Failed to add certificate in chain.", GetErrorMessage(r)); + __certFormat = certFormat; + + return r; +} + +result +_CertChain::AddCertificate(_CertFormat certFormat, byte* pBuf, int bufSize) //added certFormat +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Invalid input certificate buffer, input buffer must not be null."); + + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Input cert format is not X509."); + + std::unique_ptr<_X509Certificate> pCert(new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pCert->Parse(pBuf, bufSize); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing of certificate failed.", GetErrorMessage(r)); + + r = __certChain.Add(*pCert.release()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[r] Failed to add certificatein chain.", GetErrorMessage(r)); + + __certFormat = certFormat; + + return r; +} + +result +_CertChain::AddCertificate(_X509Certificate* pCert) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid input certificate buffer, input buffer must not be null."); + + r = __certChain.Add(*pCert); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate in chain.", GetErrorMessage(r)); + + __certFormat = _CERT_X509; + + return r; +} + +result +_CertChain::AddPrivateKey(char* pPKeyPath) +{ + SysTryReturnResult(NID_SEC_CERT, pPKeyPath != null, E_INVALID_ARG, "Input key buffer is null."); + + __pPrivateKey.reset(null); + + __pPrivateKey = std::unique_ptr<_CertPrivateKeyInfo> (new (std::nothrow) _CertPrivateKeyInfo(pPKeyPath)); + SysTryReturnResult(NID_SEC_CERT, __pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + return E_SUCCESS; +} + +result +_CertChain::AddPrivateKey(byte* pBuf, int bufSize) +{ + SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Input parameters are not correct."); + SysTryReturnResult(NID_SEC_CERT, bufSize > 0, E_INVALID_ARG, "Input buffer size must be greater than zero."); + + __pPrivateKey.reset(null); + + __pPrivateKey = std::unique_ptr<_CertPrivateKeyInfo>(new (std::nothrow) _CertPrivateKeyInfo(pBuf, bufSize)); + SysTryReturnResult(NID_SEC_CERT, __pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + return E_SUCCESS; +} + +_CertPrivateKeyInfo* +_CertChain::GetPrivateKey(void) +{ + return __pPrivateKey.get(); +} + +result +_CertChain::MoveNext(void) +{ + SysTryReturnResult(NID_SEC_CERT, __certChain.GetCount() > 0, E_SYSTEM, "No certificate is present in chain, failed to move to tail of certificate chain."); + SysTryReturnResult(NID_SEC_CERT, __pos < (__certChain.GetCount() - 1), E_SYSTEM, "Position is at last certificate, failed to move to next certificate in chain."); + + __pos++; + return E_SUCCESS; +} + +result +_CertChain::MovePrev(void) +{ + SysTryReturnResult(NID_SEC_CERT, __pos > 0, E_SYSTEM, "Position is already at zero, failed to move to previous certificate in chain."); + __pos--; + return E_SUCCESS; +} + +result +_CertChain::MoveHead(void) +{ + __pos = 0; + return E_SUCCESS; +} + +result +_CertChain::MoveTail(void) +{ + SysTryReturnResult(NID_SEC_CERT, __certChain.GetCount() > 0, E_SYSTEM, "No certificate is present in chain, failed to move to tail of certificate chain."); + __pos = __certChain.GetCount() - 1; + + return E_SUCCESS; +} + +_CertDomainType +_CertChain::GetCertTypeByDomain(void) +{ + _CertDomainType r; + + switch (__rootCertType) + { + case _CERT_TYPE_SIM_ROOT_DOMAIN1: + //fall through + case _CERT_TYPE_ROOT_DOMAIN1: + //fall through + case _CERT_TYPE_DEV_ROOT_DOMAIN1: + r = _CERT_DOMAIN1_TRUSTED; + break; + + case _CERT_TYPE_ROOT_DOMAIN2: + //fall through + case _CERT_TYPE_DEV_ROOT_DOMAIN2: + r = _CERT_DOMAIN2_TRUSTED; + break; + + case _CERT_TYPE_ROOT_DOMAIN3: + //fall through + case _CERT_TYPE_SIM_ROOT_DOMAIN3: + //fall through + case _CERT_TYPE_DEV_ROOT_DOMAIN3: + r = _CERT_DOMAIN3_TRUSTED; + break; + + case _CERT_TYPE_WRT: + r = _CERT_WRT_TRUSTED; + break; + + default: + r = _CERT_INVALID_DOMAIN; + break; + } + + return r; +} + +_X509Certificate* +_CertChain::GetCurrentCertificate(void) +{ + SysTryReturn(NID_SEC_CERT, __certChain.GetCount() > 0, null, E_SYSTEM, "[E_SYSTEM] There is no certifcate present in chain."); + SysTryReturn(NID_SEC_CERT, __pos >= 0, null, E_SYSTEM, "[E_SYSTEM] Failed to get certificate object from chain."); + return reinterpret_cast< _X509Certificate* >(__certChain.GetAt(__pos)); +} + + +result +_CertChain::Verify(void) +{ + result r = E_SUCCESS; + const unsigned char* pCertContent = null; + int certSize = 0; + int certCount = __certChain.GetCount(); + STACK_OF(X509)* pTrustedChain = null; + STACK_OF(X509)* pInterimChain = null; + X509_STORE_CTX* pStoreCtx = NULL; + byte* pCertBuffer = null; + _X509Certificate* pCert = null; + X509** ppInterimCerts = null; + X509* pX509UserCert = null; + + SysTryReturnResult(NID_SEC_CERT, certCount > 0, E_SYSTEM, "No certificates are present in certificate chain."); + SysTryReturnResult(NID_SEC_CERT, __certFormat == _CERT_X509, E_SYSTEM, "Certificate chain is not of type X509."); + + pCert = reinterpret_cast< _X509Certificate* >(__certChain.GetAt(0)); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_SYSTEM, "Failed to get first certificate in chain."); + + certCount--; //user certificate is added. + + if (certCount == 0) //only root cert to verify + { + SysTryReturnResult(NID_SEC_CERT, pCert->IsSelfSigned(), E_DATA_NOT_FOUND, "Failed to get root certificate in chain."); + return pCert->VerifySignature(null, 0); + } + + pCert->GetCertBuffer(pCertBuffer, certSize); + SysTryReturnResult(NID_SEC_CERT, pCertBuffer != null, E_SYSTEM, "Failed to get encoded buffer of first certificate."); + + pCertContent = const_cast< const unsigned char* >(pCertBuffer); + + d2i_X509(&pX509UserCert, &pCertContent, certSize); + SysTryReturnResult(NID_SEC_CERT, pX509UserCert != null, E_SYSTEM, "Failed to parse user certificate."); + + pTrustedChain = sk_X509_new_null(); + SysTryCatch(NID_SEC_CERT, pTrustedChain != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]Failed to allocate trusted root ca certificate chain."); + + pInterimChain = sk_X509_new_null(); + SysTryCatch(NID_SEC_CERT, pInterimChain != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]Failed to allocate intermediate ca certificate chain."); + + ppInterimCerts = (X509**) new X509*[certCount]; + memset(ppInterimCerts, 0, (sizeof(X509*) * certCount)); + + for (int i = 0; i < certCount; i++) + { + certSize = 0; + pCertContent = null; + pCertBuffer = null; + + pCert = reinterpret_cast< _X509Certificate* >(__certChain.GetAt(i + 1)); + SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate at index (%d).", i + 1); + + pCert->GetCertBuffer(pCertBuffer, certSize); + SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get buffer of certificate at index (%d).", i + 1); + + pCertContent = const_cast< const unsigned char* >(pCertBuffer); + + d2i_X509(&ppInterimCerts[i], &pCertContent, certSize); + SysTryCatch(NID_SEC_CERT, ppInterimCerts[i] != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to parse certificate at index (%d).", i + 1); + + if (pCert->IsSelfSigned()) + { + /* verify */ + // insert root certificate into trusted chain + if (!(sk_X509_push(pTrustedChain, ppInterimCerts[i]))) + { + SysLog(NID_SEC_CERT, "Fail to push root ca certificate into openssl stack."); + r = E_SYSTEM; + goto CATCH; + } + } + else + { + if (!(sk_X509_push(pInterimChain, ppInterimCerts[i]))) + { + SysLog(NID_SEC_CERT, "Fail to push intermediate ca certificate into openssl stack."); + r = E_SYSTEM; + goto CATCH; + } + + } + } + + SysTryCatch(NID_SEC_CERT, sk_X509_num(pTrustedChain) > 0, r = E_DATA_NOT_FOUND, E_DATA_NOT_FOUND, "[E_DATA_NOT_FOUND] Failed to get root certificate in chain."); + + // initialize store and store context + pStoreCtx = X509_STORE_CTX_new(); + + // construct store context + if (!X509_STORE_CTX_init(pStoreCtx, 0, pX509UserCert, pInterimChain)) + { + SysLog(NID_SEC_CERT, "Fail to initialize X509 store context."); + r = E_SYSTEM; + goto CATCH; + } + + X509_STORE_CTX_trusted_stack(pStoreCtx, pTrustedChain); + + // verify + if (X509_verify_cert(pStoreCtx) != 1) + { + SysLog(NID_SEC_CERT, "Fail to verify certificate chain."); + switch(X509_STORE_CTX_get_error(pStoreCtx)) + { + case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: + r = E_DATA_NOT_FOUND; + break; + case X509_V_ERR_CERT_HAS_EXPIRED: + //fall though + case X509_V_ERR_CERT_NOT_YET_VALID: + r = E_INVALID_CERTIFICATE; + break; + case X509_V_ERR_CERT_SIGNATURE_FAILURE: + r = E_CERTIFICATE_VERIFICATION_FAILED; + break; + default: + r = E_SYSTEM; + break; + } + SysLog(NID_SEC_CERT, "error number = %d", X509_STORE_CTX_get_error(pStoreCtx)); + goto CATCH; + + } + +CATCH: + + if (ppInterimCerts != null) + { + for(int i = 0; i < certCount; i++) + { + if (ppInterimCerts[i] != null) + { + X509_free(ppInterimCerts[i]); + } + } + + delete[] ppInterimCerts; + } + + if (pX509UserCert != null) + { + X509_free(pX509UserCert); + } + + if (pStoreCtx != null) + { + X509_STORE_CTX_free(pStoreCtx); + } + + if (pTrustedChain != null) + { + sk_X509_free(pTrustedChain); + } + + if (pInterimChain != null) + { + sk_X509_free(pInterimChain); + } + return r; +} + + +result +_CertChain::VerifyUsingOpenSsl(void) +{ + result r = E_SUCCESS; + int keyLen = 0; + int count = 0; + + r = MoveTail(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "No certificate is present in certificate chain, failed to validate certificate chain."); + + if (__certFormat == _CERT_X509) + { + _X509Certificate* pCert = null; + _X509Certificate* pPrevCert = null; + _X509TbsCert* pTbsCert = null; + _X509TbsCert* pPrevTbsCert = null; + + do + { + pPrevCert = GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pPrevCert != null, E_SYSTEM, "Failed to get root certificate from chain, broken certificate chain."); + + if (pPrevCert->IsSelfSigned()) + { + // rootCA self verify + if (__checkValidity) + { + pPrevTbsCert = pPrevCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pPrevTbsCert != null, E_SYSTEM, "Failed to get root certificate to be signed instance."); + + r = pPrevTbsCert->GetValidity(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CERTIFICATE, "Root certificate validation failed (subject name: %s).", pPrevTbsCert->GetSubjectName()); + } + + r = pPrevCert->VerifySignature(null, 0); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_CERTIFICATE_VERIFICATION_FAILED, "Root certificate signature verification failed (subject name: %s).", pPrevTbsCert->GetSubjectName()); + } + else + { + if (MoveNext() == E_SUCCESS) + { + pPrevCert = GetCurrentCertificate(); + } + count++; + break; + } + } + while (MovePrev() == E_SUCCESS); + + while (MovePrev() == E_SUCCESS) + { + byte* pKey = null; + count++; + + pCert = GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain."); + + pPrevTbsCert = pPrevCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pPrevTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + if (__checkValidity) + { + r = pPrevTbsCert->GetValidity(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CERTIFICATE, "Certificate validation failed (subject name: %s).", pPrevTbsCert->GetSubjectName()); + } + + + SysTryReturnResult(NID_SEC_CERT, pCert->IsIssuer(pPrevCert), E_SYSTEM, "Certificate is not in sorted order or parent certificate is missing in chain, certificate chain is broken (subject name: %s).", pPrevTbsCert->GetSubjectName()); + + r = pPrevTbsCert->GetPublicKeyInfoN(keyLen, &pKey); + SysTryReturnResult(NID_SEC_CERT, pKey != null, E_SYSTEM, "Failed to public key from certificate (subject name: %s).", pPrevTbsCert->GetSubjectName()); + + std::unique_ptr pKeyAuto(pKey); + + r = pCert->VerifySignature(pKey, keyLen); + + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_CERTIFICATE_VERIFICATION_FAILED, "Certificate signature verification failed (subject name: %s).", pTbsCert->GetSubjectName()); + + pPrevCert = pCert; + } + } + + return E_SUCCESS; +} + +result +_CertChain::VerifyCertChainWithDb(void) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + byte* pCert = null; + int certLen = 0; + _CaCertType certType = _CERT_TYPE_NOT_BOUNDED; + + r = MoveTail(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "No certificate is present in certificate chain, failed to validate certificate chain."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + if (__certFormat == _CERT_X509) + { + _X509Certificate* pLastCert = null; + _X509TbsCert* pTbsCert = null; + pLastCert = GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pLastCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + if (pLastCert->IsSelfSigned()) + { + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + pTbsCert = pLastCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get root certificate to be signed instance."); + + if (GetContextType() == _CERT_CONTEXT_SSL) + { + certType = _CERT_TYPE_ROOT_CA; + __checkValidity = true; + + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_ROOT_CA_BY_USER; + __checkValidity = true; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetSubjectName()); + } + } + else if (GetContextType() == _CERT_CONTEXT_MIDP || GetContextType() == _CERT_CONTEXT_DOMAIN || GetContextType() == _CERT_CONTEXT_DOMAIN_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_DOMAIN_NO_VALIDITY) + { + __checkValidity = false; + } + else + { + __checkValidity = true; + } + + certType = _CERT_TYPE_ROOT_DOMAIN1; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_ROOT_DOMAIN2; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_ROOT_DOMAIN3; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_DEV_ROOT_DOMAIN1; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_DEV_ROOT_DOMAIN3; + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetSubjectName()); + } + } + } + } + } + else if (GetContextType() == _CERT_CONTEXT_CERT || GetContextType() == _CERT_CONTEXT_CERT_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_CERT) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_CERT_NO_VALIDITY) + { + __checkValidity = false; + } + + certType = _CERT_TYPE_TRUSTED_CA; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_USER || GetContextType() == _CERT_CONTEXT_OSP_USER_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_USER) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_USER_NO_VALIDITY) + { + __checkValidity = false; + } + + certType = _CERT_TYPE_ROOT_CA_BY_USER; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL1 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL1_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL1) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL1_NO_VALIDITY) + { + __checkValidity = false; + } + + certType = _CERT_TYPE_OSP_CRITICAL1; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL2 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL2_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL2) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL2_NO_VALIDITY) + { + __checkValidity = false; + } + + certType = _CERT_TYPE_OSP_CRITICAL2; + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL3 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL3_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL3) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL3_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_CRITICAL3; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL4 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL4_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL4) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL4_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_CRITICAL4; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL5 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL5_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL5) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL5_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_CRITICAL5; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_PRELOAD_APP || GetContextType() == _CERT_CONTEXT_OSP_PRELOAD_APP_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_PRELOAD_APP) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_PRELOAD_APP_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_PRELOAD_APP; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_WRT) + { + __checkValidity = true; + certType = _CERT_TYPE_WRT; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_TK) + { + certType = _CERT_TYPE_ROOT_DOMAIN2; + __checkValidity = true; + if (!strcmp(_CERT_TK_ISSUER_NAME, reinterpret_cast< const char* >(pTbsCert->GetIssuerName()))) + { + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else + { + //if the issuerName of this certificate is not _CERT_TK_ISSUER_NAME then we should return some error + SysTryReturnResult(NID_SEC_CERT, false, E_INACCESSIBLE_PATH, "Failed to access specified Path."); + } + } + else + { + SysTryReturnResult(NID_SEC_CERT, false, E_SYSTEM, "Invalid context type."); + } + if (!IsFailed(r)) + { + //Set the format of root certificate + __rootCertType = certType; + } + + delete[] pCert; + return Verify(); + } + else + { + //Otherwise extract root certificate from Db and add in tail and then verify. + pTbsCert = pLastCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get to be signed object from cerificate."); + + + //If the conetxt type is SSL then root certiifcate should be searched in DefaultROOCACert directory. + //It should not search in any other directory + //Similarily, if context type is MIDP then root certificate should be searched in Domain1, Domain2 & Domain3 directory. + //If not found report error. + if (GetContextType() == _CERT_CONTEXT_SSL) + { + certType = _CERT_TYPE_ROOT_CA; + __checkValidity = true; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_ROOT_CA_BY_USER; + __checkValidity = true; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + } + else if (GetContextType() == _CERT_CONTEXT_MIDP || GetContextType() == _CERT_CONTEXT_DOMAIN || GetContextType() == _CERT_CONTEXT_DOMAIN_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_DOMAIN_NO_VALIDITY) + { + __checkValidity = false; + } + else + { + __checkValidity = true; + } + certType = _CERT_TYPE_ROOT_DOMAIN1; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_ROOT_DOMAIN2; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_ROOT_DOMAIN3; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_DEV_ROOT_DOMAIN1; + if (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen) != E_SUCCESS) + { + certType = _CERT_TYPE_DEV_ROOT_DOMAIN3; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + } + } + } + } + else if (GetContextType() == _CERT_CONTEXT_CERT || GetContextType() == _CERT_CONTEXT_CERT_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_CERT) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_CERT_NO_VALIDITY) + { + __checkValidity = false; + } + + r = pCertDb->FindIssuerCertificateAndTypeN(_CERT_X509, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen, certType); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_USER || GetContextType() == _CERT_CONTEXT_OSP_USER_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_USER) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_USER_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_ROOT_CA_BY_USER; + + r = (pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen)); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL1 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL1_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL1) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL1_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_CRITICAL1; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL2 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL2_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL2) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL2_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_CRITICAL2; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL3 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL3_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL3) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL3_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_CRITICAL3; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL4 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL4_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL4) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL4_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_CRITICAL4; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL5 || GetContextType() == _CERT_CONTEXT_OSP_CRITICAL5_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL5) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_CRITICAL5_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_CRITICAL5; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_OSP_PRELOAD_APP || GetContextType() == _CERT_CONTEXT_OSP_PRELOAD_APP_NO_VALIDITY) + { + if (GetContextType() == _CERT_CONTEXT_OSP_PRELOAD_APP) + { + __checkValidity = true; + } + else if (GetContextType() == _CERT_CONTEXT_OSP_PRELOAD_APP_NO_VALIDITY) + { + __checkValidity = false; + } + certType = _CERT_TYPE_OSP_PRELOAD_APP; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_WRT) + { + __checkValidity = true; + certType = _CERT_TYPE_WRT; + + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else if (GetContextType() == _CERT_CONTEXT_TK) + { + certType = _CERT_TYPE_ROOT_DOMAIN2; + __checkValidity = true; + + if (!strcmp(_CERT_TK_ISSUER_NAME, reinterpret_cast< const char* >(pTbsCert->GetIssuerName()))) + { + r = pCertDb->FindIssuerCertificateByTypeN(_CERT_X509, certType, reinterpret_cast< char* >(pTbsCert->GetIssuerName()), &pCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to find certificate in database (subject name: %s).", GetErrorMessage(r), pTbsCert->GetIssuerName()); + } + else + { + SysTryReturnResult(NID_SEC_CERT, false, E_INACCESSIBLE_PATH, "Failed to access specified certificate path."); + } + } + else + { + SysTryReturnResult(NID_SEC_CERT, false, E_SYSTEM, "Invalid context type."); + } + + if (pCert != null) + { + std::unique_ptr pCertAuto(pCert); + + //Add newly found root certificate in chain for verification. + r = AddCertificate(__certFormat, reinterpret_cast< byte* >(pCert), certLen); + + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to add parent certificate in chain."); + //Verify certificate chain and return result to application + r = Verify(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to verify certificate chain.", GetErrorMessage(r)); + } + else + { + SysTryReturnResult(NID_SEC_CERT, false, E_DATA_NOT_FOUND, "Parent certificate not found in certificate database."); + } + + if (!IsFailed(r)) + { + //Set the format of root certificate + __rootCertType = certType; + } + } + } + + return r; +} + +int +_CertChain::GetCount(void) +{ + return __certChain.GetCount(); +} + +void +_CertChain::SetContextType(_CertContextType type) +{ + __contextType = type; +} + +_CertContextType +_CertChain::GetContextType(void) +{ + return __contextType; +} + +_CertFormat +_CertChain::GetCertFormat(void) +{ + return __certFormat; +} + +void +_CertChain::RemoveHead(bool freeFlag) +{ + __certChain.RemoveAt(0, freeFlag); +} + +void +_CertChain::RemoveTail(bool freeFlag) +{ + if (__certChain.GetCount() > 0) + { + __certChain.RemoveAt(__certChain.GetCount() - 1, freeFlag); + } +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertChain.h b/src/security/cert/FSecCert_CertChain.h new file mode 100755 index 0000000..7824952 --- /dev/null +++ b/src/security/cert/FSecCert_CertChain.h @@ -0,0 +1,108 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertChain.h + * @brief This header file contains the declarations of Certificate Chain and its operations. + * + * This header file contains the declarations of Certificate Chain and its operations. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_CHAIN_H_ +#define _FSEC_CERT_INTERNAL_CERT_CHAIN_H_ + +#include "unique_ptr.h" +#include "FSecCert_Certificate.h" +#include "FSecCert_CertPrivateKeyInfo.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertChain +{ +public: + _CertChain(void); + + virtual ~_CertChain(void); + + void Clear(void); + + result AddCertificate(_CertFormat certFormat, char* pFileName); + + result AddCertificate(_CertFormat certFormat, byte* pBuf, int bufSize); + + result AddCertificate(_X509Certificate* pCert); + + result AddPrivateKey(char* pPKeyPath); + + result AddPrivateKey(byte* pBuf, int bufSize); + + result MoveNext(void); + + result MovePrev(void); + + result MoveHead(void); + + result MoveTail(void); + + void RemoveHead(bool freeFlag); + + void RemoveTail(bool freeFlag); + + void SetContextType(_CertContextType type); + + result Verify(void); + + result VerifyUsingOpenSsl(void); + + result VerifyCertChainWithDb(void); + + _CertPrivateKeyInfo* GetPrivateKey(void); + + _X509Certificate* GetCurrentCertificate(void); + + _CertFormat GetCertFormat(void); + + _CertDomainType GetCertTypeByDomain(void); + + _CertContextType GetContextType(void); + + int GetCount(void); + +private: + _CertChain(const _CertChain& rhs); + + _CertChain& operator =(const _CertChain& rhs); + + static void DelFunc4CmCertificate(void* pValue); + + int CheckBitInBitString(_CertExtensionInfo* pExtension, int bitNo); + +private: + int __pos; + std::unique_ptr<_CertPrivateKeyInfo> __pPrivateKey; + _CertFormat __certFormat; + _CaCertType __rootCertType; + _CertContextType __contextType; + bool __checkValidity; + Tizen::Base::Collection::ArrayList __certChain; + +}; //_CertChain + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_CHAIN_H_ diff --git a/src/security/cert/FSecCert_CertDbManager.cpp b/src/security/cert/FSecCert_CertDbManager.cpp new file mode 100755 index 0000000..7087aac --- /dev/null +++ b/src/security/cert/FSecCert_CertDbManager.cpp @@ -0,0 +1,2251 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertDbManager.cpp + * @brief This file contains implementation of X509 Certificate Db Manager APIs. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertDbStore.h" +#include "FSecCert_CertFileStore.h" +#include "FSecCert_CertDbManager.h" +#include "FSecCert_Base64.h" +#include "FSecCert_CertService.h" +#include "FSecCert_CertManager.h" + +using namespace Tizen::Base; +using namespace Tizen::Io; + +namespace Tizen { namespace Security { namespace Cert +{ +_CertDbManager* _CertDbManager::__pCertDb = null; + +_CertDbManager::_CertDbManager(void) +{ +} + +_CertDbManager::~_CertDbManager(void) +{ +} + +void +_CertDbManager::Construct(void) +{ + static _CertDbManager certDb; + __pCertDb = &certDb; +} + + +_CertDbManager* +_CertDbManager::GetInstance(void) +{ + static pthread_once_t once_block = PTHREAD_ONCE_INIT; + if (__pCertDb == null) + { + pthread_once(&once_block, Construct); + } + + return __pCertDb; +} + +result +_CertDbManager::CreateCertificateTables(void) +{ + result r = E_SUCCESS; + + r = __caCertDbStore.CreateCertificateTables(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate tables in database."); + + return E_SUCCESS; +} + +bool +_CertDbManager::IsCertificateTablesCreated(void) +{ + result r = E_SUCCESS; + + r = __caCertDbStore.IsRootCaCertTableCreated(); + if( r != E_SUCCESS ) + { + SetLastResult(E_SYSTEM); + return false; + } + + r = __userCertDbStore.IsUserCertTableCreated(); + if( r != E_SUCCESS ) + { + SetLastResult(E_SYSTEM); + return false; + } + + return true; +} + +result +_CertDbManager::ResetCertificateTables(void) +{ + result r = E_SUCCESS; + + r = __caCertDbStore.DropCertificateTables(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to drop certificate tables in database."); + + r = __caCertDbStore.CreateCertificateTables(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to create certificate tables in database."); + + return E_SUCCESS; +} + +result +_CertDbManager::RemoveCertificateTables(void) +{ + result r = E_SUCCESS; + r = __caCertDbStore.DropCertificateTables(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database."); + return E_SUCCESS; +} + +result +_CertDbManager::RemoveCaCertificateByType(_CaCertType certType) +{ + result r = E_SUCCESS; + char condition[_MAX_TYPE_CONST_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + sprintf(condition, "certType = %d and installed = '%s'", certType, installed); + + r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition)); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database."); + + return E_SUCCESS; +} + +result +_CertDbManager::RemoveUserCertificateByCertId(int certId) +{ + result r = E_SUCCESS; + _CertFileStore fileStore; + String certFileName; + String keyName; + + r = __userCertDbStore.RemoveCertificateById(certId); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete user certificate in database."); + + //Delete File + + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, certFileName); + Tizen::Io::File::Remove(certFileName); + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyName); + Tizen::Io::File::Remove(keyName); + + return E_SUCCESS; +} + +result +_CertDbManager::RemoveUserCaCertificateByCertId(int certId) +{ + result r = E_SUCCESS; + char condition[_MAX_TYPE_CONST_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + sprintf(condition, "certId = %d and certType = %d and installed = '%s'", certId, _CERT_TYPE_ROOT_CA_BY_USER, installed); + r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition)); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database."); + + return E_SUCCESS; +} + +result +_CertDbManager::InsertDefaultCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen) +{ + return InsertCaCertificateFromBuffer(certType, certFormat, pCertBuf, certLen, false); +} + +result +_CertDbManager::InsertCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen, bool checkValidity) +{ + result r = E_SUCCESS; + String tempFileName; + CaCertRecord certRecord = {0, }; + _CertFileStore fileStore; + _CertFormat certBufFormat = _CERT_UNKNOWN; + _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN; + int lenSubjectName = 0; + int lenIssuerName = 0; + int lenSerialNo = 0; + int certId = 0; + int derCertBufferLength = 0; + char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + byte* pDerCert = null; + byte* pSerial = null; + _X509TbsCert* pTbsCert = null; + + r = __caCertDbStore.IsRootCaCertTableCreated(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database."); + + std::unique_ptr <_X509Certificate> pCert (new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + certBufFormat = _CertManager::GetEncodedCertBuffer(pCertBuf, certLen, &pDerCert, &derCertBufferLength, &encodingType); + std::unique_ptr pDerCertBuffer(pDerCert); + pDerCert = null; + SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_CONDITION, "Input certificate buffer."); + SysTryReturnResult(NID_SEC_CERT, certBufFormat == _CERT_X509, E_INVALID_CONDITION, "Unsupported certificate format."); + SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_CONDITION, "Invalid certificate length."); + + r = pCert->Parse(pDerCertBuffer.get(), derCertBufferLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed."); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null,E_SYSTEM, "Failed to get certificate to be signed instance."); + + lenSubjectName = strlen(reinterpret_cast< const char* >(pTbsCert->GetSubjectName())); + lenIssuerName = strlen(reinterpret_cast< const char* >(pTbsCert->GetIssuerName())); + + SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE,E_SYSTEM, "Subject name is more then maximum specified length."); + SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length."); + + strcpy(subjectName, reinterpret_cast< const char* >(pTbsCert->GetSubjectName())); + strcpy(issuerName, reinterpret_cast< const char* >(pTbsCert->GetIssuerName())); + + pTbsCert->GetSerialNumber(pSerial, reinterpret_cast< int& >(lenSerialNo)); + if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE)) + { + memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE); + lenSerialNo = 1; + } + else + { + memcpy(serialName, pSerial, lenSerialNo); + } + + if (checkValidity) + { + if (pCert->IsSelfSigned()) + { + r = pCert->VerifySignature(null, 0); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "Invalid data."); + } +#ifdef _CERT_VERIFY_AND_INSTALL_CERTIFICATE + //Open this code - if u want to support installation of Intermediate CA Certificate with verification using this API.(ideally it should check if installing intermediate CA) (09082011) + else if (pCert->IsCaCertificate()) + { + std::unique_ptr <_CertChain> pCertChain (new (std::nothrow) _CertChain()); + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pCertChain->AddCertificate(certFormat, pDerCertBuffer.get(), derCertBufferLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "AddCertificate failed."); + + r = pCertChain->MoveHead(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "MoveHead failed."); + + + // It support only RSA, For ECC Certificate if you want to omit this, block this call or check as per algo id + //(there are ECC certificate installation which we support for china model. hence these comments) + r = pCertChain->VerifyCertChainWithDb(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to verify certificate chain."); + } +#endif + +#ifdef _CERT_INSTALL_ONLY_CA_CERTIFICATE + //Open this code - if u want to support only CA Certificate installation using this API.(ideally it should check) + else + { + return E_UNSUPPORTED_OPERATION; + } +#endif + + } + + r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(subjectName), lenSubjectName); + if(r == E_SUCCESS) + { + return E_FILE_ALREADY_EXIST; + } + //Get the last installed certificate id from db table + __caCertDbStore.GetCurrentCertId(certId); + //Calculate the new (std::nothrow) certificate id for installation + certId = certId + 1; + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName); + + memset(&certRecord, 0, sizeof(certRecord)); + certRecord.certType = static_cast< int >(certType); + certRecord.certFormat = static_cast< int >(certFormat); + + std::unique_ptr pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName)); + SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get file attributes."); + + strcpy(certRecord.fileName, pFileName.get()); + + certRecord.subjectNameLen = lenSubjectName; + memcpy(certRecord.subjectName, subjectName, lenSubjectName); + certRecord.issuerNameLen = lenIssuerName; + memcpy(certRecord.issuerName, issuerName, lenIssuerName); + certRecord.parentCa = certId; + strcpy(certRecord.installed, installed); + memcpy(certRecord.serialNo, serialName, lenSerialNo); + certRecord.serialNoLen = lenSerialNo; + + r = __caCertDbStore.InsertCaCertificate(&certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Certificate record insertion failed.", GetErrorMessage(r)); + + fileStore.SetFilePath(tempFileName); + + r = fileStore.WriteToFile(pDerCertBuffer.get(), derCertBufferLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path inaccessible."); + + return r; + +} + +result +_CertDbManager::UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen) +{ + result r = E_SUCCESS; + String tempFileName; + CaCertRecord certRecord = {0, }; + CaCertRecord certRecord1 = {0, }; + _CertFileStore fileStore; + _X509TbsCert* pTbsCert = null; + _X509TbsCert* pNewTbsCert = null; + int lenSubjectName = 0; + int lenNewSubjectName = 0; + int lenIssuerName = 0; + int lenNewIssuerName = 0; + int lenNewSerialNo = 0; + int certId = 0; + int subjNameB64len = 0; + char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char newSubjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char newIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char newSerialName[_MAX_SERIAL_NUMBER_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, }; + byte* pNewSerial = null; + + r = __caCertDbStore.IsRootCaCertTableCreated(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database."); + + std::unique_ptr<_X509Certificate> pCert (new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pCert->Parse(pCurCertBuf, curCertLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Parse failed."); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())); + lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())); + + SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length."); + SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length."); + + r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), lenSubjectName); + if (!IsFailed(r)) //checkit + { + subjNameB64len = _Base64::GetEncodedSize(lenSubjectName); + SysTryReturnResult(NID_SEC_CERT, subjNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + + r = _Base64::Encode(pTbsCert->GetSubjectName(), lenSubjectName, subjectNameBase64, subjNameB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed); + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + certId = certRecord.parentCa; + + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName); + fileStore.SetFilePath(tempFileName); + + if (certFormat == _CERT_X509) + { + std::unique_ptr <_X509Certificate> pNewCert(new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pNewCert->Parse(pNewCertBuf, newCertLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed."); + + pNewTbsCert = pNewCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pNewTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + strcpy(newSubjectName, reinterpret_cast< const char* >(pNewTbsCert->GetSubjectName())); + strcpy(newIssuerName, reinterpret_cast< const char* >((pNewTbsCert->GetIssuerName()))); + + lenNewSubjectName = strlen(newSubjectName); + lenNewIssuerName = strlen(newIssuerName); + + pNewTbsCert->GetSerialNumber(pNewSerial, reinterpret_cast< int& >(lenNewSerialNo)); + if ((lenNewSerialNo <= 0) || (lenNewSerialNo > _MAX_SERIAL_NUMBER_SIZE)) + { + memset(pNewSerial, 0, _MAX_SERIAL_NUMBER_SIZE); + lenNewSerialNo = 1; + + } + else + { + memcpy(newSerialName, pNewSerial, lenNewSerialNo); + } + + SysTryReturnResult(NID_SEC_CERT, lenNewSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length."); + SysTryReturnResult(NID_SEC_CERT, lenNewIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length."); + } + certRecord1.certType = static_cast< int >(certType); + certRecord1.certFormat = static_cast< int >(certFormat); + + std::unique_ptr pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName)); + SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_OPERATION_FAILED, "Failed to get file name."); + + strcpy(certRecord1.fileName, pFileName.get()); + + certRecord1.subjectNameLen = lenNewSubjectName; + memcpy(certRecord1.subjectName, newSubjectName, lenNewSubjectName); + certRecord1.issuerNameLen = lenIssuerName; + memcpy(certRecord1.issuerName, newIssuerName, lenNewIssuerName); + certRecord1.parentCa = certId; + strcpy(certRecord1.installed, certRecord.installed); + memcpy(certRecord1.serialNo, newSerialName, lenNewSerialNo); + certRecord1.serialNoLen = lenNewSerialNo; + + r = __caCertDbStore.UpdateCaCertificate(&certRecord, &certRecord1); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to update ca certificate."); + + fileStore.DeleteFile(); + + r = fileStore.WriteToFile(pNewCertBuf, newCertLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path does not exist."); + //No need to update record as only file data changed. + return E_SUCCESS; + } + else + { + return E_FILE_ALREADY_EXIST; + } + + return r; +} + +result +_CertDbManager::RemoveCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen) +{ + result r = E_SUCCESS; + _X509TbsCert* pTbsCert = null; + String fileName; + _CertFileStore fileStore; + int certId = 0; + + //Check certType missing + + r = __caCertDbStore.IsRootCaCertTableCreated(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "No root certificate tables are create in databased."); + + std::unique_ptr <_X509Certificate> pCert (new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pCert->Parse(pCertBuf, certLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Parsing failed."); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()))); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "Certificate not found in db."); + + r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())), + pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + certId, certType); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate id.", GetErrorMessage(r)); + + + r = __caCertDbStore.RemoveCertificateById(certId); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate with certificate id (%d).", certId); + + //Delete File + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName); + Tizen::Io::File::Remove(fileName); + + return r; +} + + +result +_CertDbManager::RemoveCertificateChainByCertId(int certId) +{ + result r = E_SUCCESS; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, }; + UserCertRecord userCertRecord = {0, }; + + memset(&userCertRecord, 0, sizeof(userCertRecord)); + memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE); + + sprintf(condition, "certId = %d", certId); + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record."); + SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found."); + + r = DeleteCertificateChain(userCertRecord.certId, userCertRecord.parentCa); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "File deletion failed for certificate Id (%d).", certId); + + return r; +} + + +result +_CertDbManager::GetCaCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId, _CaCertType certType) +{ + result r = E_SUCCESS; + int subjNameB64len = 0; + int issuerB64len = 0; + char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + CaCertRecord caCertRecord = {0, }; + + SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name."); + SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length."); + + subjNameB64len = _Base64::GetEncodedSize(subjectNameSize); + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + + r = _Base64::Encode(pSubjectName, subjectNameSize, subjectNameBase64, subjNameB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + memset(condition, 0, sizeof(condition)); + + if (pIssuerName != null && issuerNameSize > 0) + { + issuerB64len = _Base64::GetEncodedSize(issuerNameSize); + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + + r = _Base64::Encode(pIssuerName, issuerNameSize, issuerNameBase64, issuerB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + if (certType == _CERT_TYPE_NOT_BOUNDED) + { + sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed); + } + else + { + sprintf(condition, "subjectName = '%s' and issuerName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, issuerNameBase64, certType, installed); + } + } + else + { + if (certType == _CERT_TYPE_NOT_BOUNDED) + { + sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed); + } + else + { + sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed); + } + } + + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &caCertRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + certId = caCertRecord.certId; + + return E_SUCCESS; +} + +result +_CertDbManager::GetUserCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId) +{ + result r = E_SUCCESS; + int subjNameB64len = 0; + int issuerB64len = 0; + char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + UserCertRecord userCertRecord = {0, }; + + SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name."); + SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length."); + + subjNameB64len = _Base64::GetEncodedSize(subjectNameSize); + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + + r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameSize, subjectNameBase64, subjNameB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + memset(condition, 0, sizeof(condition)); + + if (pIssuerName != null && issuerNameSize > 0) + { + issuerB64len = _Base64::GetEncodedSize(issuerNameSize); + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + + r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameSize, issuerNameBase64, issuerB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed); + } + else + { + sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed); + } + + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r)); + + certId = userCertRecord.certId; + + return E_SUCCESS; +} + +result +_CertDbManager::RemoveAllUserCertificate(void) +{ + __userCertDbStore.DeleteUserCertFiles(); + + return E_SUCCESS; +} + +result +_CertDbManager::DeleteCertificateChain(int devCertId, int devParentCA) +{ + result r = E_SUCCESS; + CaCertRecord certRecord = {0, }; + int recCount = 0; + int caCertId = 0; + int caParentCa = 0; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, }; + bool devCert = true; + + SysTryReturnResult(NID_SEC_CERT, devCertId > 0, E_INVALID_ARG, "Invalid input argument."); + SysTryReturnResult(NID_SEC_CERT, devParentCA > 0, E_INVALID_ARG, "Invalid input argument."); + + memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE); + + sprintf(condition, "parentCa = %d and installed = '%s'", devParentCA, installed); + //Check if any other device certificate has same parent as of referred device certificare. If it is yes then we + //delete only device certificate and return. We cannot disturb another chain. + __userCertDbStore.GetCountByCondition(reinterpret_cast< byte* >(&condition), recCount); + //More than one device certificate found which is referring same intermidiate CA or ROOT CA. So just delete device certificate and return. + if (recCount > 1) + { + r = DeleteCertificateByIdNTableName(devCertId, _CERT_USER_CERT_TABLE); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate."); + + return E_SUCCESS; + } + //Now there is not two device certificate with same intermidiate CA, + //so go ahead to intermidiate CA and delete device certificate. + caParentCa = devParentCA; + caCertId = devCertId; + do + { + if (__caCertDbStore.CheckIfSameParent(caParentCa) == E_SUCCESS) + { + if (devCert) + { + r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate."); + + devCert = false; //Device certificate is deleted here now go to CA certificate for deletion + SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion."); + break; // break here next certificate has dependency + } + else + { + r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate."); + + break; // break here next certificate has dependency + } + } + else // The caCertId's parent is no more parent of any other certificate so delete caCertId from Db. + { + if (devCert) //If it is device certificate + { + r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate table."); + + devCert = false; //Device certificate is deleted here now go to CA certificate for deletion + SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion."); + } + else //If it is CA certificate and there is no dependency + { + r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate table."); + + SysLog(NID_SEC_CERT, "It is CA certificate and there is no dependency."); + } + caCertId = caParentCa; // Now look for next certificate in chain + memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE); + sprintf(condition, "certId = %d and installed = '%s'", devParentCA, installed); + memset(&certRecord, 0, sizeof(certRecord)); + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record."); + SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found."); + + caParentCa = certRecord.parentCa; + } + } + while (caCertId != caParentCa); + + return E_SUCCESS; +} + +result +_CertDbManager::GetCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count) +{ + result r = E_SUCCESS; + CaCertRecord certRecord = {0, }; + _CertificateListInfo* pHoldList = null; + _CertFileStore fileStore; + int certCount = 0; + int certLength = 0; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + char condition[_MAX_TYPE_CONST_SIZE] = {0, }; + + sprintf(condition, "certFormat = %d and certType != %d and installed = '%s'", certFormat, _CERT_TYPE_INTERMIDIATE_CA, installed); + + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record."); + SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found."); + + std::unique_ptr <_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo); + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertList.get(), 0, sizeof(*pCertList.get())); + pCertList->pNext = null; + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = fileStore.ReadFromFile(pCertList->certificate, certLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file."); + + pCertList->length = certLength; + pCertList->certFileId = certRecord.certId; + pCertList->format = static_cast< _CertFormat >(certRecord.certFormat); + pCertList->certType = static_cast< _CaCertType >(certRecord.certType); + certCount++; + + pHoldList = pCertList.release(); + *ppCertList = pHoldList; + + while (__caCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS) + { + std::unique_ptr <_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo); + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertList.get(), 0, sizeof(*pCertList.get())); + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = fileStore.ReadFromFile(pCertList->certificate, certLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file."); + + pCertList->pNext = null; + pCertList->length = certLength; + pCertList->certFileId = certRecord.certId; + pCertList->format = (_CertFormat) certRecord.certFormat; + pCertList->certType = static_cast< _CaCertType >(certRecord.certType); + + pHoldList->pNext = pCertList.release(); + pHoldList = pHoldList->pNext; + + certCount++; + } + + count = certCount; + + + return r; +} + +result +_CertDbManager::GetUserCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count) +{ + result r = E_SUCCESS; + UserCertRecord certRecord = {0, }; + _CertificateListInfo* pHoldList = null; + _CertFileStore fileStore; + int certCount = 0; + int certLength = 0; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + char condition[_MAX_TYPE_CONST_SIZE] = {0, }; + + *ppCertList = null; + + sprintf(condition, "certFormat = %d and installed = '%s'", certFormat, installed); + + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record."); + SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found."); + + std::unique_ptr<_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo); + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertList.get(), 0, sizeof(*pCertList.get())); + pCertList->pNext = null; + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = fileStore.ReadFromFile(pCertList->certificate, certLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file."); + + pCertList->length = certLength; + pCertList->certFileId = certRecord.certId; + pCertList->format = static_cast< _CertFormat >(certRecord.certFormat); + pCertList->certType = _CERT_TYPE_USER_CERT; + certCount++; + + pHoldList = pCertList.release(); + *ppCertList = pHoldList; + + while (__userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS) + { + std::unique_ptr<_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo); + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertList.get(), 0, sizeof(*pCertList.get())); + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = fileStore.ReadFromFile(pCertList->certificate, certLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file."); + + pCertList->pNext = null; + pCertList->length = certLength; + pCertList->certFileId = certRecord.certId; + pCertList->format = static_cast< _CertFormat >(certRecord.certFormat); + pCertList->certType = _CERT_TYPE_USER_CERT; + + pHoldList->pNext = pCertList.release(); + pHoldList = pHoldList->pNext; + + certCount++; + } + + count = certCount; + + return E_SUCCESS; +} + +result +_CertDbManager::GetCaCertificateListByCertId(int certId, _CertificateListInfo** ppCertList) +{ + result r = E_SUCCESS; + CaCertRecord certRecord = {0, }; + _CertFileStore fileStore; + int certLength = 0; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + char condition[_MAX_TYPE_CONST_SIZE] = {0, }; + + *ppCertList = null; + sprintf(condition, "certId = %d and certType != %d and installed = '%s'", certId, _CERT_TYPE_INTERMIDIATE_CA, installed); + + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r)); + + std::unique_ptr <_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo); + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertList.get(), 0, sizeof(*pCertList.get())); + + pCertList->pNext = null; + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = fileStore.ReadFromFile(pCertList->certificate, certLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file."); + + pCertList->length = certLength; + pCertList->certFileId = certRecord.certId; + pCertList->format = static_cast< _CertFormat >(certRecord.certFormat); + pCertList->certType = static_cast< _CaCertType >(certRecord.certType); + + *ppCertList = pCertList.release(); + + return r; +} + +result +_CertDbManager::GetUserCertificateListByCertId(int certId, _CertificateListInfo** ppCertList) +{ + result r = E_SUCCESS; + _CertFileStore fileStore; + UserCertRecord certRecord = {0, }; + int priKeyLen = 0; + int certLength = 0; + char condition[_MAX_TYPE_CONST_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + *ppCertList = null; + + SysTryReturnResult(NID_SEC_CERT, ppCertList != null, E_INVALID_ARG, "Invalid input arguments."); + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input arguments."); + + sprintf(condition, "certId = %d and installed = '%s'", certId, installed); + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r)); + + std::unique_ptr <_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo); + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertList.get(), 0, sizeof(*pCertList.get())); + + pCertList->pNext = null; + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = fileStore.ReadFromFile(pCertList->certificate, certLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file."); + + pCertList->length = certLength; + pCertList->certFileId = certRecord.certId; + pCertList->format = static_cast< _CertFormat >(certRecord.certFormat); + pCertList->certType = _CERT_TYPE_USER_CERT; + + std::unique_ptr <_CertPrivateKeyInfo> pPriKey (new (std::nothrow) _CertPrivateKeyInfo()); + SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + std::unique_ptr pPrivateKey (new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]); + SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE); + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = fileStore.ReadFromFile(pPrivateKey.get(), priKeyLen); + if (!IsFailed(r) && priKeyLen != 0) + { + byte* pPrivateTempKey = null; + pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get()); + + pPrivateKey.reset(null); + + pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0); + SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer."); + + std::unique_ptr pPrivateKeyAuto(pPrivateTempKey); + + memcpy(pCertList->privatekey, pPrivateTempKey, priKeyLen); + } + pCertList->priKeyLen = priKeyLen; + + *ppCertList = pCertList.release(); + + return r; +} + +result +_CertDbManager::FindIssuerCertificateAndTypeN(_CertFormat certFormat, char* pIssuerName, byte** ppCert, int& certLen, _CaCertType& certType) +{ + result r = E_SUCCESS; + CaCertRecord certRecord = {0, }; + _CertFileStore fileStore; + String filePath; + int issuerNameB64len = 0; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_OFFSET_CONST_SIZE] = {0, }; + char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments."); + SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments."); + + issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName)); + SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + + r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + sprintf(condition, "subjectName = '%s' and certFormat = %d and installed = '%s'", issuerNameBase64, certFormat, installed); + + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r)); + + filePath = reinterpret_cast< char* >(certRecord.fileName); + + fileStore.SetFilePath(filePath); + + *ppCert = new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE]; + SysTryReturnResult(NID_SEC_CERT, *ppCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = fileStore.ReadFromFile(*ppCert, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r)); + + certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate + + return r; +} + +result +_CertDbManager::FindIssuerCertificateByTypeN(_CertFormat certFormat, _CaCertType certType, char* pIssuerName, byte** ppCert, int& certLen) +{ + result r = E_SUCCESS; + String filePath; + CaCertRecord certRecord = {0, }; + _CertFileStore fileStore; + int issuerNameB64len = 0; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_CONDITION_SIZE] = {0, }; + char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_NAME_OFFSET] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type."); + SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments."); + SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments."); + + issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName)); + SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to get encoded size."); + + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + + r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + sprintf(condition, "subjectName = '%s' and certFormat = %d and certType = %d and installed = '%s'", issuerNameBase64, certFormat, certType, installed); + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r)); + + if (certRecord.certId == 0) + { + return E_SUCCESS; + } + + filePath = static_cast< char* >(certRecord.fileName); + fileStore.SetFilePath(filePath); + + std::unique_ptr pCert (new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE]); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = fileStore.ReadFromFile(pCert.get(), certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r)); + + certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate + + *ppCert = pCert.release(); + + return r; +} + +result +_CertDbManager::FindCertType(_CertFormat certFormat, char* pIssuerName, char* pSubjectName, _CaCertType* pCertType) +{ + result r = E_SUCCESS; + CaCertRecord certRecord = {0, }; + _CertFileStore fileStore; + int subjectNameB64len = 0; + int issuerNameB64len = 0; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_CONDITION_CONST_SIZE] = {0, }; + char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, }; + char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, }; + char installed[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments."); + SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input arguments."); + SysTryReturnResult(NID_SEC_CERT, pCertType != null, E_INVALID_ARG, "Invalid input arguments."); + + issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName)); + SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + + r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + subjectNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName)); + SysTryReturnResult(NID_SEC_CERT, subjectNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjectNameB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + sprintf(condition, "certFormat = %d and issuerName = '%s' and subjectName = '%s' and installed = '%s'", certFormat, issuerNameBase64, subjectNameBase64, installed); + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r)); + + *pCertType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate + return E_SUCCESS; +} + +result +_CertDbManager::DeleteCertificateByIdNTableName(int certId, String tableName) +{ + result r = E_SUCCESS; + _CertFileStore fileStore; + String fileName; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input argument."); + + if (tableName.CompareTo(_CERT_USER_CERT_TABLE) == 0) + { + String keyfileName; + + r = __userCertDbStore.RemoveCertificateById(certId); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Error in deleting certificate."); + + //Remove certificate file + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, fileName); + r = Tizen::Io::File::Remove(fileName); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file."); + + //Remove private key file + //Don't check return type here as it is not necessary that private key is present. + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyfileName); + r = Tizen::Io::File::Remove(keyfileName); + } + else if (tableName.CompareTo(_CERT_ROOT_CA_CERT_TABLE) == 0) + { + r = __caCertDbStore.RemoveCertificateById(certId); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Delete certificate failed."); + + //Remove certificate file + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName); + r = Tizen::Io::File::Remove(fileName); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file."); + } + return E_SUCCESS; +} + +result +_CertDbManager::GetHashOfCertFile(byte* pFilePath, int* pLen, char* pBuf) +{ + result r = E_SUCCESS; + String fileName(reinterpret_cast< char* >(pFilePath)); + FileAttributes attr; + File file; + long fileSize = 0; + int readCnt = 0; + int certLen = 0; + int outLen = _MAX_CERT_SHA1_DIGEST_SIZE; + int resValue = 0; + + SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid inpur arguments."); + SysTryReturnResult(NID_SEC_CERT, pLen != null, E_INVALID_ARG, "Invalid inpur arguments."); + SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Invalid inpur arguments."); + + r = File::GetAttributes(fileName, attr); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get attributes."); + + fileSize = attr.GetFileSize(); + SysTryReturn(NID_SEC_CERT, fileSize >= 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r)); + + // Open file + r = file.Construct(fileName, L"r"); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to construct file."); + + std::unique_ptr pCertBuf (new (std::nothrow) byte[fileSize + 1]); + SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertBuf.get(), 0, fileSize + 1); + readCnt = file.Read(pCertBuf.get(), fileSize); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r)); + + certLen = readCnt; + std::unique_ptr pOutBuf (new (std::nothrow) byte[outLen]); + SysTryReturnResult(NID_SEC_CERT, pOutBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pOutBuf.get(), 0, outLen); + //As per OpenSSL APIs, it takes input as unsigned data types + resValue = EVP_Digest(pCertBuf.get(), static_cast< int >(certLen), pOutBuf.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0); + SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to create digest."); + + memcpy(pBuf, pOutBuf.get(), outLen); + *pLen = outLen; + + return r; +} + +//User Certificate APIs + +result +_CertDbManager::InsertCertChain(_CertFormat certFormat, _CertChain* pCertChain) +{ + result r = E_SUCCESS; + _CaCertType certType = _CERT_TYPE_NOT_BOUNDED; + int curCACertId = 0; + int lastCACertId = 0; + int curDevCertId = 0; + bool updateUserParentCa = false; + + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + + //Check for CA certificate table creation + r = __caCertDbStore.IsRootCaCertTableCreated(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Certificate table are not not created."); + + + //Check if the chain is valid or not + r = pCertChain->Verify(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_ARG, "Invalid certificate chain."); + + r = pCertChain->MoveHead(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain."); + + if (certFormat == _CERT_X509) + { + _X509Certificate* pCurCert = null; + _X509Certificate* pUserCert = null; + _X509TbsCert* pTbsCert = null; + byte* pX509Buff = null; + int x509BuffSize = 0; + + pUserCert = pCertChain->GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain."); + + pTbsCert = pUserCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + pUserCert->GetCertBuffer(pX509Buff, x509BuffSize); + SysTryReturn(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer."); + + r = InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, null, 0); + SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && (r != E_OBJ_ALREADY_EXIST) && (r != E_FILE_ALREADY_EXIST)), r, r, "[%s] Failed insert user certificate chain.", GetErrorMessage(r)); + + updateUserParentCa = true; + + r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())), + pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + curDevCertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r)); + + //Insert certificate chain in CA certificate store + while (pCertChain->MoveNext() == E_SUCCESS) + { + + pCurCert = pCertChain->GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain."); + + if (!pCurCert->IsSelfSigned()) + { + certType = _CERT_TYPE_INTERMIDIATE_CA; + } + else + { + //This parameter need to pass from certificate manager about its type + certType = _CERT_TYPE_ROOT_CA; + } + + pTbsCert = pCurCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + if (E_SUCCESS != __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(pTbsCert->GetSubjectName()), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())))) + { + pX509Buff = null; + x509BuffSize = 0; + + pCurCert->GetCertBuffer(pX509Buff, x509BuffSize); + SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer."); + + r = InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize); + SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate."); + } + // CA certificate already present or properly installed in CA certificate store, + // get the certificate id of certificate + r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())), + pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + curCACertId, certType); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r)); + + if (updateUserParentCa) + { + __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId); + updateUserParentCa = false; + lastCACertId = curCACertId; + } + else + { + __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId); + lastCACertId = curCACertId; + } + + //If it is root certificate then its parent is itself + if (pCurCert->IsSelfSigned()) + { + __caCertDbStore.UpdateParentCa(curCACertId, curCACertId); + } + + } //end of while + + if (updateUserParentCa) + { + r = pCertChain->MoveHead(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain."); + + pCurCert = pCertChain->GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain."); + + pTbsCert = pCurCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + null, 0, curCACertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r)); + + __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId); + updateUserParentCa = false; + lastCACertId = curCACertId; + } + else if (!pCurCert->IsSelfSigned()) + { + pTbsCert = pCurCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + null, 0, curCACertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r)); + + __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId); + lastCACertId = curCACertId; + } + } + + return r; +} + +result +_CertDbManager::InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo) +{ + result r = E_SUCCESS; + _CaCertType certType = _CERT_TYPE_NOT_BOUNDED; + int prvKeyLen = 0; + int curCACertId = 0; + int lastCACertId = 0; + int curDevCertId = 0; + + bool updateUserParentCa = false; + byte* pPrvKey = null; + std::unique_ptr pPrvKeyBuffer; + + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + + r = __userCertDbStore.IsUserCertTableCreated(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table."); + + //Check for CA certificate table creation + r = __caCertDbStore.IsRootCaCertTableCreated(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table."); + + //Check if the chain is valid or not + r = pCertChain->Verify(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate.", GetErrorMessage(r)); + + r = pCertChain->MoveHead(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain."); + + if (certFormat == _CERT_X509) + { + _X509Certificate* pCurCert = null; + _X509Certificate* pUserCert = null; + _X509TbsCert* pTbsCert = null; + byte* pX509Buff = null; + int x509BuffSize = 0; + + pUserCert = pCertChain->GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain."); + + pTbsCert = pUserCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + byte* pSubjectName = pTbsCert->GetSubjectName(); + SysTryReturn(NID_SEC_CERT, pSubjectName != null, E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Subjectname not present."); + + int subjectNameLen = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())); + + r = __userCertDbStore.CheckDuplicateCertificate(pSubjectName, subjectNameLen); + if (IsFailed(r)) + { + if (pPrivateKeyInfo != null) + { + pPrivateKeyInfo->GetPkcs8EncDecKeyN(prvKeyLen, &pPrvKey, 1); + SysTryReturnResult(NID_SEC_CERT, prvKeyLen > 0, E_INVALID_KEY, "Invalid key length ."); + + pPrvKeyBuffer = std::unique_ptr (pPrvKey); + pPrvKey = null; + + } + + pUserCert->GetCertBuffer(pX509Buff, x509BuffSize); + SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer."); + + r = _CertDbManager::InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, pPrvKeyBuffer.get(), static_cast< int >(prvKeyLen)); + if (IsFailed(r) && r != E_OBJ_ALREADY_EXIST && r != E_FILE_ALREADY_EXIST) + { + return r; + } + else + { + updateUserParentCa = true; + + r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())), + pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + curDevCertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r)); + + if (pPrvKeyBuffer != null) + { + _CertFileStore fileStore; + String privateKeyFile; + + fileStore.GetFileNameFromHandle(curDevCertId, _CERT_PATH_PRIVATE_KEY, privateKeyFile); + fileStore.SetFilePath(privateKeyFile); + + + r = fileStore.WriteToFile(pPrvKeyBuffer.get(), prvKeyLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file."); + + } + } + } + else + { + return r; + } + + //Insert certificate chain in CA certificate store + while (pCertChain->MoveNext() == E_SUCCESS) + { + pCurCert = pCertChain->GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain."); + + if (!pCurCert->IsSelfSigned()) + { + certType = _CERT_TYPE_INTERMIDIATE_CA; + } + else + { + //This parameter need to pass from certificate manager about its type + certType = _CERT_TYPE_ROOT_CA; + } + + pTbsCert = pCurCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()))); + if (IsFailed(r)) + { + pX509Buff = null; + x509BuffSize = 0; + + pCurCert->GetCertBuffer(pX509Buff, x509BuffSize); + SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer."); + + r = _CertDbManager::InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize); + SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate."); + + } + // CA certificate already present or properly install in CA certificate store, + // get the certificate id of certificate + + r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())), + pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + curCACertId, certType); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r)); + + if (updateUserParentCa) + { + __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId); + updateUserParentCa = false; + lastCACertId = curCACertId; + } + else + { + __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId); + lastCACertId = curCACertId; + } + + //If it is root certificate then its parent is itself + if (pCurCert->IsSelfSigned()) + { + __caCertDbStore.UpdateParentCa(curCACertId, curCACertId); + } + } + + if (updateUserParentCa) + { + r = pCertChain->MoveHead(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain."); + + pCurCert = pCertChain->GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain."); + + pTbsCert = pCurCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + null, 0, curCACertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r)); + + __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId); + updateUserParentCa = false; + lastCACertId = curCACertId; + } + else if (!pCurCert->IsSelfSigned()) + { + pTbsCert = pCurCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + null, 0, curCACertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r)); + + __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId); + lastCACertId = curCACertId; + } + } + + return r; +} + +result +_CertDbManager::InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa) +{ + result r = E_SUCCESS; + _X509TbsCert* pTbsCert = null; + _CertFileStore fileStore; + UserCertRecord certRecord = {0, }; + String privateKeyFile; + String tempFileName; + int lenSubjectName = 0; + int lenIssuerName = 0; + int lenSerialNo = 0; + int certId = 0; + int keyIdB64Length = 0; + char* pFileName = null; + char* pPriKeyFileName = null; + char subjectNameBuffer[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char szIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, }; + char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0"; + byte* pKeyId = null; + byte* pSerial = null; + + //pPrivateKey, privateKeyLen, parentca are optional parameter, no need to sanity check for them. + SysTryReturnResult(NID_SEC_CERT, pCertBuffer != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + SysTryReturnResult(NID_SEC_CERT, certLength > 0, E_INVALID_ARG, "Invalid input parameter."); + + r = __userCertDbStore.IsUserCertTableCreated(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create user certificate."); + + std::unique_ptr <_X509Certificate> pCert (new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pCert->Parse(pCertBuffer, certLength); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing failed.", GetErrorMessage(r)); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())); + lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())); + + SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length."); + SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length."); + + strcpy(subjectNameBuffer, reinterpret_cast< char* >(pTbsCert->GetSubjectName())); + strcpy(szIssuerName, reinterpret_cast< char* >(pTbsCert->GetIssuerName())); + + pTbsCert->GetSerialNumber(pSerial, static_cast< int& >(lenSerialNo)); + if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE)) + { + if (pSerial != null) + { + memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE); + lenSerialNo = 1; + } + } + else + { + memcpy(serialName, pSerial, lenSerialNo); + } + + //Get Device ID + r = pCert->GetKeyIdN(&pKeyId); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to get key Id."); + + std::unique_ptr pKeyIdBuffer (pKeyId); + + keyIdB64Length = _Base64::GetEncodedSize(_MAX_CERT_SHA1_DIGEST_SIZE); + SysTryReturnResult(NID_SEC_CERT, keyIdB64Length >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + std::unique_ptr pId64 (new (std::nothrow) char[keyIdB64Length]); + SysTryReturnResult(NID_SEC_CERT, pId64 != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pId64.get(), 0, keyIdB64Length); + r = _Base64::Encode(reinterpret_cast< byte* >(pKeyIdBuffer.get()), _MAX_CERT_SHA1_DIGEST_SIZE, pId64.get(), keyIdB64Length); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed."); + + r = __userCertDbStore.CheckDuplicateCertificate(reinterpret_cast< byte* >(subjectNameBuffer), lenSubjectName); + SysTryReturnResult(NID_SEC_CERT, IsFailed(r), E_FILE_ALREADY_EXIST, "File already exists."); + + //Get the last installed certificate id from db table + __userCertDbStore.GetCurrentCertId(certId); + + //Calculate the new certificate id for installation + certId = certId + 1; + + if (pPrivateKey != null) + { + //Get file name for private key and store private key into file. + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, privateKeyFile); + } + else + { + pPriKeyFileName = null; + privateKeyLen = 0; + } + + //Get file name for certificate and write device certificate to file + fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, tempFileName); + + //Insert Record into Database + //It is generated automatically by sequence + memset(&certRecord, 0, sizeof(certRecord)); + + memcpy(certRecord.certPubKeyHash, pId64.get(), keyIdB64Length); //Base64 encoded device id + certRecord.certFormat = static_cast< int >(certFormat); + + pFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName); + SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get attributes."); + + strcpy(certRecord.fileName, pFileName); + certRecord.subjectNameLen = lenSubjectName; + + memcpy(certRecord.subjectName, subjectNameBuffer, lenSubjectName); + certRecord.issuerNameLen = lenIssuerName; + memcpy(certRecord.issuerName, szIssuerName, lenIssuerName); + + pPriKeyFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(privateKeyFile); + SysTryReturnResult(NID_SEC_CERT, pPriKeyFileName != null, E_SYSTEM, "Failed to get attributes."); + + strcpy(certRecord.prvKeyPath, pPriKeyFileName); + certRecord.prvKeyLen = privateKeyLen; + certRecord.parentCa = certId; + strcpy(certRecord.installed, installedRecord); + + memcpy(certRecord.serialNo, serialName, lenSerialNo); + + certRecord.serialNoLen = lenSerialNo; + + r = __userCertDbStore.InsertUserCertificate(&certRecord); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DATABASE, "Failed to insert user certificate."); + + fileStore.SetFilePath(tempFileName); + + r = fileStore.WriteToFile(pCertBuffer, certLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file."); + + if (pPrivateKey != null) + { + fileStore.SetFilePath(privateKeyFile); + + r = fileStore.WriteToFile(pPrivateKey, privateKeyLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file."); + } + + return r; +} + +result +_CertDbManager::GetUserCertificateChain(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subjectNameLen, _CertEncodingType encodingType, _CertificateListInfo** ppCertListInfoTypes) +{ + result r = E_SUCCESS; + CaCertRecord certRecord = {0, }; + UserCertRecord userCertRecord = {0, }; + _CertificateListInfo* pHoldList = null; + BIO* pBio = null; + X509* pCert = null; + EVP_PKEY* pKey = null; + int certCount = 0; + int recordCount = 0; + int subjectNameBase64Len = 0; + int count = 0; + int readLength = 0; + int priKeyLen = 0; + int subNameLen = 0; + int curCertId = 0; + int certificateBase64Len = 0; + char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0"; + char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0}; + byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, }; + byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, }; + byte subName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + bool isIssuerNameInList = false; + + subjectNameBase64Len = _Base64::GetEncodedSize(issuerNameLen); + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameLen, reinterpret_cast< char* >(issuerNameBase64), subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r),E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + if ((pSubjectName != null) && (subjectNameLen > 0)) + { + subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen); + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r),E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord); + } + else + { + r = __userCertDbStore.GetNumberOfCertificates(recordCount); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates.", GetErrorMessage(r)); + SysTryReturnResult(NID_SEC_CERT, recordCount > 0, E_OBJ_NOT_FOUND, "Failed to get certificate records."); + sprintf(condition, "installed = '%s'", installedRecord); + } + + memset(&userCertRecord, 0, sizeof(userCertRecord)); + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + std::unique_ptr <_CertPrivateKeyInfo> pPriKey (new (std::nothrow) _CertPrivateKeyInfo()); + SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + do + { + std::unique_ptr <_CertFileStore> pFileStore (new (std::nothrow) _CertFileStore()); + SysTryReturnResult(NID_SEC_CERT, pFileStore != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + std::unique_ptr<_CertificateListInfo> pCertList(new (std::nothrow) _CertificateListInfo); + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertList.get(), 0, sizeof(*pCertList.get())); + + pCertList->pNext = null; + + r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_USER_CERT); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file."); + certificateBase64Len = _Base64::GetEncodedSize(pCertList->length); + + if (encodingType == _CERT_ENC_TYPE_PEM) + { + const byte* pCertBuffer = pCertList->certificate; + + pBio = BIO_new(BIO_s_mem()); + SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pCert = d2i_X509(null, &pCertBuffer, pCertList->length); + SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed."); + + readLength = PEM_write_bio_X509(pBio, pCert); + SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER); + + readLength = BIO_read(pBio, pCertList->certificate, pCertList->length); + SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + pCertList->length = readLength; + + BIO_free(pBio); + pBio = null; + + X509_free(pCert); + pCert = null; + + } + else if (encodingType == _CERT_ENC_TYPE_BASE64) + { + int certLen = _Base64::GetEncodedSize(pCertList->length); + memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length); + r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + pCertList->length = certLen; + } + + std::unique_ptr pPrivateKey (new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]); + SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE); + pCertList->format = static_cast< _CertFormat >(userCertRecord.certFormat); + pCertList->certFileId = userCertRecord.certId; + + r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_PRIVATE_KEY); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + priKeyLen = 0; + + r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen); + if (!IsFailed(r) && priKeyLen != 0) + { + byte* pPrivateTempKey = null; + pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get()); + pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER; + + pPrivateKey.reset(null); + priKeyLen = 0; + + pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0); + SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer."); + + pPrivateKey = std::unique_ptr(pPrivateTempKey); + + if (encodingType == _CERT_ENC_TYPE_PEM) + { + const byte* pKeyBuffer = pPrivateKey.get(); + pBio = BIO_new(BIO_s_mem()); + SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, priKeyLen); + SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed"); + + PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null); + SysTryCatch(NID_SEC_CERT, pBio != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key to bio conversion failed"); + + readLength = BIO_read(pBio, pCertList->privatekey, pCertList->priKeyLen); + + SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed"); + + pCertList->priKeyLen = readLength; + + BIO_free(pBio); + pBio = null; + + X509_free(pCert); + pCert = null; + } + else if (encodingType == _CERT_ENC_TYPE_BASE64) + { + pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen); + memset(pCertList->privatekey, 0, sizeof(pCertList->privatekey)); + + r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertList->privatekey), pCertList->priKeyLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + } + else + { + memcpy(pCertList->privatekey, pPrivateKey.get(), priKeyLen); + pCertList->priKeyLen = priKeyLen; + } + } + + pPrivateKey.reset(null); + + pHoldList = pCertList.release(); + *ppCertListInfoTypes = pHoldList; + + certCount++; + + memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memcpy(subName, userCertRecord.issuerName, userCertRecord.issuerNameLen); + subNameLen = userCertRecord.issuerNameLen; + + do + { + subjectNameBase64Len = _Base64::GetEncodedSize(subNameLen); + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + r = _Base64::Encode(reinterpret_cast< byte* >(subName), subNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to encode data in base 64 encoding.", GetErrorMessage(r)); + sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord); + + if (strcmp(reinterpret_cast< char* >(issuerNameBase64), reinterpret_cast< char* >(subjectNameBase64)) == 0) + { + isIssuerNameInList = true; + } + + memset(&certRecord, 0, sizeof(certRecord)); + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + if (strcmp(certRecord.issuerName, certRecord.subjectName) != 0) + { + std::unique_ptr<_CertificateListInfo> pCertList(new (std::nothrow) _CertificateListInfo()); + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pCertList.get(), 0, sizeof(*pCertList.get())); + pCertList->pNext = null; + + r = pFileStore->SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file."); + certificateBase64Len = _Base64::GetEncodedSize(pCertList->length); + + if (encodingType == _CERT_ENC_TYPE_PEM) + { + const byte* pCertBuffer = pCertList->certificate; + + pBio = BIO_new(BIO_s_mem()); + SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pCert = d2i_X509(null, &pCertBuffer, pCertList->length); + SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed."); + + readLength = PEM_write_bio_X509(pBio, pCert); + SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER); + + readLength = BIO_read(pBio, pCertList->certificate, pCertList->length); + SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + pCertList->length = readLength; + + BIO_free(pBio); + pBio = null; + + X509_free(pCert); + pCert = null; + } + else if (encodingType == _CERT_ENC_TYPE_BASE64) + { + int certLen = _Base64::GetEncodedSize(pCertList->length); + memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length); + r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r),E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + pCertList->length = certLen; + } + pCertList->format = (_CertFormat) certRecord.certFormat; + pCertList->certType = (_CaCertType) certRecord.certType; + pCertList->certFileId = certRecord.certId; + + pHoldList->pNext = pCertList.release(); + pHoldList = pHoldList->pNext; + + certCount++; + + memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memcpy(subName, certRecord.issuerName, certRecord.issuerNameLen); + subNameLen = certRecord.issuerNameLen; + } + + } + while (strcmp(certRecord.issuerName, certRecord.subjectName)); + + if (!isIssuerNameInList) + { + if (*ppCertListInfoTypes != null) + { + _CertService::FreeCertList(*ppCertListInfoTypes); + *ppCertListInfoTypes = null; + } + + memset(condition, 0, sizeof(condition)); + sprintf(condition, "installed = '%s'", installedRecord); + + count++; + + memset(&userCertRecord, 0, sizeof(userCertRecord)); + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + curCertId = userCertRecord.certId; + + for (readLength = 0; readLength < count; readLength++) + { + + memset(&userCertRecord, 0, sizeof(userCertRecord)); + r = __userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &userCertRecord, curCertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate records.", GetErrorMessage(r)); + curCertId = userCertRecord.certId; + } + } + + } + while (isIssuerNameInList != true); + +CATCH: + if (pBio != null) + { + BIO_free(pBio); + } + if (pCert != null) + { + X509_free(pCert); + } + if (pKey != null) + { + EVP_PKEY_free(pKey); + } + + return r; +} + +result +_CertDbManager::GetUserCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo, char* pSubjectName) +{ + result r = E_SUCCESS; + UserCertRecord userCertRecord = {0, }; + CaCertRecord caCertRecord = {0, }; + int subjNameB64len = 0; + int parentCa = 0; + char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, }; + char conditonRecord[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, }; + char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + subjNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName)); + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjNameB64len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + sprintf(conditonRecord, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord); + + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &userCertRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + if (pPrivateKeyInfo != null) + { + pPrivateKeyInfo->SetPrivateKey(userCertRecord.prvKeyPath); + } + + r = pCertChain->AddCertificate(certFormat, userCertRecord.fileName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] AddCertificate failed.", GetErrorMessage(r)); + + parentCa = userCertRecord.parentCa; + + do + { + memset(&caCertRecord, 0, sizeof(caCertRecord)); + memset(conditonRecord, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE); + sprintf(conditonRecord, "certId = %d and installed = '%s'", parentCa, installedRecord); + + r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &caCertRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + parentCa = caCertRecord.parentCa; + if (caCertRecord.certId != caCertRecord.parentCa) //Exclude root certificate from the chain + { + r = pCertChain->AddCertificate(certFormat, caCertRecord.fileName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate in chain.", GetErrorMessage(r)); + } + + } + while (caCertRecord.certId != caCertRecord.parentCa); + + return E_SUCCESS; +} + +result +_CertDbManager::GetUserCertificateInfoByCertId(int certId, int* pSubjectLength, byte* pSubjectName, int* pIssuerLength, byte* pIssuerName) +{ + result r = E_SUCCESS; + UserCertRecord userCertRecord = {0, }; + char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0"; + char condition[_MAX_TYPE_CONST_SIZE] = {0, }; + + sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord); + + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + *pSubjectLength = userCertRecord.subjectNameLen; + memcpy(pSubjectName, userCertRecord.subjectName, userCertRecord.subjectNameLen); + *pIssuerLength = userCertRecord.issuerNameLen; + memcpy(pIssuerName, userCertRecord.issuerName, userCertRecord.issuerNameLen); + + return E_SUCCESS; + +} + +result +_CertDbManager::GetUserCertificateInfoByCertId(int certId, _CertEncodingType encodingType, _CertInfo** ppUserCertInfo) +{ + result r = E_SUCCESS; + char condition[_MAX_TYPE_CONST_SIZE] = {0, }; + char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0"; + int priKeyLen = 0; + int readCount = 0; + int certBufferLen = 0; + int keyBufferLen = 0; + int certificateBase64Len = 0; + const byte* pCertBuffer = null; + const byte* pKeyBuffer = null; + byte* pPrivateTempKey = null; + UserCertRecord certRecord = {0, }; + _CertFileStore fileStore; + std::unique_ptr <_CertPrivateKeyInfo> pPriKey; + BIO* pBio = null; + X509* pCert = null; + EVP_PKEY* pKey = null; + + *ppUserCertInfo = null; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter."); + sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord); + + r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r)); + + std::unique_ptr <_CertInfo> pCertInfo (new (std::nothrow) _CertInfo); + SysTryCatch(NID_SEC_CERT, pCertInfo != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pCertInfo.get(), 0, sizeof(*pCertInfo.get())); + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to set file handle.", GetErrorMessage(r)); + + r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to read from file.", GetErrorMessage(r)); + certificateBase64Len = _Base64::GetEncodedSize(pCertInfo->certLength); + + if (encodingType == _CERT_ENC_TYPE_PEM) + { + pBio = BIO_new(BIO_s_mem()); + SysTryCatch(NID_SEC_CERT, pBio != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pCertBuffer = new (std::nothrow) byte[pCertInfo->certLength]; + SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memcpy((void*) pCertBuffer, pCertInfo->certificate, pCertInfo->certLength); + certBufferLen = pCertInfo->certLength; + + pCert = d2i_X509(null, &pCertBuffer, certBufferLen); + SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed."); + + readCount = PEM_write_bio_X509(pBio, pCert); + SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + pCertInfo->certLength = certificateBase64Len + (2 * _MAX_PEM_HEADER); + readCount = BIO_read(pBio, pCertInfo->certificate, pCertInfo->certLength); + SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + pCertInfo->certLength = readCount; + } + else if (encodingType == _CERT_ENC_TYPE_BASE64) + { + int certLen = _Base64::GetEncodedSize(pCertInfo->certLength); + memset(pCertInfo->certificate + pCertInfo->certLength, 0, sizeof(pCertInfo->certificate) - pCertInfo->certLength); + r = _Base64::Encode(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength, reinterpret_cast< char* >(pCertInfo->certificate), certLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + pCertInfo->certLength = certLen; + } + pCertInfo->certId = certRecord.certId; + pCertInfo->certFormat = (_CertFormat) certRecord.certFormat; + pCertInfo->certType = _CERT_TYPE_USER_CERT; + + if (certRecord.prvKeyLen > 0) + { + pPriKey = std::unique_ptr <_CertPrivateKeyInfo> (new (std::nothrow) _CertPrivateKeyInfo()); + SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + std::unique_ptr pPrivateKey (new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]); + SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE); + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle."); + + r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen); + if (!IsFailed(r) && priKeyLen != 0) + { + pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get()); + + pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER; + + priKeyLen = 0; + + pPrivateKey.reset(null); + + pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0); + SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pPrivateKey = std::unique_ptr(pPrivateTempKey); + + if (encodingType == _CERT_ENC_TYPE_PEM) + { + BIO_free(pBio); + + pBio = BIO_new(BIO_s_mem()); + SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pKeyBuffer = new (std::nothrow) byte[priKeyLen]; + SysTryCatch(NID_SEC_CERT, pKeyBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memcpy((void*) pKeyBuffer, pPrivateKey.get(), priKeyLen); + keyBufferLen = priKeyLen; + + pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, keyBufferLen); + SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed"); + + PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null); + + readCount = BIO_read(pBio, pCertInfo->privatekey, pCertInfo->privateKeyLen); + SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed"); + + pCertInfo->privateKeyLen = readCount; + } + else if (encodingType == _CERT_ENC_TYPE_BASE64) + { + pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen); + memset(pCertInfo->privatekey, 0, sizeof(pCertInfo->privatekey)); + r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertInfo->privatekey), pCertInfo->privateKeyLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding."); + + } + else + { + memcpy(pCertInfo->privatekey, pPrivateKey.get(), priKeyLen); + pCertInfo->privateKeyLen = priKeyLen; + } + } + } + + *ppUserCertInfo = pCertInfo.release(); + +CATCH: + + if (encodingType == _CERT_ENC_TYPE_PEM) + { + BIO_free(pBio); + X509_free(pCert); + EVP_PKEY_free(pKey); + } + + { + } + return r; +} + + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertDbManager.h b/src/security/cert/FSecCert_CertDbManager.h new file mode 100755 index 0000000..173fcd4 --- /dev/null +++ b/src/security/cert/FSecCert_CertDbManager.h @@ -0,0 +1,127 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertDbManager.h + * @brief This header file contains the declarations of X509 Certificate interface layer. + * + * This header file contains the declarations of X509 Certificate interface layer. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_DB_MANAGER_H_ +#define _FSEC_CERT_INTERNAL_CERT_DB_MANAGER_H_ + +#include "FSecCert_CertTypes.h" +#include "FSecCert_CertDbStore.h" +#include "FSecCert_CertChain.h" +#include "FSecCert_CertPrivateKeyInfo.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertDbManager +{ +public: + static _CertDbManager* GetInstance(void); + + bool IsCertificateTablesCreated(void); + + result RemoveCaCertificateByType(_CaCertType certType); + + result RemoveUserCaCertificateByCertId(int certId); + + result RemoveUserCertificateByCertId(int certId); + + result RemoveAllUserCertificate(void); + + result CreateCertificateTables(void); + + result ResetCertificateTables(void); + + result RemoveCertificateTables(void); + + result RemoveCertificateChainByCertId(int certId); + + result InsertDefaultCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen); + + result InsertCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen, bool checkValidity = true); + + result UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen); + + result RemoveCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen); + + result GetCaCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId, _CaCertType certType = _CERT_TYPE_NOT_BOUNDED); + + result GetUserCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId); + + result GetCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count); + + result GetUserCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count); + + result GetCaCertificateListByCertId(int certId, _CertificateListInfo** ppCertList); + + result FindIssuerCertificateAndTypeN(_CertFormat certFormat, char* pIssuerName, byte** ppCert, int& certLen, _CaCertType& certType); + + result FindIssuerCertificateByTypeN(_CertFormat certFormat, _CaCertType certType, char* pIssuerName, byte** ppCert, int& certLen); + + result FindCertType(_CertFormat certFormat, char* pIssuerName, char* pSubjectName, _CaCertType* pCertType); + + result GetUserCertificateListByCertId(int certId, _CertificateListInfo** ppCertList); + + result GetHashOfCertFile(byte* pFilePath, int* pLen, char* pBuf); + + result InsertCertChain(_CertFormat certFormat, _CertChain* pCertChain); + + result InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo = null); + + result InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa = 0); + + result GetUserCertificateChain(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subjectNameLen, _CertEncodingType encodingType, _CertificateListInfo** ppCertListInfoTypes); + + result GetUserCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo, char* pSubjectName = null); + + result GetUserCertificateInfoByCertId(int pCertId, int* pSubjectLength, byte* pSubjectName, int* pIssuerLength, byte* pIssuerName); + + result GetUserCertificateInfoByCertId(int certId, _CertEncodingType encodingType, _CertInfo** ppUserCertInfo); + +private: + result DeleteCertificateChain(int devCertId, int devParentCa); + + result DeleteCertificateByIdNTableName(int certId, Tizen::Base::String tableName); + + _CertDbManager(void); + + virtual ~_CertDbManager(void); + + _CertDbManager(const _CertDbManager& rhs); + + _CertDbManager& operator =(const _CertDbManager& rhs); + + static void Construct(void); + + +private: + _CaCertDbStore __caCertDbStore; + _UserCertDbStore __userCertDbStore; + + static _CertDbManager* __pCertDb; + +}; // _CertDbManager + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_DB_MANAGER_H_ diff --git a/src/security/cert/FSecCert_CertDbStore.cpp b/src/security/cert/FSecCert_CertDbStore.cpp new file mode 100755 index 0000000..3a79cfb --- /dev/null +++ b/src/security/cert/FSecCert_CertDbStore.cpp @@ -0,0 +1,1674 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertDbStore.cpp + * @brief This file contains implementation of X509 Certificate Database. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertDbStore.h" +#include "FSecCert_Base64.h" + +using namespace Tizen::Io; +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Cert +{ + +_CertDbStore::_CertDbStore(void) +{ + __rootCaCertTableCreated = Database::Exists(_CERT_ROOT_CA_CERT_TABLE); + __userCertTableCreated = Database::Exists(_CERT_USER_CERT_TABLE); +} + +_CertDbStore::~_CertDbStore(void) +{ + //Empty body +} + +result +_CertDbStore::IsRootCaCertTableCreated(void) +{ + if(!Database::Exists(_CERT_ROOT_CA_CERT_TABLE)) + { + return E_SYSTEM; + } + + return E_SUCCESS; +} + +result +_CertDbStore::IsUserCertTableCreated(void) +{ + if(!Database::Exists(_CERT_USER_CERT_TABLE)) + { + return E_SYSTEM; + } + + return E_SUCCESS; + +} + +result +_CertDbStore::CreateCertificateTables(void) +{ + result r = E_SUCCESS; + String sql; + String sql2; + std::unique_ptr< Database > pRootCaDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pRootCaDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pRootCaDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + sql.Append(L"CREATE TABLE IF NOT EXISTS rootcert (\ + certId INTEGER PRIMARY KEY AUTOINCREMENT,\ + certType SMALLINT DEFAULT 0,\ + certFormat SMALLINT DEFAULT 0,\ + fileName VARCHAR,\ + subjectNameLen SMALLINT DEFAULT 20,\ + subjectName VARCHAR,\ + issuerNameLen SMALLINT DEFAULT 20,\ + issuerName VARCHAR,\ + parentCa SMALLINT,\ + installed VARCHAR,\ + serialNo VARCHAR,\ + serialNoLen SMALLINT DEFAULT 20)"); + + r = pRootCaDatabase->ExecuteSql(sql, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql.", GetErrorMessage(r)); + + std::unique_ptr< Database > pUserCertDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pUserCertDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pUserCertDatabase->Construct(_CERT_USER_CERT_TABLE, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create certificate table. ", GetErrorMessage(r)); + + // Create a database table + sql2.Append(L"CREATE TABLE IF NOT EXISTS usercert (\ + certId INTEGER PRIMARY KEY AUTOINCREMENT,\ + certPubKeyHash VARCHAR DEFAULT null,\ + certFormat SMALLINT DEFAULT 0,\ + fileName VARCHAR,\ + subjectNameLen SMALLINT DEFAULT 20,\ + subjectName VARCHAR,\ + issuerNameLen SMALLINT DEFAULT 20,\ + issuerName VARCHAR,\ + prvKeyPath VARCHAR DEFAULT null,\ + prvKeyLen SMALLINT DEFAULT 0,\ + parentCa SMALLINT DEFAULT 0,\ + installed VARCHAR,\ + serialNo VARCHAR,\ + serialNoLen SMALLINT DEFAULT 20)"); + + r = pUserCertDatabase->ExecuteSql(sql2, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql.", GetErrorMessage(r)); + + return r; +} + +result +_CertDbStore::DeleteCaCertFiles(void) +{ + result r = E_SUCCESS; + String strVal; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create certificate table.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(L"SELECT * from rootcert")); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "Failed to get data."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetStringAt(3, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get string.", GetErrorMessage(r)); + Tizen::Io::File::Remove(strVal); + } + + return r; +} + +result +_CertDbStore::DeleteUserCertFiles(void) +{ + result r = E_SUCCESS; + Database database; + String strVal; + + r = database.Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to open user cert database.", GetErrorMessage(r)); + + std::unique_ptr< DbEnumerator > pEnum(database.QueryN(L"SELECT * from usercert")); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "Failed to find any user certificate in database."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetStringAt(3, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get string.", GetErrorMessage(r)); + Tizen::Io::File::Remove(strVal); + } + + return r; +} + +result +_CertDbStore::DropCertificateTables(void) +{ + result r = E_SUCCESS; + Database database; + + r = Database::Delete(_CERT_ROOT_CA_CERT_TABLE); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to delete CA table.", GetErrorMessage(r)); + + r = Database::Delete(_CERT_USER_CERT_TABLE); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to delete user table.", GetErrorMessage(r)); + + //Remove root certificates from the file system + DeleteCaCertFiles(); + + return r; +} + +result +_CertDbStore::RemoveCertificateById(int certId) +{ + return E_FAILURE; +} + +result +_CertDbStore::RemoveAllCertificates(void) +{ + return E_FAILURE; +} + +result +_CertDbStore::GetNumberOfCertificates(int& count) +{ + return E_FAILURE; +} + + +_CaCertDbStore::_CaCertDbStore(void) +{ +} + +_CaCertDbStore::~_CaCertDbStore(void) +{ +} + +result +_CaCertDbStore::InsertCaCertificate(CaCertRecord* pCertRecord) +{ + result r = E_SUCCESS; + byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + byte base64SerialNum[_MAX_SERIAL_NUMBER_SIZE] = {0, }; + int subjectNameBase64Len = 0; + int base64IssuerNameLen = 0; + int base64SerialNumLen = 0; + String statement; + + SysTryReturnResult(NID_SEC_CERT, pCertRecord != null, E_INVALID_ARG, "Invalid input parameter."); + + memcpy(subjectNameBase64, pCertRecord->subjectName, pCertRecord->subjectNameLen); + memcpy(issuerNameBase64, pCertRecord->issuerName, pCertRecord->issuerNameLen); + memcpy(base64SerialNum, pCertRecord->serialNo, _MAX_SERIAL_NUMBER_SIZE); + memset(pCertRecord->subjectName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memset(pCertRecord->issuerName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memset(pCertRecord->serialNo, 0, _MAX_SERIAL_NUMBER_SIZE); + + subjectNameBase64Len = _Base64::GetEncodedSize(pCertRecord->subjectNameLen); + memset(pCertRecord->subjectName, 0, sizeof(pCertRecord->subjectName)); + r = _Base64::Encode(static_cast< byte* >(subjectNameBase64), pCertRecord->subjectNameLen, pCertRecord->subjectName, subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode subject name of certificate."); + + pCertRecord->subjectNameLen = subjectNameBase64Len; + + base64IssuerNameLen = _Base64::GetEncodedSize(pCertRecord->issuerNameLen); + memset(pCertRecord->issuerName, 0, sizeof(pCertRecord->issuerName)); + r = _Base64::Encode(static_cast< byte* >(issuerNameBase64), pCertRecord->issuerNameLen, pCertRecord->issuerName, base64IssuerNameLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode issuer name of certificate."); + + pCertRecord->issuerNameLen = base64IssuerNameLen; + + base64SerialNumLen = _Base64::GetEncodedSize(pCertRecord->serialNoLen); + memset(pCertRecord->serialNo, 0, sizeof(pCertRecord->serialNo)); + r = _Base64::Encode(static_cast< byte* >(base64SerialNum), pCertRecord->serialNoLen, pCertRecord->serialNo, base64SerialNumLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode serial number of certificate."); + + pCertRecord->serialNoLen = base64SerialNumLen; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Begin transaction failed.", GetErrorMessage(r)); + + statement.Append(L"INSERT INTO rootcert (certId, certType, certFormat, fileName, subjectNameLen, subjectName, issuerNameLen, issuerName, parentCa, installed, serialNo, serialNoLen) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)"); + + std::unique_ptr< DbStatement > pStmt(pDatabase->CreateStatementN(statement)); + + r = pStmt->BindInt(1, pCertRecord->certType); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 1 in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(2, pCertRecord->certFormat); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 2 in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(3, pCertRecord->fileName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 3 in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(4, pCertRecord->subjectNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 4 in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(5, pCertRecord->subjectName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 5 in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(6, pCertRecord->issuerNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 6 in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(7, pCertRecord->issuerName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 7 in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(8, pCertRecord->parentCa); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 8 in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(9, pCertRecord->installed); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 9 in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(10, pCertRecord->serialNo); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 10 in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(11, pCertRecord->serialNoLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun 11 in database statement.", GetErrorMessage(r)); + + std::unique_ptr< DbEnumerator > pEnum(pDatabase->ExecuteStatementN(*pStmt)); + AppAssert(!pEnum); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Commit transaction failed.", GetErrorMessage(r)); + + return r; +} + +result +_CaCertDbStore::UpdateCaCertificate(CaCertRecord* pCertRecord, CaCertRecord* pUpdateCertRecord) +{ + result r = E_SUCCESS; + String statement(_MAX_QUERY_LEN); + int subjectNameBase64Len = 0; + int base64IssuerNameLen = 0; + byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + + SysTryReturnResult(NID_SEC_CERT, !(pCertRecord == null || pUpdateCertRecord == null), E_INVALID_ARG, "Invalid input parameter."); + + memcpy(subjectNameBase64, pCertRecord->subjectName, pCertRecord->subjectNameLen); + memcpy(issuerNameBase64, pCertRecord->issuerName, pCertRecord->issuerNameLen); + memset(pCertRecord->subjectName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memset(pCertRecord->issuerName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + + subjectNameBase64Len = _Base64::GetEncodedSize(pCertRecord->subjectNameLen); + memset(pCertRecord->subjectName, 0, sizeof(pCertRecord->subjectName)); + r = _Base64::Encode(static_cast< byte* >(subjectNameBase64), pCertRecord->subjectNameLen, pCertRecord->subjectName, subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode subject name of certificate."); + + pCertRecord->subjectNameLen = subjectNameBase64Len; + + base64IssuerNameLen = _Base64::GetEncodedSize(pCertRecord->issuerNameLen); + memset(pCertRecord->issuerName, 0, sizeof(pCertRecord->issuerName)); + r = _Base64::Encode(static_cast< byte* >(issuerNameBase64), pCertRecord->issuerNameLen, pCertRecord->issuerName, base64IssuerNameLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode issuer name of certificate."); + + pCertRecord->issuerNameLen = base64IssuerNameLen; + + memset(subjectNameBase64, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memset(issuerNameBase64, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + subjectNameBase64Len = 0; + base64IssuerNameLen = 0; + memcpy(subjectNameBase64, pUpdateCertRecord->subjectName, pUpdateCertRecord->subjectNameLen); + memcpy(issuerNameBase64, pUpdateCertRecord->issuerName, pUpdateCertRecord->issuerNameLen); + memset(pUpdateCertRecord->subjectName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memset(pUpdateCertRecord->issuerName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + + subjectNameBase64Len = _Base64::GetEncodedSize(pUpdateCertRecord->subjectNameLen); + memset(pCertRecord->subjectName, 0, sizeof(pCertRecord->subjectName)); + r = _Base64::Encode(static_cast< byte* >(subjectNameBase64), pUpdateCertRecord->subjectNameLen, pUpdateCertRecord->subjectName, subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode subject name of certificate."); + + pUpdateCertRecord->subjectNameLen = subjectNameBase64Len; + + base64IssuerNameLen = _Base64::GetEncodedSize(pUpdateCertRecord->issuerNameLen); + memset(pCertRecord->issuerName, 0, sizeof(pCertRecord->issuerName)); + r = _Base64::Encode(static_cast< byte* >(issuerNameBase64), pUpdateCertRecord->issuerNameLen, pUpdateCertRecord->issuerName, base64IssuerNameLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode issuer name of certificate."); + + pUpdateCertRecord->issuerNameLen = base64IssuerNameLen; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Construct of update ca certificate failed.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"UPDATE rootcert SET subjectNameLen = %d, subjectName = '%s', issuerNameLen = %d, issuerName = '%s' WHERE subjectName = '%s' and issuerName = '%s' and certType = %d and certId = %d", pUpdateCertRecord->subjectNameLen, pUpdateCertRecord->subjectName, pUpdateCertRecord->issuerNameLen, pUpdateCertRecord->issuerName, pCertRecord->subjectName, pCertRecord->issuerName, pCertRecord->certType, pCertRecord->certId); + r = pDatabase->ExecuteSql(statement, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql.", GetErrorMessage(r)); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction .", GetErrorMessage(r)); + + return r; +} + +result +_CaCertDbStore::UpdateParentCa(int certId, int parentCa) +{ + result r = E_SUCCESS; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter certificate identifier."); + SysTryReturnResult(NID_SEC_CERT, parentCa > 0, E_INVALID_ARG, "Invalid input parameter parent certificate identifier."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"UPDATE rootcert SET parentCa = '%d' WHERE certId = '%d'", parentCa, certId); + r = pDatabase->ExecuteSql(statement, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql statement.", GetErrorMessage(r)); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction.", GetErrorMessage(r)); + + return r; +} + +result +_CaCertDbStore::RemoveCertificateBySubjectName(_CaCertType certType, byte* pSubjectName, int subjectNameLen) +{ + result r = E_SUCCESS; + char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + int subjectNameBase64Len = 0; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, !((pSubjectName == null) || (subjectNameLen <= 0) || (certType < _MIN_CERT_TYPE) || (certType > _MAX_CERT_TYPE)), + E_INVALID_ARG, "Invalid input parameter subjetname or invalid subject name length."); + + subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen); + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + r = _Base64::Encode(static_cast< byte* >(pSubjectName), subjectNameLen, subjectNameBase64, subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode subject name of certificate."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"DELETE FROM rootcert WHERE subjectName = '%s' and subjectNameLen = '%d' and certType = '%d'", subjectNameBase64, subjectNameBase64Len, certType); + + r = pDatabase->ExecuteSql(statement, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql statement.", GetErrorMessage(r)); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit tranction.", GetErrorMessage(r)); + + return r; +} + +result +_CaCertDbStore::RemoveCertificateByIssuerNameAndSerialNo(_CaCertType certType, byte* issuerName, int issuerNameLen, byte* serialNo) +{ + result r = E_SUCCESS;char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char base64SerialNum[_MAX_SERIAL_NUMBER_SIZE] = {0, }; + int base64IssuerNameLen = 0; + int base64SerialNoLen = 0; + int serialNoLen = 0; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, !((issuerName == null) || (issuerNameLen <= 0) || (serialNo == null) || (certType < _MIN_CERT_TYPE) || (certType > _MAX_CERT_TYPE)), + E_INVALID_ARG, "Invalid input parameter issuer name or length of issuer name."); + + base64IssuerNameLen = _Base64::GetEncodedSize(issuerNameLen); + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + r = _Base64::Encode(issuerName, issuerNameLen, issuerNameBase64, base64IssuerNameLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode issuer name of certificate."); + + serialNoLen = strlen(reinterpret_cast< const char* >(serialNo)); + + base64SerialNoLen = _Base64::GetEncodedSize(serialNoLen); + memset(base64SerialNum, 0, sizeof(base64SerialNum)); + r = _Base64::Encode(serialNo, serialNoLen, base64SerialNum, base64SerialNoLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode serial number of certificate."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"DELETE FROM rootcert WHERE issuerName = '%s' and issuerNameLen = '%d' and certType = '%d' and serialNo = '%s'", issuerNameBase64, base64IssuerNameLen, certType, base64SerialNum); + r = pDatabase->ExecuteSql(statement, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql statement.", GetErrorMessage(r)); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction.", GetErrorMessage(r)); + + return r; +} + +result +_CaCertDbStore::RemoveAllCertificateByCondition(byte* pCondition) +{ + result r = E_SUCCESS; + int curCertId = 0; + CaCertRecord certRecord = {0, }; + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Invalid input parameter."); + + r = GetNextRecordByCondition(pCondition, &certRecord, curCertId); + + while (!IsFailed(r)) + { + curCertId = certRecord.certId; + + r = _CaCertDbStore::RemoveCertificateById(certRecord.certId); + if (!IsFailed(r)) + { + Tizen::Io::File::Remove(certRecord.fileName); + } + + r = GetNextRecordByCondition(pCondition, &certRecord, curCertId); + + } + + return E_SUCCESS; +} + +result +_CaCertDbStore::CheckDuplicateCertificate(_CaCertType certType, byte* pSubjectName, int subjectNameLen) +{ + result r = E_SUCCESS;char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + int subjectNameBase64Len = 0; + String statement; + String query; + + SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input parameter subject name."); + SysTryReturnResult(NID_SEC_CERT, subjectNameLen >= 0, E_INVALID_ARG, "Invalid input parameter subject name length."); + SysTryReturnResult(NID_SEC_CERT, certType >= _MIN_CERT_TYPE, E_INVALID_ARG, "Invalid input parameter certificate identifier(value less than minimum index)."); + SysTryReturnResult(NID_SEC_CERT, certType <= _MAX_CERT_TYPE, E_INVALID_ARG, "Invalid input parameter certificate identifier(value greater than maximim index)."); + + subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen); + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + r = _Base64::Encode(static_cast< byte* >(pSubjectName), subjectNameLen, subjectNameBase64, subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode subject name of certificate."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * from rootcert where certType = '%d' and subjectName = '%s' and subjectNameLen = '%d'", certType, subjectNameBase64, subjectNameBase64Len); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + if(pEnum == null) + { + return E_DATA_NOT_FOUND; + } + + return r; +} + +result +_CaCertDbStore::CheckDuplicateCertificate(_CaCertType certType, byte* issuerName, int issuerNameLen, byte* pSerialNumber) +{ + result r = E_SUCCESS;char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char base64SerialNo[_MAX_SERIAL_NUMBER_SIZE] = {0, }; + int base64IssuerNameLen = 0; + int base64SerialNoLen = 0; + int serialNoLen = 0; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, issuerName != null, E_INVALID_ARG, "Invalid input parameter issuer name."); + SysTryReturnResult(NID_SEC_CERT, issuerNameLen >= 0, E_INVALID_ARG, "Invalid input parameter issuer name length."); + SysTryReturnResult(NID_SEC_CERT, pSerialNumber != null, E_INVALID_ARG, "Invalid input parameter serial number."); + SysTryReturnResult(NID_SEC_CERT, certType >= _MIN_CERT_TYPE, E_INVALID_ARG, "Invalid input parameter certificate identifier (value is less than minimum index)."); + SysTryReturnResult(NID_SEC_CERT, certType <= _MAX_CERT_TYPE, E_INVALID_ARG, "Invalid input parameter certificate identifier (value is greater than maximum index)."); + + base64IssuerNameLen = _Base64::GetEncodedSize(issuerNameLen); + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + r = _Base64::Encode(issuerName, issuerNameLen, issuerNameBase64, base64IssuerNameLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode issuer name of certificate."); + + serialNoLen = strlen(reinterpret_cast< const char* >(pSerialNumber)); + + base64SerialNoLen = _Base64::GetEncodedSize(serialNoLen); + memset(base64SerialNo, 0, sizeof(base64SerialNo)); + r = _Base64::Encode(pSerialNumber, serialNoLen, base64SerialNo, base64SerialNoLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode serial number of certificate."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM rootcert WHERE certType = '%d' AND issuerName = '%s' AND issuerNameLen = '%d' AND serialNo = '%s'", certType, issuerNameBase64, base64IssuerNameLen, base64SerialNo); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in databas."); + + return r; +} + +result +_CaCertDbStore::GetFirstRecordByConditions(byte* pCondition, CaCertRecord* pCertRecord) +{ + result r = E_SUCCESS; + String statement(_MAX_QUERY_LEN); + ByteBuffer* pTempBuf = null; + char tmpName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + String strVal; + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, pCertRecord != null, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM rootcert WHERE %s ORDER BY certId", pCondition); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + r = pEnum->MoveNext(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to move next.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(0, pCertRecord->certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 0.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(1, pCertRecord->certType); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 1.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(2, pCertRecord->certFormat); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 2.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(3, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 3.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); //check this + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->fileName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->fileName[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(4, pCertRecord->subjectNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 4.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(5, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 5.", GetErrorMessage(r)); + + memset(tmpName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(tmpName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pCertRecord->subjectNameLen); + _Base64::Decode(tmpName, pCertRecord->subjectNameLen, reinterpret_cast< byte* >(pCertRecord->subjectName), pCertRecord->subjectNameLen); + + r = pEnum->GetIntAt(6, pCertRecord->issuerNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 6.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(7, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 7.", GetErrorMessage(r)); + + memset(tmpName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(tmpName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pCertRecord->issuerNameLen); + _Base64::Decode(tmpName, pCertRecord->issuerNameLen, reinterpret_cast< byte* >(pCertRecord->issuerName), pCertRecord->issuerNameLen); + + r = pEnum->GetIntAt(8, pCertRecord->parentCa); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 8.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(9, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 9.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->installed, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->installed[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetStringAt(10, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 10.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(11, pCertRecord->serialNoLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 11.", GetErrorMessage(r)); + + memset(tmpName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(tmpName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + _Base64::Decode(tmpName, pCertRecord->serialNoLen, reinterpret_cast< byte* >(pCertRecord->serialNo), pCertRecord->serialNoLen); + + return r; +} + +result +_CaCertDbStore::GetNextRecordByCondition(byte* pCondition, CaCertRecord* pCertRecord, int curCertId) +{ + result r = E_SUCCESS; + String statement(_MAX_QUERY_LEN); + ByteBuffer* pTempBuf = null; + String strVal; + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, pCertRecord != null, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM rootcert WHERE %s AND certId > '%d' ORDER BY certId", pCondition, curCertId); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + if(pEnum == null) + { + return E_DATA_NOT_FOUND; + } + + r = pEnum->MoveNext(); + r = pEnum->GetIntAt(0, pCertRecord->certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 0.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(1, pCertRecord->certType); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 1.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(2, pCertRecord->certFormat); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 2.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(3, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 3."); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->fileName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->fileName[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(4, pCertRecord->subjectNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 4.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(5, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 5.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->subjectName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->subjectName[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(6, pCertRecord->issuerNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 6.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(7, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 7.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->issuerName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->issuerName[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(8, pCertRecord->parentCa); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 8.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(9, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 9.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->installed, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->installed[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetStringAt(10, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 10.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->serialNo, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->serialNo[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(11, pCertRecord->serialNoLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database of column 11.", GetErrorMessage(r)); + + return r; +} + +result +_CaCertDbStore::GetCurrentCertId(int& curCertId) +{ + result r = E_SUCCESS; + int certId = 0; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + std::unique_ptr pEnum(pDatabase->QueryN("SELECT seq FROM sqlite_sequence")); + if(pEnum == null) + { + return E_DATA_NOT_FOUND; + } + + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetIntAt(0, certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database.", GetErrorMessage(r)); + } + curCertId = certId; + + return r; +} + +result +_CaCertDbStore::CheckIfSameParent(int certId) +{ + result r = E_SUCCESS; + int curCertId = 0; + int count = 0; + String statement; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM rootcert where parentCa = %d ORDER BY certId", certId); + + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetIntAt(0, curCertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database.", GetErrorMessage(r)); + count++; + } + + SysTryReturnResult(NID_SEC_CERT, count > 1, E_SYSTEM, "Failed to get record."); + + return r; +} + +result +_CaCertDbStore::SelectCaCertificateBycertId(int certId, CaCertRecord* pCertRecord) +{ + byte condition[_MAX_TYPE_CONST_SIZE] = {0, }; + + return _CaCertDbStore::GetNextRecordByCondition(static_cast< byte* >(condition), pCertRecord, certId); + +} + +result +_CaCertDbStore::RemoveCertificateById(int certId) +{ + result r = E_SUCCESS; + String statement; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Append(L"DELETE FROM rootcert WHERE certId = ?"); + std::unique_ptr< DbStatement > pStmt(pDatabase->CreateStatementN(statement)); + SysTryReturn(NID_SEC_CERT, pStmt != null, r, r, "[%s] Failed to create statement.", GetErrorMessage(r)); + + r = pStmt->BindInt(0, certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + + pDatabase->ExecuteStatementN(*pStmt); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction.", GetErrorMessage(r)); + + return r; +} + +result +_CaCertDbStore::RemoveAllCertificates(void) +{ + result r = E_SUCCESS; + String statement; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Append(L"DELETE from rootcert"); + + r = pDatabase->ExecuteSql(statement, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql.", GetErrorMessage(r)); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction.", GetErrorMessage(r)); + + return r; +} + +result +_CaCertDbStore::GetNumberOfCertificates(int& count) +{ + result r = E_SUCCESS; + + String statement; + int certCount = 0; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_ROOT_CA_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Append(L"SELECT * FROM rootcert"); + std::unique_ptr< DbStatement > pStmt(pDatabase->CreateStatementN(statement)); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->ExecuteStatementN(*pStmt)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + certCount++; + } + + count = certCount; + + return r; +} + +_UserCertDbStore::_UserCertDbStore(void) +{ +} + +_UserCertDbStore::~_UserCertDbStore(void) +{ +} + +result +_UserCertDbStore::InsertUserCertificate(UserCertRecord* pCertRecord) +{ + result r = E_SUCCESS; + byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + byte base64SerialNum[_MAX_SERIAL_NUMBER_SIZE] = {0, }; + int subjectNameBase64Len = 0; + int base64IssuerNameLen = 0; + int base64SerialNumLen = 0; + String statement; + + SysTryReturnResult(NID_SEC_CERT, pCertRecord != null, E_INVALID_ARG, "Invalid input parameter."); + + memcpy(subjectNameBase64, pCertRecord->subjectName, pCertRecord->subjectNameLen); + memcpy(issuerNameBase64, pCertRecord->issuerName, pCertRecord->issuerNameLen); + memcpy(base64SerialNum, pCertRecord->serialNo, _MAX_SERIAL_NUMBER_SIZE); + memset(pCertRecord->subjectName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memset(pCertRecord->issuerName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memset(pCertRecord->serialNo, 0, _MAX_SERIAL_NUMBER_SIZE); + + subjectNameBase64Len = _Base64::GetEncodedSize(pCertRecord->subjectNameLen); + memset(pCertRecord->subjectName, 0, sizeof(pCertRecord->subjectName)); + r = _Base64::Encode(static_cast< byte* >(subjectNameBase64), pCertRecord->subjectNameLen, pCertRecord->subjectName, subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode subject name of certificate."); + + pCertRecord->subjectNameLen = subjectNameBase64Len; + + base64IssuerNameLen = _Base64::GetEncodedSize(pCertRecord->issuerNameLen); + memset(pCertRecord->issuerName, 0, sizeof(pCertRecord->issuerName)); + r = _Base64::Encode(static_cast< byte* >(issuerNameBase64), pCertRecord->issuerNameLen, pCertRecord->issuerName, base64IssuerNameLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode issuer name of certificate."); + + pCertRecord->issuerNameLen = base64IssuerNameLen; + + base64SerialNumLen = _Base64::GetEncodedSize(pCertRecord->serialNoLen); + memset(pCertRecord->serialNo, 0, sizeof(pCertRecord->serialNo)); + r = _Base64::Encode(static_cast< byte* >(base64SerialNum), pCertRecord->serialNoLen, pCertRecord->serialNo, base64SerialNumLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode serial number of certificate."); + + pCertRecord->serialNoLen = base64SerialNumLen; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "Failed to construct database instance."); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Append(L"INSERT INTO usercert (certId, certPubKeyHash, certFormat, fileName, subjectNameLen, subjectName, issuerNameLen, issuerName, prvKeyPath, prvKeyLen, parentCa, installed, serialNo, serialNoLen) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)"); + std::unique_ptr< DbStatement > pStmt(pDatabase->CreateStatementN(statement)); + r = pStmt->BindString(1, pCertRecord->certPubKeyHash); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(2, pCertRecord->certFormat); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(3, pCertRecord->fileName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(4, pCertRecord->subjectNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(5, pCertRecord->subjectName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(6, pCertRecord->issuerNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(7, pCertRecord->issuerName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(8, pCertRecord->prvKeyPath); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(9, pCertRecord->prvKeyLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(10, pCertRecord->parentCa); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(11, pCertRecord->installed); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindString(12, pCertRecord->serialNo); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + r = pStmt->BindInt(13, pCertRecord->serialNoLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->ExecuteStatementN(*pStmt)); + AppAssert(!pEnum); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction.", GetErrorMessage(r)); + + return r; +} + +result +_UserCertDbStore::UpdateParentCa(int certId, int parentCa) +{ + result r = E_SUCCESS; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, parentCa > 0, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"UPDATE usercert SET parentCa = '%d' WHERE certId = '%d'", parentCa, certId); + r = pDatabase->ExecuteSql(statement, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql.", GetErrorMessage(r)); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction.", GetErrorMessage(r)); + + return r; +} + +result +_UserCertDbStore::UpdateRecordByCondition(byte* pCondition) +{ + result r = E_SUCCESS; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"UPDATE usercert SET %s", pCondition); + + r = pDatabase->ExecuteSql(statement, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql statement.", GetErrorMessage(r)); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transactoin.", GetErrorMessage(r)); + + return r; +} + +result +_UserCertDbStore::RemoveCertificateByCondition(byte* pCondition) +{ + result r = E_SUCCESS; + + + int curCertId = 0; + String statement(_MAX_QUERY_LEN); + String strVal; + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM usercert WHERE %s ORDER BY certId", pCondition); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + + while (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetIntAt(0, curCertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database.", GetErrorMessage(r)); + + r = _UserCertDbStore::RemoveCertificateById(curCertId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to delete record from database.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(4, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database.", GetErrorMessage(r)); + + Tizen::Io::File::Remove(strVal); + } + + return r; +} + +result +_UserCertDbStore::CheckDuplicateCertificate(byte* pSubjectName, int subjectNameLen) +{ + result r = E_SUCCESS; + char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + int subjectNameBase64Len = 0; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, subjectNameLen > 0, E_INVALID_ARG, "Invalid input parameter."); + + subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen); + memset(subjectNameBase64, 0, sizeof(subjectNameBase64)); + r = _Base64::Encode(static_cast< byte* >(pSubjectName), subjectNameLen, subjectNameBase64, subjectNameBase64Len); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode subject name of certificate."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM usercert WHERE subjectName = '%s' AND subjectNameLen = '%d'", subjectNameBase64, subjectNameBase64Len); + + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + return r; +} + +result +_UserCertDbStore::CheckDuplicateCertificate(byte* pIssuerName, int issuerNameLen, byte* pSerialNumber) +{ + result r = E_SUCCESS; + char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char base64SerialNo[_MAX_SERIAL_NUMBER_SIZE] = {0, }; + int base64IssuerNameLen = 0; + int base64SerialNoLen = 0; + int serialNoLen = 0; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invald input parameter"); + SysTryReturnResult(NID_SEC_CERT, issuerNameLen >= 0, E_INVALID_ARG, "Invald input parameter"); + SysTryReturnResult(NID_SEC_CERT, pSerialNumber != null, E_INVALID_ARG, "Invald input parameter"); + + base64IssuerNameLen = _Base64::GetEncodedSize(issuerNameLen); + memset(issuerNameBase64, 0, sizeof(issuerNameBase64)); + r = _Base64::Encode(pIssuerName, issuerNameLen, issuerNameBase64, base64IssuerNameLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode issuer name of certificate."); + + serialNoLen = strlen(reinterpret_cast< const char* >(pSerialNumber)); + + base64SerialNoLen = _Base64::GetEncodedSize(serialNoLen); + memset(base64SerialNo, 0, sizeof(base64SerialNo)); + r = _Base64::Encode(pSerialNumber, serialNoLen, base64SerialNo, base64SerialNoLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode serial number of certificate."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM usercert WHERE issuerName = '%s' AND issuerNameLen = '%d' AND serialNo = '%s'", issuerNameBase64, base64IssuerNameLen, base64SerialNo); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + return r; +} + +result +_UserCertDbStore::GetFirstRecordByConditions(byte* pCondition, UserCertRecord* pCertRecord) +{ + result r = E_SUCCESS; + String statement(_MAX_QUERY_LEN); + ByteBuffer* pTempBuf = null; + char tmpName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + int len = 0; + String strVal; + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Invalid input parameter"); + SysTryReturnResult(NID_SEC_CERT, pCertRecord != null, E_INVALID_ARG, "Invalid input parameter"); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM usercert WHERE %s", pCondition); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturn(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, E_DATA_NOT_FOUND, "No certificate found in database."); + + + r = pEnum->MoveNext(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(0, pCertRecord->certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 0.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(1, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 1.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->certPubKeyHash, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->certPubKeyHash[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(2, pCertRecord->certFormat); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 2.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(3, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 3.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->fileName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->fileName[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(4, pCertRecord->subjectNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 4.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(5, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 5.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memset(tmpName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memcpy(tmpName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + _Base64::Decode(tmpName, pCertRecord->subjectNameLen, reinterpret_cast< byte* >(pCertRecord->subjectName), pCertRecord->subjectNameLen); + + r = pEnum->GetIntAt(6, pCertRecord->issuerNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 6.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(7, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 7.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + + memset(tmpName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memcpy(tmpName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + _Base64::Decode(tmpName, pCertRecord->issuerNameLen, reinterpret_cast< byte* >(pCertRecord->issuerName), pCertRecord->issuerNameLen); + + r = pEnum->GetStringAt(8, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 8.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + if (pTempBuf) + { + memcpy(pCertRecord->prvKeyPath, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + } + else + { + memset(pCertRecord->prvKeyPath, 0, _MAX_PRV_KEY_PATH_SIZE_SIZE); + } + + r = pEnum->GetIntAt(9, pCertRecord->prvKeyLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 9.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(10, pCertRecord->parentCa); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 10.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(11, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 11.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->installed, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->installed[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetStringAt(12, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 12.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memset(tmpName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE); + memcpy(tmpName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + + len = pTempBuf->GetRemaining(); + _Base64::Decode(tmpName, len, reinterpret_cast< byte* >(pCertRecord->serialNo), len); + + r = pEnum->GetIntAt(13, pCertRecord->serialNoLen); + pCertRecord->serialNoLen = _Base64::GetDecodedSize(pCertRecord->serialNoLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 13.", GetErrorMessage(r)); + + return r; +} + +result +_UserCertDbStore::GetNextRecordByCondition(byte* pCondition, UserCertRecord* pCertRecord, int curCertId) +{ + result r = E_SUCCESS; + String statement(_MAX_QUERY_LEN); + ByteBuffer* pTempBuf = null; + String strVal; + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Input parameters are invalid"); + SysTryReturnResult(NID_SEC_CERT, pCertRecord != null, E_INVALID_ARG, "Input parameters are invalid"); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM usercert WHERE %s AND certId > '%d'", pCondition, curCertId); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + r = pEnum->MoveNext(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(0, pCertRecord->certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 0.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(1, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 1.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->certPubKeyHash, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->certPubKeyHash[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(2, pCertRecord->certFormat); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 2.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(3, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 3.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->fileName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->fileName[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(4, pCertRecord->subjectNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 4.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(5, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 5.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->subjectName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->subjectName[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(6, pCertRecord->issuerNameLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 6.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(7, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 7.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->issuerName, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->issuerName[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetStringAt(8, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 8.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + if (pTempBuf) + { + memcpy(pCertRecord->prvKeyPath, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + } + else + { + memset(pCertRecord->prvKeyPath, 0, _MAX_PRV_KEY_PATH_SIZE_SIZE); + } + + r = pEnum->GetIntAt(9, pCertRecord->prvKeyLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 9.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(10, pCertRecord->parentCa); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 10.", GetErrorMessage(r)); + + r = pEnum->GetStringAt(11, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 11.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->installed, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->installed[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetStringAt(12, strVal); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 12.", GetErrorMessage(r)); + + pTempBuf = Tizen::Base::Utility::StringUtil::StringToUtf8N(strVal); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, pTempBuf != null, r, r, "[%s] String to Utf8 function failed.", GetErrorMessage(r)); + + memcpy(pCertRecord->serialNo, reinterpret_cast< const char* >(pTempBuf->GetPointer()), pTempBuf->GetRemaining()); + pCertRecord->serialNo[pTempBuf->GetRemaining()] = '\0'; + + r = pEnum->GetIntAt(13, pCertRecord->serialNoLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database from column 13.", GetErrorMessage(r)); + + return r; +} + +result +_UserCertDbStore::GetCurrentCertId(int& curCertId) +{ + result r = E_SUCCESS; + int certId = 0; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + std::unique_ptr< DbEnumerator> pEnum(pDatabase->QueryN("SELECT seq FROM sqlite_sequence")); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + r = pEnum->MoveNext(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to move next.", GetErrorMessage(r)); + + r = pEnum->GetIntAt(0, certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database.", GetErrorMessage(r)); + + curCertId = certId; + + return r; +} + +result +_UserCertDbStore::GetCountByCondition(byte* pCondition, int& count) +{ + result r = E_SUCCESS; + int certCount = 0; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Input parameter are invalid"); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Construct fails.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT * FROM usercert WHERE %s", pCondition); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in Db."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + certCount++; + } + + count = certCount; + + return r; +} + +result +_UserCertDbStore::GetParentCaByCondition(byte* pCondition, int& parentCa) +{ + result r = E_SUCCESS; + int currParentCa = 0; + String statement(_MAX_QUERY_LEN); + + SysTryReturnResult(NID_SEC_CERT, pCondition != null, E_INVALID_ARG, "Input parameter are invalid"); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Format(_MAX_QUERY_LEN, L"SELECT parentCa FROM usercert WHERE %s", pCondition); + std::unique_ptr< DbEnumerator > pEnum(pDatabase->QueryN(statement)); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + if (pEnum->MoveNext() == E_SUCCESS) + { + r = pEnum->GetIntAt(10, currParentCa); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Unable to get data from database.", GetErrorMessage(r)); + } + + parentCa = currParentCa; + + return r; +} + +result +_UserCertDbStore::SelectUserCertificateBycertId(int certId, UserCertRecord* pCertRecord) +{ + byte condition[_MAX_TYPE_CONST_SIZE] = {0, }; + + return _UserCertDbStore::GetNextRecordByCondition(static_cast< byte* >(condition), pCertRecord, certId); + +} + +result +_UserCertDbStore::RemoveCertificateById(int certId) +{ + result r = E_SUCCESS; + String statement; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input certificate id."); + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Append(L"DELETE FROM usercert WHERE certId = ?"); + std::unique_ptr< DbStatement > pStmt(pDatabase->CreateStatementN(statement)); + SysTryReturn(NID_SEC_CERT, pStmt, GetLastResult(), GetLastResult(), "[%s] Failed to create statement.", GetErrorMessage(GetLastResult())); + + r = pStmt->BindInt(0, certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to bind colmun in database statement.", GetErrorMessage(r)); + + pDatabase->ExecuteStatementN(*pStmt); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction.", GetErrorMessage(r)); + + return r; +} + +result +_UserCertDbStore::RemoveAllCertificates(void) +{ + result r = E_SUCCESS; + String statement; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_WRITE, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + r = pDatabase->BeginTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to begin transaction.", GetErrorMessage(r)); + + statement.Append(L"DELETE from usercert"); + r = pDatabase->ExecuteSql(statement, true); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to execute sql.", GetErrorMessage(r)); + + r = pDatabase->CommitTransaction(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to commit transaction.", GetErrorMessage(r)); + + return r; +} + +result +_UserCertDbStore::GetNumberOfCertificates(int& count) +{ + result r = E_SUCCESS; + String statement; + int certCount = 0; + + std::unique_ptr< Database > pDatabase(new (std::nothrow) Database()); + SysTryReturnResult(NID_SEC_CERT, pDatabase != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + r = pDatabase->Construct(_CERT_USER_CERT_TABLE, DB_OPEN_READ_ONLY, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct database instance.", GetErrorMessage(r)); + + statement.Append(L"SELECT * FROM usercert"); + + std::unique_ptr< DbStatement > pStmt(pDatabase->CreateStatementN(statement)); + SysTryReturnResult(NID_SEC_CERT, pStmt != null, E_DATA_NOT_FOUND, "Failed to create statement for user certifcates."); + + std::unique_ptr< DbEnumerator > pEnum(pDatabase->ExecuteStatementN(*pStmt.get())); + SysTryReturnResult(NID_SEC_CERT, pEnum != null, E_DATA_NOT_FOUND, "No certificate found in database."); + + while (pEnum->MoveNext() == E_SUCCESS) + { + certCount++; + } + + count = certCount; + + return r; +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertDbStore.h b/src/security/cert/FSecCert_CertDbStore.h new file mode 100755 index 0000000..86bf753 --- /dev/null +++ b/src/security/cert/FSecCert_CertDbStore.h @@ -0,0 +1,205 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertDbStore.h + * @brief This header file contains the declarations of X509 Certificate Database. + * + * This header file contains the declarations of X509 Certificate Database. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_DB_STORE_H_ +#define _FSEC_CERT_INTERNAL_CERT_DB_STORE_H_ + +#include "FSecCert_CertTypes.h" +#include "FBaseString.h" +#include "FBaseByteBuffer.h" +#include "FBaseResult.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +struct CaCertRecord +{ + int certId; + int certType; + int certFormat; + char fileName[_MAX_CERTIFICATE_PATH_SIZE]; + int subjectNameLen; + char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE]; + int issuerNameLen; + char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE]; + int parentCa; + char installed[_MAX_TYPE_RECORD_SIZE]; + char serialNo[_MAX_SERIAL_NUMBER_SIZE]; + int serialNoLen; +}; //CaCertRecord + +struct UserCertRecord +{ + int certId; + char certPubKeyHash[_MAX_CERT_PUB_KEY_HASH_SIZE]; + int certFormat; + char fileName[_MAX_CERTIFICATE_PATH_SIZE]; + int subjectNameLen; + char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE]; + int issuerNameLen; + char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE]; + char prvKeyPath[_MAX_PRV_KEY_PATH_SIZE_SIZE]; + int prvKeyLen; + int parentCa; + char installed[_MAX_TYPE_RECORD_SIZE]; + char serialNo[_MAX_SERIAL_NUMBER_SIZE]; + int serialNoLen; +}; //UserCertRecord + +class _CertDbStore +{ +public: + _CertDbStore(void); + + virtual ~_CertDbStore(void); + + virtual result RemoveCertificateById(int certId); + + virtual result RemoveAllCertificates(void); + + virtual result GetNumberOfCertificates(int& count); + + result IsRootCaCertTableCreated(void); + + result IsUserCertTableCreated(void); + + result CreateCertificateTables(void); + + result DropCertificateTables(void); + + result DeleteCaCertFiles(void); + + result DeleteUserCertFiles(void); + +private: + _CertDbStore(const _CertDbStore& rhs); + + _CertDbStore& operator =(const _CertDbStore& rhs); + +private: + bool __rootCaCertTableCreated; + bool __userCertTableCreated; + +}; //_CertDbStore + +class _CaCertDbStore + : public _CertDbStore + , public Tizen::Base::Object +{ +public: + _CaCertDbStore(void); + + virtual ~_CaCertDbStore(void); + + result RemoveCertificateById(int certId); + + result RemoveAllCertificates(void); + + result GetNumberOfCertificates(int& count); + + result InsertCaCertificate(CaCertRecord* pCertRecord); + + result UpdateCaCertificate(CaCertRecord* pCertRecord, CaCertRecord* pUpdateCertRecord); + + result UpdateParentCa(int certId, int parentCa); + + result RemoveCertificateBySubjectName(_CaCertType certType, byte* pSubjectName, int subjectNameLen); + + result RemoveCertificateByIssuerNameAndSerialNo(_CaCertType certType, byte* pIssuerName, int issuerNameLen, byte* pSerialNo); + + result RemoveAllCertificateByCondition(byte* pCondition); + + result CheckDuplicateCertificate(_CaCertType certType, byte* pSubjectName, int subjectNameLen); + + result CheckDuplicateCertificate(_CaCertType certType, byte* pIssuerName, int issuerNameLen, byte* pSerialNumber); + + result GetFirstRecordByConditions(byte* pCondition, CaCertRecord* pCertRecord); + + result GetNextRecordByCondition(byte* pCondition, CaCertRecord* pCertRecord, int curCertId); + + result GetCurrentCertId(int& curCertId); + + result CheckIfSameParent(int certId); + + result SelectCaCertificateBycertId(int certId, CaCertRecord* pCertRecord); + +private: + _CaCertDbStore(const _CaCertDbStore& rhs); + + _CaCertDbStore& operator =(const _CaCertDbStore& rhs); + +}; //_CaCertDbStore + + +class _UserCertDbStore + : public _CertDbStore + , public Tizen::Base::Object +{ + +public: + _UserCertDbStore(void); + + virtual ~_UserCertDbStore(void); + + result RemoveCertificateById(int certId); + + result RemoveAllCertificates(void); + + result GetNumberOfCertificates(int& count); + + result InsertUserCertificate(UserCertRecord* pCertRecord); + + result UpdateParentCa(int certId, int parentCa); + + result UpdateRecordByCondition(byte* pCondition); + + result RemoveCertificateByCondition(byte* pCondition); + + result CheckDuplicateCertificate(byte* pSubjectName, int subjectNameLen); + + result CheckDuplicateCertificate(byte* pIssuerName, int issuerNameLen, byte* pSerialNumber); + + result GetFirstRecordByConditions(byte* pCondition, UserCertRecord* pCertRecord); + + result GetNextRecordByCondition(byte* pCondition, UserCertRecord* pCertRecord, int curCertId); + + result GetCurrentCertId(int& curCertId); + + result GetCountByCondition(byte* pCondition, int& count); + + result GetParentCaByCondition(byte* pCondition, int& parentCa); + + result SelectUserCertificateBycertId(int certId, UserCertRecord* pCertRecord); + +private: + _UserCertDbStore(const _UserCertDbStore& rhs); + + _UserCertDbStore& operator =(const _UserCertDbStore& rhs); + + +}; //_UserCertDbStore + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_DB_STORE_H_ diff --git a/src/security/cert/FSecCert_CertExtension.cpp b/src/security/cert/FSecCert_CertExtension.cpp new file mode 100644 index 0000000..cbe522a --- /dev/null +++ b/src/security/cert/FSecCert_CertExtension.cpp @@ -0,0 +1,247 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertExtension.cpp + * @brief This file contains implementation of X509 Certificate Extensions. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertExtension.h" +#include "FSecCert_CertOidDef.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +struct _ExtTable +{ + _CertExt type; + byte* pOid; +}; //_ExtTable + +const _ExtTable mExtTable[_MAX_EXT_TABLESIZE] = +{ + {_CERT_EXT_BASIC_CONTRAINTS, reinterpret_cast< byte* >(const_cast< char* >(_OID_BASIC_CONSTRAINTS))}, + {_CERT_EXT_CRL_DISTRIBUTION_POINTS, reinterpret_cast< byte* >(const_cast< char* >(_OID_CRL_DISTRIBUTION_POINT))}, + {_CERT_EXT_KEY_USAGE, reinterpret_cast< byte* >(const_cast< char* >(_OID_KEY_USAGE))}, + {_CERT_EXT_AUTHORITY_KEY_IDENTIFIER, reinterpret_cast< byte* >(const_cast< char* >(_OID_AUTHORITY_KEY_IDENTIFIER))}, + {_CERT_EXT_SUBJECT_KEY_IDENTIFIER, reinterpret_cast< byte* >(const_cast< char* >(_OID_SUBJECT_KEY_IDENTIFIER))}, + {_CERT_EXT_CERTIFICATE_POLICIES, reinterpret_cast< byte* >(const_cast< char* >(_OID_CERTIFICATE_POLICIES))}, + {_CERT_EXT_EXT_KEY_USAGE, reinterpret_cast< byte* >(const_cast< char* >(_OID_EXT_KEY_USAGE))}, + {_CERT_EXT_OCSP_NONCE, reinterpret_cast< byte* >(const_cast< char* >(_OID_OCSP_NONCE))}, + {_CERT_EXT_OCSP_NO_CHECK, reinterpret_cast< byte* >(const_cast< char* >(_OID_OCSP_NO_CHECK))}, + {_CERT_EXT_OCSP, reinterpret_cast< byte* >(const_cast< char* >(_OID_OCSP))}, + {_CERT_EXT_OCSP_SIGNING, reinterpret_cast< byte* >(const_cast< char* >(_OID_OCSP_SIGNING))}, + {_CERT_EXT_AUTHORITY_INFO_ACCESS, reinterpret_cast< byte* >(const_cast< char* >(_OID_AUTHORITY_INFO_ACCESS))}, + {_CERT_EXT_OMA_DRM_AGENT, reinterpret_cast< byte* >(const_cast< char* >(_OID_DRM_AGENT))}, + {_CERT_EXT_OMA_RIGHTS_ISSUER, reinterpret_cast< byte* >(const_cast< char* >(_OID_OMA_KP_RIGHTS_ISSUER))}, + {_CERT_EXT_REVOKED_CERTIFICATE_RANGE, reinterpret_cast< byte* >(const_cast< char* >(_OID_REVOKED_CERTIFICATE_RANGE))}, + {_CERT_EXT_ISSUING_DISTRIBUTION_POINT, reinterpret_cast< byte* >(const_cast< char* >(_OID_ISSUING_DISTRIBUTION_POINT))}, + {_CERT_EXT_CRL_NUMBER, reinterpret_cast< byte* >(const_cast< char* >(_OID_CRL_NUMBER))}, + {_CERT_EXT_CA_ISSUERS, reinterpret_cast< byte* >(const_cast< char* >(_OID_CA_ISSUERS))}, + {_CERT_EXT_SUB_ALT_NAME, reinterpret_cast< byte* >(const_cast< char* >(_OID_SUBJECT_ALT_NAME))}, + {_CERT_EXT_SUB_DIR_ATTR, reinterpret_cast< byte* >(const_cast< char* >(_OID_SUBJECT_DIRECTORY_ATTRIBUTES))}, + {_CERT_EXT_PRI_KEY_USAGE_PER, reinterpret_cast< byte* >(const_cast< char* >(_OID_PRIVATE_KEY_USAGE_PERIOD))}, + {_CERT_EXT_ISSUER_ALT_NAME, reinterpret_cast< byte* >(const_cast< char* >(_OID_ISSUER_ALT_NAME))}, + {_CERT_EXT_REASON_CODE, reinterpret_cast< byte* >(const_cast< char* >(_OID_CRL_REASON_CODE))}, + {_CERT_EXT_INSTRUCTION_CODE, reinterpret_cast< byte* >(const_cast< char* >(_OID_INSTRUCTION_CODE))}, + {_CERT_EXT_INVALID_DATE, reinterpret_cast< byte* >(const_cast< char* >(_OID_INVALIDITY_DATE))}, + {_CERT_EXT_DELTA_CRL_INDI, reinterpret_cast< byte* >(const_cast< char* >(_OID_DELTA_CRL_INDICATOR))}, + {_CERT_EXT_CERTIFICATE_ISSUER, reinterpret_cast< byte* >(const_cast< char* >(_OID_CERTIFICATE_ISSUER))}, + {_CERT_EXT_NAME_CONSTRAINT, reinterpret_cast< byte* >(const_cast< char* >(_OID_NAME_CONSTRAINT))}, + {_CERT_EXT_POLICY_MAPPING, reinterpret_cast< byte* >(const_cast< char* >(_OID_POLICY_MAPPINGS))}, + {_CERT_EXT_POLICY_CONSTRAINTS, reinterpret_cast< byte* >(const_cast< char* >(_OID_POLICY_CONSTRAINTS))}, + {_CERT_EXT_UNKNOWN, reinterpret_cast< byte* >(const_cast< char* >(""))} +}; + +// +// _CertExtension class +// +_CertExtension::_CertExtension(void) + : __pExts(null) +{ + + +} + +_CertExtension::~_CertExtension(void) +{ + short num = 0; + short getId = 0; + _CertExtensionInfo* pTmpExt = __pExts; + _CertExtensionInfo* pNextExt = __pExts; + num = GetExtNum(); + + for (getId = 0; getId < num; getId++) + { + if (pTmpExt != null) + { + pNextExt = pTmpExt->pCertExtNext; + delete[] pTmpExt->CertExtValue; + pTmpExt->CertExtValue = null; + delete pTmpExt; + } + pTmpExt = pNextExt; + } +} + +void +_CertExtension::AddExt(byte* pOid, bool critical, byte* pValue, int len) +{ + SysTryReturnVoidResult(NID_SEC_CERT, pOid != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnVoidResult(NID_SEC_CERT, pValue != null, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr <_CertExtensionInfo> pAddExt(new (std::nothrow) _CertExtensionInfo()); + SysTryReturnVoidResult(NID_SEC_CERT, pAddExt != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + // GetExtType + pAddExt->CertExtType = GetExtType(pOid); + + pAddExt->CertExtCritical = critical; + + pAddExt->CertExtValue = new (std::nothrow) byte[len + 1]; + SysTryReturnVoidResult(NID_SEC_CERT, pAddExt->CertExtValue != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memset(pAddExt->CertExtValue, 0, len + 1); + memcpy(pAddExt->CertExtValue, pValue, len); + pAddExt->CertExtLength = len; + pAddExt->pCertExtNext = null; + + if (__pExts == null) + { + __pExts = pAddExt.release(); + } + else + { + _CertExtensionInfo* pTmpExt = __pExts; + __pExts = pAddExt.release(); + __pExts->pCertExtNext = pTmpExt; + } + + return; +} +_CertExtensionInfo* +_CertExtension::GetExt(byte* pOid) +{ + byte* pExtOid = null; + SysTryReturn(NID_SEC_CERT, pOid != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input parameter."); + + _CertExtensionInfo* pTmpExt = __pExts; + while (pTmpExt) + { + pExtOid = GetExtOid(pTmpExt->CertExtType); + if (pExtOid != null) + { + if (strcmp(reinterpret_cast< const char* >(pExtOid), reinterpret_cast< const char* >(pOid)) == 0) + { + return pTmpExt; + } + } + pTmpExt = pTmpExt->pCertExtNext; + } + + return null; +} + +_CertExtensionInfo* +_CertExtension::GetExt(_CertExt type) +{ + _CertExtensionInfo* pTmpExt = __pExts; + while (pTmpExt) + { + if (pTmpExt->CertExtType == type) + { + return pTmpExt; + } + pTmpExt = pTmpExt->pCertExtNext; + } + return null; +} + +short +_CertExtension::GetExtNum(void) +{ + _CertExtensionInfo* pTmpExt = __pExts; + short num = 0; + while (pTmpExt) + { + num++; + pTmpExt = pTmpExt->pCertExtNext; + } + return num; +} + +_CertExtensionInfo* +_CertExtension::GetExtEntry(short getId) +{ + _CertExtensionInfo* pTmpExt = __pExts; + short index = 1; + + for (index = 1; index < getId; index++) + { + if (pTmpExt != null) + { + pTmpExt = pTmpExt->pCertExtNext; + } + } + return pTmpExt; +} + +_CertExt +_CertExtension::GetExtType(byte* pOid) +{ + short index = 0; + + SysTryReturn(NID_SEC_CERT, pOid != null, _CERT_EXT_UNKNOWN, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input parameter."); + + for (index = 0; index < _MAX_EXT_TABLESIZE; index++) + { + if (strcmp(reinterpret_cast< const char* >(mExtTable[index].pOid), reinterpret_cast< const char* >(pOid)) == 0) + { + return mExtTable[index].type; + } + } + return _CERT_EXT_UNKNOWN; +} + +byte* +_CertExtension::GetExtOid(_CertExt type) +{ + short index = 0; + + for (index = 0; index < _MAX_EXT_TABLESIZE; index++) + { + if (mExtTable[index].type == type) + { + return mExtTable[index].pOid; + } + } + return null; +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertExtension.h b/src/security/cert/FSecCert_CertExtension.h new file mode 100755 index 0000000..b6bcb53 --- /dev/null +++ b/src/security/cert/FSecCert_CertExtension.h @@ -0,0 +1,67 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertExtension.h + * @brief This header file contains the declarations of Certificate Extensions. + * + * This header file contains the declarations of Certificate Extensions. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_EXTENSION_H_ +#define _FSEC_CERT_INTERNAL_CERT_EXTENSION_H_ + +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertExtension +{ +public: + _CertExtension(void); + + virtual ~_CertExtension(void); + + void AddExt(byte* pOid, bool critical, byte* pValue, int len); + + _CertExtensionInfo* GetExt(byte* pOid); + + _CertExtensionInfo* GetExt(_CertExt type); + + _CertExtensionInfo* GetExtEntry(short getId); + + short GetExtNum(void); + +private: + _CertExtension(const _CertExtension& rhs); + + _CertExtension& operator =(const _CertExtension& rhs); + + _CertExt GetExtType(byte* pOid); + + byte* GetExtOid(_CertExt type); + + +private: + _CertExtensionInfo* __pExts; + +}; //_CertExtension + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_EXTENSION_H_ diff --git a/src/security/cert/FSecCert_CertFileStore.cpp b/src/security/cert/FSecCert_CertFileStore.cpp new file mode 100644 index 0000000..39ff04d --- /dev/null +++ b/src/security/cert/FSecCert_CertFileStore.cpp @@ -0,0 +1,234 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertFileStore.cpp + * @brief This file contains implementation of X509 Certificate and private key storing in File System. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertFileStore.h" + +using namespace Tizen::Base; +using namespace Tizen::Io; + +namespace Tizen { namespace Security { namespace Cert +{ + +const int _MAX_CERT_EXT_PATH_SIZE = 12; + +_CertFileStore::_CertFileStore(void) + : __hCert(0) + , __CertPathType(_CERT_PATH_UNKNOWN) +{ + +} + + +_CertFileStore::_CertFileStore(_CertPathType pathType) + : __hCert(0) +{ + __CertPathType = pathType; + +} + +_CertFileStore::_CertFileStore(char* pFileName, _CertPathType pathType) + : __hCert(0) +{ + if (pathType == _CERT_PATH_CA_CERT) + { + __fileName = _CERT_ROOT_CA_CERT_FILE_DIRECTORY; + } + else if (pathType == _CERT_PATH_USER_CERT) + { + __fileName = _CERT_USER_CERT_FILE_DIRECTORY; + } + else if (pathType == _CERT_PATH_PRIVATE_KEY) + { + __fileName = _CERT_USER_PRIVKEY_FILE_DIRECTORY; + } + + __fileName.Append(pFileName); + __CertPathType = pathType; +} + +_CertFileStore::_CertFileStore(CertIdNo hCertHandle, _CertPathType pathType) +{ + __hCert = hCertHandle; + __CertPathType = pathType; +} + +_CertFileStore::~_CertFileStore(void) +{ + +} + +_CertPathType +_CertFileStore::GetPathType(void) +{ + return __CertPathType; +} + +String +_CertFileStore::GetFilePath(void) +{ + return __fileName; +} + +result +_CertFileStore::SetFilePath(String& filePath) +{ + SysTryReturnResult(NID_SEC_CERT, filePath.GetLength() > 0, E_INVALID_ARG, "Invalid input file path."); + + __fileName = filePath; + return E_SUCCESS; +} + +result +_CertFileStore::SetFileHandle(CertIdNo hCert, _CertPathType pathType) +{ + SysTryReturnResult(NID_SEC_CERT, hCert != null, E_INVALID_ARG, "Invalid input certificate handle."); + + __hCert = hCert; + __CertPathType = pathType; + __fileName = L""; + GetFileNameFromHandle(__hCert, __CertPathType, __fileName); + return E_SUCCESS; +} + +result +_CertFileStore::WriteToFile(byte* pData, int dataLen) +{ + result r = E_SUCCESS; + String fileName(__fileName); + File file; + + SysTryReturnResult(NID_SEC_CERT, pData != null, E_INVALID_ARG, "Invalid input parameter."); + + SysTryReturnResult(NID_SEC_CERT, dataLen > 0, E_INVALID_ARG, "Invalid input parameter."); + + SysTryReturnResult(NID_SEC_CERT, __fileName.GetLength() > 0, E_INACCESSIBLE_PATH, "File path is not set."); + + // Open file + r = file.Construct(fileName, L"w+"); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Construct failed.", GetErrorMessage(r)); + + r = file.Write(pData, dataLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Construct failed.", GetErrorMessage(r)); + + return E_SUCCESS; +} + +result +_CertFileStore::ReadFromFile(byte* pData, int& dataLen) +{ + result r = E_SUCCESS; + String fileName(__fileName); + FileAttributes attr; + File file; + long fileSize = 0; + int readCnt = 0; + + SysTryReturnResult(NID_SEC_CERT, pData != null, E_INVALID_ARG, "Invalid input buffer."); + + // Open file + r = file.Construct(fileName, L"r"); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Propagated", GetErrorMessage(r)); + + r = File::GetAttributes(fileName, attr); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + fileSize = attr.GetFileSize(); + SysTryReturn(NID_SEC_CERT, fileSize >= 0, r, r, "[%s] Propagated.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] Propagated.", GetErrorMessage(r)); + + readCnt = file.Read(pData, fileSize); + dataLen = readCnt; + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Propagated.", GetErrorMessage(r)); + + return r; +} + +result +_CertFileStore::DeleteFile() +{ + return File::Remove(__fileName); +} + +result +_CertFileStore::GetFileNameFromHandle(CertIdNo hCert, _CertPathType pathType, String& fileName) +{ + char temp[_MAX_CERT_EXT_PATH_SIZE] = {0, }; + String tempStr; + String extn = L".cert"; + + SysTryReturnResult(NID_SEC_CERT, hCert != null, E_INVALID_ARG, "Invalid input parameter."); + + sprintf(temp, "%03d", hCert); + tempStr.Append(temp); + + switch (pathType) + { + case _CERT_PATH_CA_CERT: + { + fileName = _CERT_ROOT_CA_CERT_FILE_DIRECTORY; + } + break; + + case _CERT_PATH_USER_CERT: + { + fileName = _CERT_USER_CERT_FILE_DIRECTORY; + } + break; + + case _CERT_PATH_PRIVATE_KEY: + { + extn = L".key"; + fileName = _CERT_USER_PRIVKEY_FILE_DIRECTORY; + } + break; + + default: + { + fileName = _CERT_ROOT_CA_CERT_FILE_DIRECTORY; + } + break; + } + + fileName.Append(tempStr); + fileName.Append(extn); + + SysLog(NID_SEC_CERT, "GetFileNameFromHandle(Handle = %d): File name = %ls.", + hCert, fileName.GetPointer()); + return E_SUCCESS; +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertFileStore.h b/src/security/cert/FSecCert_CertFileStore.h new file mode 100755 index 0000000..c268b65 --- /dev/null +++ b/src/security/cert/FSecCert_CertFileStore.h @@ -0,0 +1,79 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertFileStore.h + * @brief This header file contains the declarations of storing certificates and private key in file system. + * + * This header file contains the declarations of storing certificates and private key in file system. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_FILE_STORE_H_ +#define _FSEC_CERT_INTERNAL_CERT_FILE_STORE_H_ + +#include +#include "FSecCert_CertTypes.h" + + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertFileStore +{ + +public: + _CertFileStore(void); + + _CertFileStore(_CertPathType pathType); + + _CertFileStore(char* pFileName, _CertPathType pathType); + + _CertFileStore(CertIdNo hCertHandle, _CertPathType pathType); + + virtual ~_CertFileStore(void); + + _CertPathType GetPathType(void); + + Tizen::Base::String GetFilePath(void); + + result SetFilePath(Tizen::Base::String& filePath); + + result SetFileHandle(CertIdNo hCert, _CertPathType pathType); + + result WriteToFile(byte* pData, int dataLen); + + result DeleteFile(void); + + result GetFileNameFromHandle(CertIdNo hCert, _CertPathType pathType, Tizen::Base::String& fileName); + + result ReadFromFile(byte* pData, int& dataLen); + +private: + _CertFileStore(const _CertFileStore& rhs); + + _CertFileStore& operator =(const _CertFileStore& rhs); + +private: + Tizen::Base::String __fileName; + CertIdNo __hCert; + _CertPathType __CertPathType; + +}; //_CertFileStore + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_FILE_STORE_H_ diff --git a/src/security/cert/FSecCert_CertList.cpp b/src/security/cert/FSecCert_CertList.cpp new file mode 100755 index 0000000..4dbb5c3 --- /dev/null +++ b/src/security/cert/FSecCert_CertList.cpp @@ -0,0 +1,549 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// +// @file FSecCert_CertList.cpp +// @brief This file contains implementation of X509 Certificate list. +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertList.h" +#include "FSecCert_CertOidDef.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Cert +{ +// +// _X509RevokedCert class +// +_X509RevokedCert::_X509RevokedCert(void) + : __serialNumberLen(0) + , __pExtension(null) + , __pNextRevokedCert(null) +{ + memset(__serialNumber, 0, _MAX_SERIAL_NUMBER_SIZE); +} + +_X509RevokedCert::~_X509RevokedCert(void) +{ +} + +void +_X509RevokedCert::SetSerialNumber(byte* pSerial, int len) +{ + memcpy(__serialNumber, pSerial, len); + __serialNumberLen = len; +} + +byte* +_X509RevokedCert::GetSerialNumber(void) +{ + return __serialNumber; +} + +void +_X509RevokedCert::SetTime(byte* pRevocationDate) +{ + _CertTime::_CertTimeType revokedTimeType = _CertTime::CERT_TIME_UTC; + if ((strlen(reinterpret_cast< const char* >(pRevocationDate))) == static_cast< int >(_MAX_CERT_TIME_LEN)) + { + revokedTimeType = _CertTime::CERT_TIME_GENERAL; + } + __revokedTime.SetTime(revokedTimeType, pRevocationDate); +} + +byte* +_X509RevokedCert::GetTime(void) +{ + return __revokedTime.GetTime(); +} + +void +_X509RevokedCert::AddExt(byte* pOid, bool critical, byte* pValue, int len) +{ + if (__pExtension == null) + { + __pExtension = std::unique_ptr< _CertExtension > (new (std::nothrow) _CertExtension()); + SysTryReturn(NID_SEC_CERT, __pExtension != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + } + __pExtension->AddExt(pOid, critical, pValue, len); +} + +_CertExtensionInfo* +_X509RevokedCert::GetExt(byte* pOid) +{ + if (__pExtension != null) + { + return __pExtension->GetExt(pOid); + } + return null; +} + +_CertExtensionInfo* +_X509RevokedCert::GetExt(_CertExt type) +{ + if (__pExtension != null) + { + return __pExtension->GetExt(type); + } + return null; +} + +short +_X509RevokedCert::GetExtNum(void) +{ + if (__pExtension != null) + { + return __pExtension->GetExtNum(); + } + return 0; +} + +_CertExtensionInfo* +_X509RevokedCert::GetExtEntry(short getId) +{ + if (__pExtension != null) + { + return __pExtension->GetExtEntry(getId); + } + return null; +} + +// +// _X509TBSCertList class +// + +_X509TbsCertList::_X509TbsCertList(void) + : __version(1) + , __pSignatureAlgoId(null) + , __pIssuer(null) +{ + +} + +_X509TbsCertList::~_X509TbsCertList(void) +{ + __revokedCerts.RemoveAll(true); +} + +// +// version Version OPTIONAL, +// -- if present, MUST be v2 +// +void +_X509TbsCertList::SetVersion(byte* pVersion, int len) +{ + __version = pVersion[0] + 1; // MUST be 2 + if (__version != 2) + { + __version = 2; + } +} + +int +_X509TbsCertList::GetVersion(void) +{ + return __version; +} + +void +_X509TbsCertList::SetSignature(const char* pAlgo) +{ + __pSignatureAlgoId.reset(null); + + if (pAlgo != null) + { + int size = strlen(pAlgo); + + __pSignatureAlgoId = std::unique_ptr (new (std::nothrow) char[size + 1]); + if (__pSignatureAlgoId != null) + { + memcpy(__pSignatureAlgoId.get(), pAlgo, size); + __pSignatureAlgoId[size] = 0x00; + } + + } +} + +char* +_X509TbsCertList::GetSigature(void) +{ + return __pSignatureAlgoId.get(); +} + +result +_X509TbsCertList::SetIssuerName(byte* pName) +{ + __pIssuer.reset(null); + + if (pName != null) + { + int len = strlen(reinterpret_cast< const char* >(pName)); + __pIssuer = std::unique_ptr (new (std::nothrow) byte[len + 1]); + SysTryReturnResult(NID_SEC_CERT, __pIssuer != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(__pIssuer.get(), 0, len + 1); + strcpy(reinterpret_cast< char* >(__pIssuer.get()), reinterpret_cast< const char* >(pName)); + } + + return E_SUCCESS; +} + +byte* +_X509TbsCertList::GetIssuerName(void) +{ + return __pIssuer.get(); +} + +result +_X509TbsCertList::SetTimes(byte* pThisUpdate, byte* pNextUpdate) +{ + _CertTime::_CertTimeType thisTimeType = _CertTime::CERT_TIME_UTC; + _CertTime::_CertTimeType nextTimeType = _CertTime::CERT_TIME_UTC; + + if (strlen(reinterpret_cast< const char* >(pThisUpdate)) == static_cast< int >(_MAX_CERT_TIME_LEN)) + { + thisTimeType = _CertTime::CERT_TIME_GENERAL; + } + __thisUpdate.SetTime(thisTimeType, pThisUpdate); + if (pNextUpdate != null) + { + if (strlen(reinterpret_cast< const char* >(pNextUpdate)) == static_cast< int >(_MAX_CERT_TIME_LEN)) + { + nextTimeType = _CertTime::CERT_TIME_GENERAL; + } + __nextUpdate.SetTime(nextTimeType, pNextUpdate); + } + else + { + pNextUpdate = null; + } + return E_SUCCESS; +} + +void +_X509TbsCertList::AddCrlEntry(_X509RevokedCert* pCrlEntry) +{ + __revokedCerts.Add(pCrlEntry); +} + + +int +_X509TbsCertList::GetEntryNumber(void) +{ + return __revokedCerts.GetCount(); +} + +_X509RevokedCert* +_X509TbsCertList::GetEntry(int getId) +{ + return reinterpret_cast<_X509RevokedCert*> (__revokedCerts.GetAt(getId)); +} + +void +_X509TbsCertList::AddExtension(byte* pOid, bool critical, byte* pValue, int len) +{ + __extension.AddExt(pOid, critical, pValue, len); +} + +// +// _CertList class +// +_CertList::_CertList(void) + : __pX509Crl(null) +{ +} + +_CertList::~_CertList() +{ + if (__pX509Crl != null) + { + X509_CRL_free(static_cast< X509_CRL* >(__pX509Crl)); + } + +} + + + +result +_CertList::ParseAlgorithmIdentifier() +{ + const char* pAlgorithmIdentifier = null; + X509_CRL* pX509Crl = static_cast< X509_CRL* >(__pX509Crl); + SysTryReturnResult(NID_SEC_CERT, pX509Crl != null, E_SYSTEM, "Initial parameters are not set"); + + pAlgorithmIdentifier = OBJ_nid2ln(OBJ_obj2nid(pX509Crl->crl->sig_alg->algorithm)); + SysTryReturnResult(NID_SEC_CERT, pAlgorithmIdentifier != null, E_PARSING_FAILED, "Parsing of algorithm identifier of chain failed."); + + __tbsCertList.SetSignature(pAlgorithmIdentifier); + + return E_SUCCESS; +} + +result +_CertList::ParseIssuerName() +{ + byte* pName = null; + X509_CRL* pX509Crl = static_cast< X509_CRL* >(__pX509Crl); + SysTryReturnResult(NID_SEC_CERT, pX509Crl != null, E_SYSTEM, "Initial parameters are not set"); + + pName = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Crl->crl->issuer, null, 0)); + SysTryReturnResult(NID_SEC_CERT, pName != null, E_PARSING_FAILED, "Parsing of issuer name of chain failed."); + + __tbsCertList.SetIssuerName(pName); + + return E_SUCCESS; +} + +result +_CertList::ParseUpdateTimes() +{ + ASN1_GENERALIZEDTIME* pTimeLastUpdate = NULL; + ASN1_GENERALIZEDTIME* pTimeNextUpdate = NULL; + X509_CRL* pX509Crl = static_cast< X509_CRL* >(__pX509Crl); + SysTryReturnResult(NID_SEC_CERT, pX509Crl != null, E_SYSTEM, "Initial parameters are not set"); + + ASN1_TIME_to_generalizedtime(pX509Crl->crl->lastUpdate, &pTimeLastUpdate); + ASN1_TIME_to_generalizedtime(pX509Crl->crl->nextUpdate, &pTimeNextUpdate); + + std::unique_ptr pThisUpdate(new (std::nothrow) byte[pTimeLastUpdate->length + 1]); + SysTryReturnResult(NID_SEC_CERT, pThisUpdate != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memcpy(pThisUpdate.get(), pTimeLastUpdate->data, pTimeLastUpdate->length); + pThisUpdate[pTimeLastUpdate->length] = 0x00; + + std::unique_ptr pNextUpdate(new (std::nothrow) byte[pTimeNextUpdate->length + 1]); + SysTryReturnResult(NID_SEC_CERT, pNextUpdate != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memcpy(pNextUpdate.get(), pTimeNextUpdate->data, pTimeNextUpdate->length); + pNextUpdate[pTimeNextUpdate->length] = 0x00; + + __tbsCertList.SetTimes(pThisUpdate.get(), pNextUpdate.get()); + + return E_SUCCESS; +} + +result +_CertList::ParseRevokedCerts() +{ + byte* pValue = null; + byte* pOid = null; + bool critical = false; + int fieldCount = 0; + int extLen = 0; + int certCount = 0; + int certIndex = 0; + X509_REVOKED* pRevokedCert = null; + ASN1_GENERALIZEDTIME* pRevocationDate = null; + X509_EXTENSION* pExt = NULL; + X509_CRL* pX509Crl = static_cast< X509_CRL* >(__pX509Crl); + SysTryReturnResult(NID_SEC_CERT, pX509Crl != null, E_SYSTEM, "Initial parameters are not set"); + + certCount = sk_X509_REVOKED_num(pX509Crl->crl->revoked); + + for (certIndex = 0; certIndex < certCount; certIndex++) + { + pRevokedCert = sk_X509_REVOKED_value(pX509Crl->crl->revoked, certIndex); + + if (pRevokedCert == null) + { + continue; + } + + std::unique_ptr<_X509RevokedCert> pNewCRLEntry(new (std::nothrow) _X509RevokedCert()); + SysTryReturnResult(NID_SEC_CERT, pNewCRLEntry != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pNewCRLEntry->SetSerialNumber(pRevokedCert->serialNumber->data, pRevokedCert->serialNumber->length); + + ASN1_TIME_to_generalizedtime(pRevokedCert->revocationDate, &pRevocationDate); + + pNewCRLEntry->SetTime(pRevocationDate->data); + + // pCrlEntryExtensions + SysTryReturnResult(NID_SEC_CERT, pX509Crl->crl->extensions != null, E_SUCCESS, "No extensions are present in certificates"); + + fieldCount = sk_X509_EXTENSION_num(pRevokedCert->extensions); + + for (int i = 0; i < fieldCount; i++) + { + pExt = sk_X509_EXTENSION_value(pRevokedCert->extensions, i); + + if (pExt != null) + { + pOid = reinterpret_cast< byte* >(const_cast< char* >(OBJ_nid2ln(OBJ_obj2nid(pExt->object)))); + + critical = pExt->critical; + pValue = pExt->value->data; + extLen = pExt->value->length; + + if (pOid != null) + { + pNewCRLEntry->AddExt(pOid, critical, pValue, extLen); + } + } + } + __tbsCertList.AddCrlEntry(pNewCRLEntry.release()); + } + + return E_SUCCESS; +} + +result +_CertList::ParseExtensions() +{ + byte* pValue = null; + byte* pOid = null; + bool critical = false; + int fieldCount = 0; + int extLen = 0; + X509_EXTENSION* pExt = NULL; + X509_CRL* pX509Crl = static_cast< X509_CRL* >(__pX509Crl); + + SysTryReturnResult(NID_SEC_CERT, pX509Crl != null, E_SYSTEM, "Initial parameters are not set"); + + SysTryReturnResult(NID_SEC_CERT, pX509Crl->crl->extensions != null, E_SUCCESS, "No extesions are present in certificates"); + + fieldCount = sk_X509_EXTENSION_num(pX509Crl->crl->extensions); + + for (int i = 0; i < fieldCount; i++) + { + pExt = sk_X509_EXTENSION_value(pX509Crl->crl->extensions, i); + + if (pExt != null) + { + pOid = reinterpret_cast< byte* >(const_cast< char* >(OBJ_nid2ln(OBJ_obj2nid(pExt->object)))); + + critical = pExt->critical; + pValue = pExt->value->data; + extLen = pExt->value->length; + + + if (pOid != null) + { + __tbsCertList.AddExtension(pOid, critical, pValue, extLen); + } + } + + } // End of while loop + + return E_SUCCESS; + +} + +result +_CertList::ParseSignature() +{ + result r = E_PARSING_FAILED; + const char* pAlgorithmIdentifier = null; + X509_CRL* pX509Crl = static_cast< X509_CRL* >(__pX509Crl); + SysTryReturnResult(NID_SEC_CERT, pX509Crl != null, E_SYSTEM, "Initial parameters are not set"); + + // get SEQUENCE + pAlgorithmIdentifier = OBJ_nid2ln(OBJ_obj2nid(pX509Crl->sig_alg->algorithm)); + SysTryReturnResult(NID_SEC_CERT, pAlgorithmIdentifier != null, E_SYSTEM, "Signature algorithm not present in certificate list."); + SysTryReturnResult(NID_SEC_CERT, pX509Crl->signature->data != null, E_SYSTEM, "Signature data not present in certificate list."); + + __signatureInfo.SetSignature(pAlgorithmIdentifier, pX509Crl->signature->length, pX509Crl->signature->data); + + return r; +} + +result +_CertList::ParseObject(void) +{ + BIO* pBio = null; + X509_CRL* pX509Crl = static_cast< X509_CRL* >(__pX509Crl); + const unsigned char* pX509Buff = const_cast< const unsigned char* >(_pX509Buff.get()); + + SysAssertf(pX509Buff != null, "Not yet constructed. Reconstructor the object."); + + if (pX509Crl != null) + { + X509_CRL_free(pX509Crl); + __pX509Crl = null; + } + + pBio = BIO_new(BIO_s_mem()); + SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + BIO_write(pBio, pX509Buff, _x509BuffSize); + + pX509Crl = d2i_X509_CRL_bio(pBio, null); + SysTryReturnResult(NID_SEC_CERT, pX509Crl != null, E_PARSING_FAILED, "Failed to decode certificate chain."); + + __pX509Crl = pX509Crl; + + BIO_free(pBio); + + if (ParseAlgorithmIdentifier() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + if (ParseIssuerName() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + if (ParseUpdateTimes() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + if (ParseRevokedCerts() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + + if (ParseSignature() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + return E_SUCCESS; +} + +result +_CertList::GetCrlBuffer(byte*& pBuf, int& bufSize) +{ + SysTryReturnResult(NID_SEC_CERT, _pX509Buff != null, E_INVALID_ARG, "Initial parameters not set"); + pBuf = _pX509Buff.get(); + bufSize = _x509BuffSize; + return E_SUCCESS; +} + +_X509TbsCertList* +_CertList::GetTbsCertListInstance(void) +{ + return &__tbsCertList; +} + +_CertSignature* +_CertList::GetSignInstance(void) +{ + return &__signatureInfo; +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertList.h b/src/security/cert/FSecCert_CertList.h new file mode 100755 index 0000000..bcbf8c6 --- /dev/null +++ b/src/security/cert/FSecCert_CertList.h @@ -0,0 +1,169 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertList.h + * @brief This header file contains the declarations of Certificate List. + * + * This header file contains the declarations of Certificate List. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_LIST_H_ +#define _FSEC_CERT_INTERNAL_CERT_LIST_H_ + +#include "unique_ptr.h" +#include "FBaseColArrayList.h" +#include "FSecCert_CertSignature.h" +#include "FSecCert_CertTime.h" +#include "FSecCert_CertExtension.h" +#include "FSecCert_Asn1Parser.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +class _X509RevokedCert + : public Tizen::Base::Object +{ +public: + _X509RevokedCert(void); + + virtual ~_X509RevokedCert(void); + + void SetSerialNumber(byte* pSerial, int len); + + byte* GetSerialNumber(void); + + void SetTime(byte* pRevocationDate); + + byte* GetTime(void); + + void AddExt(byte* pOid, bool critical, byte* pValue, int len); + + _CertExtensionInfo* GetExt(byte* pOid); + + _CertExtensionInfo* GetExt(_CertExt type); + + short GetExtNum(void); + + _CertExtensionInfo* GetExtEntry(short getId); + +private: + _X509RevokedCert(const _X509RevokedCert& rhs); + + _X509RevokedCert& operator =(const _X509RevokedCert& rhs); + +private: + byte __serialNumber[_MAX_SERIAL_NUMBER_SIZE]; + int __serialNumberLen; + _CertTime __revokedTime; + std::unique_ptr<_CertExtension> __pExtension; + _X509RevokedCert* __pNextRevokedCert; + +}; //_X509RevokedCert + +class _X509TbsCertList +{ +public: + _X509TbsCertList(void); + + virtual ~_X509TbsCertList(void); + + void SetVersion(byte* pVersion, int len); + + int GetVersion(void); + + void SetSignature(const char* pAlgo); + + char* GetSigature(void); + + result SetIssuerName(byte* pName); + + byte* GetIssuerName(void); + + result SetTimes(byte* pThisUpdate, byte* pNextUpdate); + + byte* GetNextUpdate(void); + + void AddCrlEntry(_X509RevokedCert* pCrlEntry); + + int GetEntryNumber(void); + + _X509RevokedCert* GetEntry(int getId); + + void AddExtension(byte* pOid, bool critical, byte* pValue, int len); + +private: + _X509TbsCertList(const _X509TbsCertList& rhs); + + _X509TbsCertList& operator =(const _X509TbsCertList& rhs); + +private: + int __version; + std::unique_ptr __pSignatureAlgoId; + std::unique_ptr __pIssuer; + Tizen::Base::Collection::ArrayList __revokedCerts; + _CertExtension __extension; + _CertTime __thisUpdate; + _CertTime __nextUpdate; + +}; //_X509TBSCertList + +class _CertList + : public _Asn1Parser +{ +public: + _CertList(void); + + virtual ~_CertList(void); + + result ParseObject(void); + + _X509TbsCertList* GetTbsCertListInstance(void); + + _CertSignature* GetSignInstance(void); + + result GetCrlBuffer(byte*& pBuf, int& bufSize); + +private: + _CertList(const _CertList& rhs); + + _CertList& operator =(const _CertList& rhs); + + result ParseVersion(); + + result ParseAlgorithmIdentifier(); + + result ParseIssuerName(); + + result ParseUpdateTimes(); + + result ParseRevokedCerts(); + + result ParseExtensions(); + + result ParseSignature(); + +private: + void* __pX509Crl; + _X509TbsCertList __tbsCertList; + _CertSignature __signatureInfo; + +}; //_CertList + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_LIST_H_ diff --git a/src/security/cert/FSecCert_CertManager.cpp b/src/security/cert/FSecCert_CertManager.cpp new file mode 100644 index 0000000..ab49fbc --- /dev/null +++ b/src/security/cert/FSecCert_CertManager.cpp @@ -0,0 +1,1505 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertManager.cpp + * @brief This file contains implementation of X509 Certificate and private key interface APIs. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertManager.h" +#include "FSecCert_CertPrivateKeyInfo.h" +#include "FSecCert_CertDbManager.h" +#include "FSecCert_Base64.h" +#include "FSecCert_CertOidDef.h" +#include "FSecCert_CertFileStore.h" + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Io; + +namespace Tizen { namespace Security { namespace Cert +{ + +static const char* _CERT_BASE64_HEADER = "-----BEGIN CERTIFICATE-----"; +static const char* _CERT_BASE64_TRAILER = "-----END CERTIFICATE-----"; + +result +_CertManager::CreateCrtFile(void) +{ + result r = E_SUCCESS; + BIO* pBio = null; + X509* pCert = null; + Directory dir; + File fileCrt; + FileAttributes attr; + byte certBufData[_MAX_CERTIFICATE_SIZE] = {0, }; + const unsigned char* pCertBuffer = null; + long fileSize = 0; + int certBufferLen = 0; + int readLength = 0; + int certificateBase64Len = 0; + int readCnt = 0; + String dirName(_CERT_ROOT_CA_CERT_FILE_DIRECTORY); + String crtFileName(_CERT_MGR_CRT_FILE_PATH); + String tmpCrtFileName(_TEMP_CERT_MGR_CRT_FILE_PATH); + + r = fileCrt.Construct(tmpCrtFileName, L"a+"); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Construct failed.", GetErrorMessage(r)); + + r = dir.Construct(dirName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct directory.", GetErrorMessage(r)); + + std::unique_ptr pDirEnum(dir.ReadN()); + SysTryReturn(NID_SEC_CERT, pDirEnum != null, GetLastResult(), GetLastResult(), "[%s] Failed to read directory.", GetErrorMessage(GetLastResult())); + + while (pDirEnum->MoveNext() == E_SUCCESS) + { + String fileName; + File file; + DirEntry entry = pDirEnum->GetCurrentDirEntry(); + + fileName.Append(dirName); + fileName.Append(entry.GetName()); + if ((entry.GetName() == "..") || (entry.GetName() == ".")) + { + continue; + } + + r = file.Construct(fileName, L"r"); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct file.", GetErrorMessage(r)); + + r = File::GetAttributes(fileName, attr); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r)); + + fileSize = attr.GetFileSize(); + SysTryCatch(NID_SEC_CERT, fileSize > 0, r = GetLastResult(), GetLastResult(), "[%s] Failed to get file size.", GetErrorMessage(r)); + SysTryCatch(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r = GetLastResult(), GetLastResult(), "[%s] File size exceeds maximum specified length.", GetErrorMessage(r)); + + readCnt = file.Read(certBufData, fileSize); + certificateBase64Len = _Base64::GetEncodedSize(readCnt); + r = GetLastResult(); + if (!IsFailed(r) && readCnt == fileSize) + { + BIO_free(pBio); + X509_free(pCert); + + pBio = BIO_new(BIO_s_mem()); + SysTryCatch(NID_SEC_CERT, pBio != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pCertBuffer = new (std::nothrow) unsigned char[readCnt]; + SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memcpy((void*) pCertBuffer, certBufData, readCnt); + certBufferLen = readCnt; + + pCert = d2i_X509(null, &pCertBuffer, certBufferLen); + SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed."); + + readLength = PEM_write_bio_X509(pBio, pCert); + SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + readCnt = certificateBase64Len + (2 * _MAX_PEM_HEADER); + + readLength = BIO_read(pBio, certBufData, readCnt); + SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + readCnt = readLength; + + r = fileCrt.Write(certBufData, readLength); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%] Failed to write certificate to file.", GetErrorMessage(r)); + + fileSize = 0; + readCnt = 0; + readLength = 0; + memset(certBufData, 0, _MAX_CERTIFICATE_SIZE); + } + } + fileCrt.Flush(); + Tizen::Io::File::Remove(crtFileName); + Tizen::Io::File::Move(tmpCrtFileName, crtFileName); +CATCH: + BIO_free(pBio); + X509_free(pCert); + return r; +} + +result +_CertManager::OpenContext(_CertContextType type, CertChainCtx* pHCertCtx) +{ + SysTryReturnResult(NID_SEC_CERT, type > 0, E_INVALID_ARG, "Invalid input parameter."); + + _CertChain* pCertChain = new (std::nothrow) _CertChain(); + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pCertChain->SetContextType(type); + *pHCertCtx = (CertChainCtx) pCertChain; + + return E_SUCCESS; +} + +result +_CertManager::AddCertificate(CertChainCtx certCtx, byte* pCert, int certLen) +{ + result r = E_SUCCESS; + byte* pDerCert = null; + int derCertBufferLength = 0; + _CertFormat certFormat = _CERT_UNKNOWN; + _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN; + _CertChain* pCertChain = reinterpret_cast< _CertChain* >(certCtx); + + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Initial parameters are invalid."); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Initial parameters are invalid."); + + certFormat = _CertManager::GetEncodedCertBuffer(pCert, certLen, &pDerCert, &derCertBufferLength, &encodingType); + std::unique_ptr pDerCertBuffer(pDerCert); + pDerCert = null; + + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Unsupported certificate format."); + SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_ARG, "Invalid certificate length."); + SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_ARG, "Input certificate buffer."); + + r = pCertChain->AddCertificate(certFormat, static_cast< byte* >(pDerCertBuffer.get()), derCertBufferLength); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "Failed to add certificate in chain context."); + + return r; +} + +result +_CertManager::VerifyChain(CertChainCtx certCtx, _CertDomainType* pDomain) +{ + result r = E_SUCCESS; + _CertChain* pCertChain = reinterpret_cast< _CertChain* >(certCtx); + + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Initial parameters are invalid."); + + r = pCertChain->VerifyCertChainWithDb(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate chain.", GetErrorMessage(r)); + + if (pDomain != null) + { + *pDomain = pCertChain->GetCertTypeByDomain(); + } + + return r; +} + +result +_CertManager::VerifyCertificate(CertificateHandle certHandle, byte* pPublickey, int keyLen) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC_CERT, pPublickey != null, E_INVALID_ARG, "Initial parameters are invalid."); + SysTryReturnResult(NID_SEC_CERT, keyLen > 0, E_INVALID_ARG, "Initial parameters are invalid."); + SysTryReturnResult(NID_SEC_CERT, certHandle != 0, E_INVALID_ARG, "Initial parameters are invalid."); + + _Certificate* pTempCert = reinterpret_cast< _Certificate* >(certHandle); + SysTryReturnResult(NID_SEC_CERT, pTempCert != null, E_INVALID_ARG, "Initial parameters are invalid."); + + _CertFormat format = pTempCert->GetCertFormat(); + + if (format == _CERT_X509) + { + _X509Certificate* pCert = reinterpret_cast< _X509Certificate* >(certHandle); + + pCert->VerifySignature(pPublickey, keyLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get signature.", GetErrorMessage(r)); + + } + else + { + SysLogException(NID_SEC_CERT, E_INVALID_CONTENT, "[E_INVALID_CONTENT]GetCertificateType: Unknown certificate format."); + r = E_SYSTEM; + } + + return r; +} + +result +_CertManager::GetChainDepth(CertChainCtx certCtx, int* pDepth) +{ + _CertChain* pCertChain = reinterpret_cast< _CertChain* >(certCtx); + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Initial parameters are invalid."); + *pDepth = pCertChain->GetCount(); + return E_SUCCESS; +} + +result +_CertManager::GetNthCertificate(CertChainCtx certCtx, int nth, CertificateHandle* pCertHandle) +{ + result r = E_SUCCESS; + _CertFormat format = _CERT_UNKNOWN; + _CertChain* pCertChain = reinterpret_cast< _CertChain* >(certCtx); + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Initial parameters are invalid."); + + r = pCertChain->MoveHead(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move ahead in certificate chain."); + + for (int index = 0; index < nth; index++) + { + r = pCertChain->MoveNext(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move next in certificate chain."); + } + format = pCertChain->GetCertFormat(); + if (format == _CERT_X509) + { + _X509Certificate* pCert = null; + pCert = pCertChain->GetCurrentCertificate(); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain."); + + pCert->SetContextCertificate(true); + *pCertHandle = (CertificateHandle) pCert; + } + + return r; +} + +result +_CertManager::GetCertBuffer(CertificateHandle certHandle, char** ppCertbuffer, int* pCertLen) +{ + result r = E_SUCCESS; + byte* pBuf = null; + int bufSize = 0; + _Certificate* pTempCert = null; + _CertFormat format; + + SysTryReturnResult(NID_SEC_CERT, certHandle != null, E_INVALID_ARG, "Initial params not set."); + + pTempCert = reinterpret_cast< _Certificate* >(certHandle); + format = pTempCert->GetCertFormat(); + SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_INVALID_ARG, "Initial params not set."); + + _X509Certificate* pCert = reinterpret_cast< _X509Certificate* >(certHandle); + + r = pCert->GetCertBuffer(pBuf, bufSize); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move next in certificate chain."); + + *ppCertbuffer = new (std::nothrow) char[bufSize]; + SysTryReturnResult(NID_SEC_CERT, *ppCertbuffer != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memcpy(*ppCertbuffer, pBuf, bufSize); + *pCertLen = bufSize; + + return r; +} + +result +_CertManager::CloseContext(CertChainCtx certCtx) +{ + _CertChain* pCertChain = static_cast< _CertChain* >(certCtx); + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Initial parameter not set."); + + delete pCertChain; + return E_SUCCESS; +} + +result +_CertManager::GetCertInfo(CertificateHandle certHandle, _CertFieldType field, _CertFieldInfos* pCertInfo) +{ + result r = E_SUCCESS; + _X509Certificate* pCert = static_cast< _X509Certificate* >(certHandle); + _X509TbsCert* pTbsCert = null; + byte* pSerial = null; + int publicKeyLen = 0; + int fingerPrintLen = 0; + int serialLen = 0; + int resValue = 0; + char* pSigAlg = null; + + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Initial params not set."); + SysTryReturnResult(NID_SEC_CERT, pCertInfo != null, E_INVALID_ARG, "Initial params not set."); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + if (field & _CERT_FIELD_SERIAL) + { + pTbsCert->GetSerialNumber(pSerial, serialLen); + if (pSerial != null) + { + byte* pSerialNumber = null; + int iterVal = 0; + int index = 0; + iterVal = serialLen; + pSerialNumber = static_cast< byte* >(pSerial); + memset(pCertInfo->serialNo, 0, _MAX_SERIAL_NUMBER_SIZE + 1); + for (index = 0; index < iterVal; index++) + { + sprintf(&pCertInfo->serialNo[index * 2], "%02X", pSerialNumber[index]); + } + } + } + if (field & _CERT_FIELD_SIGALGORITHM) + { + pSigAlg = pTbsCert->GetSignatureAlgoId(); + if (pSigAlg != null) + { + int len = strlen(pSigAlg); + if (len <= _MAX_CERT_ALGORITHM_SIZE) + { + strcpy(pCertInfo->sigAlgorithm, pSigAlg); + } + else + { + memcpy(pCertInfo->sigAlgorithm, pSigAlg, _MAX_CERT_ALGORITHM_SIZE); + pCertInfo->sigAlgorithm[_MAX_CERT_ALGORITHM_SIZE] = '\0'; + } + + } + else + { + strcpy(pCertInfo->sigAlgorithm, "Unknown"); + } + } + if (field & _CERT_FIELD_VALIDITY) + { + Tizen::Base::DateTime notBefore; + Tizen::Base::DateTime notAfter; + pTbsCert->GetAfterTimes(notAfter); + pTbsCert->GetBeforeTimes(notBefore); + memset(pCertInfo->validityFrom, 0, _MAX_CERT_VALIDITY_SIZE + 1); + memset(pCertInfo->validityTo, 0, _MAX_CERT_VALIDITY_SIZE + 1); + + _CertTime::FormatDateTime(notBefore, pCertInfo->validityFrom); + _CertTime::FormatDateTime(notAfter, pCertInfo->validityTo); + } + + if (field & _CERT_FIELD_SUBJECT) + { + byte* pSubjectName = pTbsCert->GetSubjectName(); + int subLen = strlen(reinterpret_cast< const char* >(pSubjectName)); + memset(pCertInfo->subjectName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + if (subLen <= _MAX_ISSUER_SUBJECT_NAME_SIZE + 1) + { + strcpy(pCertInfo->subjectName, reinterpret_cast< const char* >(pSubjectName)); + } + ParseCertTitle(reinterpret_cast< char* >(pSubjectName), pCertInfo->certTitle); + ClearLastResult(); + } + if (field & _CERT_FIELD_ISSUER) + { + byte* pIssuerName = pTbsCert->GetIssuerName(); + int issuerLen = strlen(reinterpret_cast< const char* >(pIssuerName)); + memset(pCertInfo->issuerName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + if (issuerLen <= _MAX_ISSUER_SUBJECT_NAME_SIZE + 1) + { + strcpy(pCertInfo->issuerName, reinterpret_cast< const char* >(pIssuerName)); + } + ParseCertTitle(reinterpret_cast< char* >(pIssuerName), pCertInfo->certSubTitle); + ClearLastResult(); + } + if (field & _CERT_FIELD_FINGERPRINT) + { + byte* pX509Buff = null; + int x509BuffSize = 0; + + memset(pCertInfo->fingerPrint, 0, _MAX_CERT_FINGERPRINT_SIZE + 1); + + //As per OpenSSL APIs, it takes input as unsigned data types + pCert->GetCertBuffer(pX509Buff, x509BuffSize); + SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer."); + + std::unique_ptr pFingerPrint(new (std::nothrow) byte[SHA_DIGEST_LENGTH + 1]); + SysTryReturnResult(NID_SEC_CERT, pFingerPrint != null, E_OUT_OF_MEMORY, "Failed to allocate memory. "); + + memset(pFingerPrint.get(), 0, SHA_DIGEST_LENGTH + 1); + + resValue = EVP_Digest(pX509Buff, x509BuffSize, pFingerPrint.get(), reinterpret_cast< unsigned int* >(&fingerPrintLen), EVP_sha1(), 0); + SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to create digest hash."); + + int index = 0; + int maxValue = SHA_DIGEST_LENGTH; + for (index = 0; index < maxValue; index++) + { + sprintf(&pCertInfo->fingerPrint[index * 2], "%02X", pFingerPrint[index]); + } + pCertInfo->fingerPrintLen = fingerPrintLen; + + } + if (field & _CERT_FIELD_PUBLICKEY) + { + byte* pPublicKeyBuffer = null; + pTbsCert->GetPublicKeyInfoN(publicKeyLen, &pPublicKeyBuffer); + if (pPublicKeyBuffer != null) + { + std::unique_ptr pPublicKeyAuto(pPublicKeyBuffer); + int iterVal = publicKeyLen; + int index = 0; + + memset(pCertInfo->publicKey, 0, _MAX_CERT_PUBLIC_KEY_SIZE + 1); + for (index = 0; index < iterVal; index++) + { + sprintf(&pCertInfo->publicKey[index * 2], "%02X", pPublicKeyBuffer[index]); + } + + } + } + + if (field & _CERT_FIELD_VERSION) + { + pCertInfo->certVersion = pTbsCert->GetVersion(); + SysTryReturnResult(NID_SEC_CERT, pCertInfo->certVersion > 0, E_SYSTEM, "Failed to get version."); + } + + if (field & _CERT_FIELD_TYPE) + { + char type[6] = "X.509"; + memset(pCertInfo->certTypeFormat, 0, sizeof(pCertInfo->certTypeFormat)); + strcpy(pCertInfo->certTypeFormat, type); + } + if (strcmp(pCertInfo->certTitle, pCertInfo->certSubTitle) == 0) + { + char selfSigned[12] = "Self-signed"; + memset(pCertInfo->certSubTitle, 0, sizeof(pCertInfo->certSubTitle)); + strcpy(pCertInfo->certSubTitle, selfSigned); + } + + return r; +} + + +_CertFormat +_CertManager::GetEncodedCertBuffer(byte* pCertBuffer, int certBufferLen, byte** pDerCertBuffer, int* pDerCertBufferLength, _CertEncodingType* encodingType) +{ + result r = E_SUCCESS; + _CertFormat certFormat = _CERT_UNKNOWN; + BIO* pBio = null; + X509* pOpensslX509Cert = null; + char* pBase64Header = null; + char* pBase64Trailer = null; + int readCount = 0; + int certBufLen = 0; + int decodedLen = 0; + int pemCertSize = 0; + + ClearLastResult(); + + SysTryReturn(NID_SEC_CERT, pCertBuffer != null, _CERT_UNKNOWN, E_INVALID_ARG, "[E_INVALID_ARG] Invalid argument passed."); + SysTryReturn(NID_SEC_CERT, certBufferLen > 0, _CERT_UNKNOWN, E_INVALID_ARG, "[E_INVALID_ARG] Invalid argument passed."); + + std::unique_ptr<_X509Certificate> pX509Cert(new (std::nothrow) _X509Certificate()); + SysTryReturn(NID_SEC_CERT, pX509Cert != null, _CERT_UNKNOWN, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pBase64Header = strstr(reinterpret_cast< char* >(pCertBuffer), _CERT_BASE64_HEADER); + pBase64Trailer = strstr(reinterpret_cast< char* >(pCertBuffer), _CERT_BASE64_TRAILER); + + if ((pBase64Header != null) && (pBase64Trailer != null) && (pBase64Trailer > pBase64Header)) + { + pBio = BIO_new(BIO_s_mem()); + SysTryReturn(NID_SEC_CERT, pBio != null, _CERT_UNKNOWN, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pemCertSize = (int(pBase64Trailer - pBase64Header) + strlen(_CERT_BASE64_TRAILER)); + readCount = BIO_write(pBio, (const void*) pBase64Header, pemCertSize); + SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed"); + + pOpensslX509Cert = PEM_read_bio_X509(pBio, NULL, 0, NULL); + SysTryCatch(NID_SEC_CERT, pOpensslX509Cert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convention failed. readCount = %d Calculated length = %d pBase64Trailer = %s, pBase64Header = %s", readCount, pemCertSize, pBase64Trailer, pBase64Header); + + decodedLen = i2d_X509(pOpensslX509Cert, pDerCertBuffer); + SysTryCatch(NID_SEC_CERT, decodedLen > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Invalid certificate length."); + + *pDerCertBufferLength = decodedLen; + + certFormat = _CERT_X509; + *encodingType = _CERT_ENC_TYPE_PEM; + } + else if (pX509Cert->Parse(pCertBuffer, certBufferLen) == E_SUCCESS) + { + std::unique_ptr pCertBuf(new (std::nothrow) byte[certBufferLen]); + SysTryReturn(NID_SEC_CERT, pCertBuf != null, _CERT_UNKNOWN, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memcpy(pCertBuf.get(), pCertBuffer, certBufferLen); + certBufLen = certBufferLen; + + *pDerCertBuffer = pCertBuf.release(); + *pDerCertBufferLength = certBufLen; + + certFormat = _CERT_X509; + *encodingType = _CERT_ENC_TYPE_BINARY; + } + else + { + certBufLen = _Base64::GetDecodedSize(certBufferLen); + SysTryReturn(NID_SEC_CERT, certBufLen > 0, _CERT_UNKNOWN, E_SYSTEM, "[E_SYSTEM] Invalid certificate length."); + + std::unique_ptr pCertBuf(new (std::nothrow) byte[certBufLen]); + SysTryReturn(NID_SEC_CERT, pCertBuf != null, _CERT_UNKNOWN, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pCertBuf.get(), 0, certBufLen); + + decodedLen = certBufLen; + readCount = _Base64::Decode(reinterpret_cast< char* >(pCertBuffer), certBufferLen, pCertBuf.get(), decodedLen); + SysTryReturn(NID_SEC_CERT, readCount > 0, _CERT_UNKNOWN, E_SYSTEM, "[E_SYSTEM] Certificate decoding failed."); + + *pDerCertBuffer = pCertBuf.release(); + *pDerCertBufferLength = decodedLen; + + certFormat = _CERT_X509; + *encodingType = _CERT_ENC_TYPE_BASE64; + } + + SetLastResult(E_SUCCESS); //To clear the result of parsing certificate. + +CATCH: + + if (pBio != null) + { + BIO_free(pBio); + } + + if (pOpensslX509Cert != null) + { + X509_free(pOpensslX509Cert); + } + + return certFormat; +} + +result +_CertManager::GetPublicKey(CertificateHandle certificate, char* pBuffer, int* pBufLen) +{ + _Certificate* pTempCert = reinterpret_cast< _Certificate* >(certificate); + _X509Certificate* pCert = null; + _X509TbsCert* pTbsCert = null; + byte* pPuKey = null; + int pubKeyLen = 0; + + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, pTempCert != null, E_INVALID_ARG, "Invalid input parameter."); + + _CertFormat format = pTempCert->GetCertFormat(); + SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_SYSTEM, "Failed to get certificate format."); + + pCert = reinterpret_cast< _X509Certificate* >(certificate); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid input parameter."); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + pTbsCert->GetPublicKeyInfoN(pubKeyLen, &pPuKey); + SysTryReturnResult(NID_SEC_CERT, pPuKey != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + std::unique_ptr pPubKeyAuto(pPuKey); + + memcpy(pBuffer, pPubKeyAuto.get(), pubKeyLen); + + if (pBufLen) + { + *pBufLen = pubKeyLen; + } + + return E_SUCCESS; +} + +result +_CertManager::GetSignature(CertificateHandle certificate, char* pBuffer, int* pBufLen) +{ + _Certificate* pTempCert = reinterpret_cast< _Certificate* >(certificate); + _X509Certificate* pCert = null; + byte* pSignature = null; + _CertFormat format; + _CertSignature* pSig = null; + int signLength = 0; + + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, pTempCert != null, E_INVALID_ARG, "Initial parameter not set."); + + format = pTempCert->GetCertFormat(); + SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_SYSTEM, "Failed to get certificate format."); + pCert = reinterpret_cast< _X509Certificate* >(certificate); + + pSig = pCert->GetSignInstance(); + SysTryReturnResult(NID_SEC_CERT, pSig != null, E_SYSTEM, "Failed to get certificate signature."); + + pSignature = pSig->GetSignatureInfo(signLength); + memcpy(pBuffer, pSignature, signLength); + + if (pBufLen != null) + { + *pBufLen = signLength; + } + return E_SUCCESS; +} + +int +_CertManager::GetVersion(CertificateHandle certificate) +{ + _Certificate* pTempCert = null; + _X509Certificate* pCert = null; + _X509TbsCert* pTbsCert = null; + + pTempCert = reinterpret_cast< _Certificate* >(certificate); + SysTryReturn(NID_SEC_CERT, pTempCert != null, -1, E_INVALID_ARG, "[E_INVALID_ARG] Initial parameter not set."); + + _CertFormat format = pTempCert->GetCertFormat(); + + SysTryReturn(NID_SEC_CERT, format == _CERT_X509, -1, E_SYSTEM, "[E_SYSTEM] Unknown certificate format."); + pCert = reinterpret_cast< _X509Certificate* >(certificate); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + return pTbsCert->GetVersion(); +} + +result +_CertManager::GetValidity(CertificateHandle certificate, _CertValidityType* pValidity) +{ + _Certificate* pTempCert = reinterpret_cast< _Certificate* >(certificate); + _X509Certificate* pCert = null; + _X509TbsCert* pTbsCert = null; + Tizen::Base::DateTime notBefore; + Tizen::Base::DateTime notAfter; + Tizen::Base::DateTime curTime; + + SysTryReturnResult(NID_SEC_CERT, pTempCert != null, E_INVALID_ARG, "Initial parameter not set."); + + _CertFormat format = pTempCert->GetCertFormat(); + SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_SYSTEM, "Unknown certificate format."); + + pCert = reinterpret_cast< _X509Certificate* >(certificate); + + Tizen::System::SystemTime::GetCurrentTime(UTC_TIME, curTime); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + pTbsCert->GetBeforeTimes(notBefore); + pTbsCert->GetAfterTimes(notAfter); + if (curTime <= notAfter && curTime >= notBefore) + { + *pValidity = _CERT_VALIDITY_VALID; + } + else if (curTime < notBefore) + { + *pValidity = _CERT_VALIDITY_NOT_YET_VALID; + } + else if (curTime > notAfter) + { + *pValidity = _CERT_VALIDITY_EXPIRED; + } + return E_SUCCESS; + +} + +result +_CertManager::GetCertificateType(CertificateHandle certHandle, _CaCertType* pCertType) +{ + result r = E_SUCCESS; + char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, }; + int lenSubjectName = 0; + int lenIssuerName = 0; + _Certificate* pParentCert = reinterpret_cast< _Certificate* >(certHandle); + _X509Certificate* pCert = null; + _X509TbsCert* pTbsCert = null; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, pParentCert != null, E_INVALID_ARG, "Initial parameter not set."); + + + _CertFormat format = pParentCert->GetCertFormat(); + SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_SYSTEM, "Failed to get certificate format."); + + pCert = reinterpret_cast< _X509Certificate* >(certHandle); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Initial parameter not set."); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + lenSubjectName = strlen(reinterpret_cast< const char* >(pTbsCert->GetSubjectName())); + lenIssuerName = strlen(reinterpret_cast< const char* >(pTbsCert->GetIssuerName())); + SysTryReturnResult(NID_SEC_CERT, lenSubjectName > 0, E_SYSTEM, "Subject length is not valid."); + SysTryReturnResult(NID_SEC_CERT, lenIssuerName > 0, E_SYSTEM, "Issuer length is not valid."); + + strcpy(subjectName, reinterpret_cast< const char* >(pTbsCert->GetSubjectName())); + strcpy(issuerName, reinterpret_cast< const char* >(pTbsCert->GetIssuerName())); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->FindCertType(format, issuerName, subjectName, pCertType); + + if (IsFailed(r)) + { + *pCertType = _CERT_TYPE_MAX; + return E_SYSTEM; + } + + return E_SUCCESS; +} + +result +_CertManager::ParseCertTitle(char* pSubject, char* pTitle) +{ + char* pCNHeader = null; + char* pOUHeader = null; + char* pEailHeader = null; + char* pTrailer = null; + std::unique_ptr pOutputBuf(null); + int outputBufLen = 0; + + ClearLastResult(); + + SysTryReturn(NID_SEC_CERT, pSubject != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input parameter."); + + pCNHeader = strstr(pSubject, _CERT_COMMON_NAME); + pOUHeader = strstr(pSubject, _CERT_ORG_UNIT_NAME); + pEailHeader = strstr(pSubject, _CERT_EMAIL_ADDRESS); + if (pCNHeader != null) + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_COMMON_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_ORG_UNIT_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_ORG_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_STATE_OR_PROVINCE_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_STATE_OF_PROVINCE); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_LOCALITY_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_COUNTRY_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_EMAIL_ADDRESS); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pCNHeader + strlen(_CERT_COMMON_NAME), _CERT_DC); + if (pTrailer != null) + { + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME) - _MAX_GAP; + } + else + { + pTrailer = pCNHeader + strlen(pCNHeader); + outputBufLen = pTrailer - pCNHeader - strlen(_CERT_COMMON_NAME); + } + } + } + } + } + } + } + } + } + pOutputBuf = std::unique_ptr (new (std::nothrow) char[outputBufLen + 1]); + SysTryReturnResult(NID_SEC_CERT, pOutputBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pOutputBuf.get(), 0, outputBufLen + 1); + memcpy(pOutputBuf.get(), pCNHeader + strlen(_CERT_COMMON_NAME), outputBufLen); + } + else if (pOUHeader != null) + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_COMMON_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_ORG_UNIT_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_ORG_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_STATE_OR_PROVINCE_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_STATE_OF_PROVINCE); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_LOCALITY_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_COUNTRY_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_EMAIL_ADDRESS); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = strstr(pOUHeader + strlen(_CERT_ORG_UNIT_NAME), _CERT_DC); + if (pTrailer != null) + { + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME) - _MAX_GAP; + } + else + { + pTrailer = pOUHeader + strlen(pOUHeader); + outputBufLen = pTrailer - pOUHeader - strlen(_CERT_ORG_UNIT_NAME); + } + } + } + } + } + } + } + } + } + pOutputBuf = std::unique_ptr (new (std::nothrow) char[outputBufLen + 1]); + SysTryReturnResult(NID_SEC_CERT, pOutputBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memcpy(pOutputBuf.get(), pOUHeader + strlen(_CERT_ORG_UNIT_NAME), outputBufLen); + + } + else if (pEailHeader != null) + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_COMMON_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_ORG_UNIT_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_ORG_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_STATE_OR_PROVINCE_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_STATE_OF_PROVINCE); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_LOCALITY_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_COUNTRY_NAME); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_EMAIL_ADDRESS); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = strstr(pEailHeader + strlen(_CERT_EMAIL_ADDRESS), _CERT_DC); + if (pTrailer != null) + { + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS) - _MAX_GAP; + } + else + { + pTrailer = pEailHeader + strlen(pEailHeader); + outputBufLen = pTrailer - pEailHeader - strlen(_CERT_EMAIL_ADDRESS); + } + } + } + } + } + } + } + } + } + pOutputBuf = std::unique_ptr (new (std::nothrow) char[outputBufLen + 1]); + SysTryReturnResult(NID_SEC_CERT, pOutputBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pOutputBuf.get(), 0, outputBufLen + 1); + memcpy(pOutputBuf.get(), pEailHeader + strlen(_CERT_EMAIL_ADDRESS), outputBufLen); + } + else + { + SysLogException(NID_SEC_CERT, E_PARSING_FAILED, "[E_PARSING_FAILED] Failed to parse Certificate title."); + return E_SYSTEM; + } + strcpy(pTitle, pOutputBuf.get()); + + return E_SUCCESS; +} + +//User Certificate APIs +result +_CertManager::MakeParseAndVerifyCertChainBufferN(byte* pCertChainBuffer, int certChainLength, byte* pUserPrivateKeyBuffer, int userPrivateKeyLength, _CertChain** ppX509CertChain, _CertPrivateKeyInfo** ppX509PrivateKeyInfo) +{ + result r = E_SUCCESS; + int dataOffset = 0; + int currCertBufLen = 0; + int totCertCount = 0; + int bufSize = 0; + int countTotalCertificateChecked = 0; + int addedNumberCertificate = 0; + bool pubPriPair = false; + byte* pCertBuf = null; + byte* pCurrCertBuf = null; + _X509Certificate* pUserCert = null; + std::unique_ptr<_CertPrivateKeyInfo> pPKeyInfo(null); + + pCertBuf = pCertChainBuffer; + bufSize = certChainLength; + + SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_INVALID_ARG, "Invalid certificate chain buffer."); + SysTryReturnResult(NID_SEC_CERT, bufSize > 0, E_INVALID_ARG, "Invalid length of certificate chain buffer."); + + // Process Private Key + if (pUserPrivateKeyBuffer != null && userPrivateKeyLength > 0) + { + pPKeyInfo = std::unique_ptr<_CertPrivateKeyInfo> (new (std::nothrow) _CertPrivateKeyInfo(pUserPrivateKeyBuffer, userPrivateKeyLength)); + SysTryReturnResult(NID_SEC_CERT, pPKeyInfo != null, E_OUT_OF_MEMORY, "Failed allocate memory."); + } + + // Get Cert Count + while (dataOffset < bufSize) + { + pCurrCertBuf = pCertBuf + dataOffset; + currCertBufLen = _CertManager::GetBlockSize(pCurrCertBuf); + totCertCount++; + dataOffset += currCertBufLen; + } + + dataOffset = 0; + + std::unique_ptr<_CertChain> pCertChain(new (std::nothrow) _CertChain()); + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Failed to parse and verify certificate chain."); + + if (pPKeyInfo != null) + { + // Find Device/User Certificate + while (dataOffset < bufSize) + { + pCurrCertBuf = pCertBuf + dataOffset; + currCertBufLen = _CertManager::GetBlockSize(pCurrCertBuf); + + std::unique_ptr<_X509Certificate> pTmpCert(new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pTmpCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pTmpCert->Parse(pCurrCertBuf, currCertBufLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to parse and verify certificate chain."); + + r = _CertManager::CheckRsaPublicPrivateKeyPair(pTmpCert.get(), pPKeyInfo.get()); + if (!IsFailed(r)) + { + r = pCertChain->AddCertificate(pTmpCert.get()); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONDITION, "Failed to parse and verify certificate chain."); + + pubPriPair = true; + addedNumberCertificate++; + pUserCert = pTmpCert.release(); + break; + } + + dataOffset += currCertBufLen; + } + //Check key pair + SysTryReturnResult(NID_SEC_CERT, pubPriPair, E_INVALID_KEY, "Failed to parse and verify certificate chain."); + } + + dataOffset = 0; + + //As there is no private key present in chain, it is assumed that first certificate is user certificate + if (pUserCert == null) + { + pCurrCertBuf = pCertBuf + dataOffset; + currCertBufLen = _CertManager::GetBlockSize(pCurrCertBuf); + + std::unique_ptr<_X509Certificate> pUserCertAuto(new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pUserCertAuto != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pUserCertAuto->Parse(pCurrCertBuf, currCertBufLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to parse first certificate in chain."); + + r = pCertChain->AddCertificate(pUserCertAuto.get()); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONDITION, "Failed to add first certificate in chain. "); + + addedNumberCertificate++; + pUserCert = pUserCertAuto.release(); + } + + + while (totCertCount > addedNumberCertificate) + { + dataOffset = 0; + countTotalCertificateChecked++; + + if (countTotalCertificateChecked > totCertCount) + { + break; + } + + SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_INVALID_ARG, "Invalid certificate in chain. "); + + while (dataOffset < bufSize) + { + std::unique_ptr<_X509Certificate> pCurrentCert(new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CERT, pCurrentCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory. "); + + pCurrCertBuf = pCertBuf + dataOffset; + currCertBufLen = _CertManager::GetBlockSize(pCurrCertBuf); + + r = pCurrentCert->Parse(pCurrCertBuf, currCertBufLen); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to parse certificate in chain. "); + + if (pUserCert->IsIssuer(pCurrentCert.get())) + { + r = pCertChain->AddCertificate(pCurrentCert.get()); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONDITION, "Failed to add certificate in chain. "); + + pUserCert = pCurrentCert.release(); + addedNumberCertificate++; + break; + } + + dataOffset += currCertBufLen; + } + } + + //Here is the place where we verifying certificate chain before installation + r = pCertChain->VerifyCertChainWithDb(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to verify certificate chain.", GetErrorMessage(r)); + + *ppX509CertChain = pCertChain.release(); + *ppX509PrivateKeyInfo = pPKeyInfo.release(); + + return r; +} + +result +_CertManager::CheckRsaPublicPrivateKeyPair(_X509Certificate* pX509Certificate, _CertPrivateKeyInfo* pX509CertificatePrivateKey) +{ + result r = E_SUCCESS; + int retValue = 0; + EVP_PKEY* pPrivateKey = null; + int privateKeyLength = 0; + X509* pX509Cert = null; + const char* pSigalg = null; + + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_INVALID_ARG, "Invalid input parameter. "); + SysTryReturnResult(NID_SEC_CERT, pX509CertificatePrivateKey != null, E_INVALID_ARG, "Invalid input parameter."); + + pX509Cert = static_cast< X509* >(pX509Certificate->GetX509CertObject()); + SysTryReturnResult(NID_SEC_CERT, pX509Cert != null, E_SYSTEM, "Failed to parse certificate. "); + + //const char * + pSigalg = OBJ_nid2ln(OBJ_obj2nid(pX509Cert->sig_alg->algorithm)); + SysTryReturnResult(NID_SEC_CERT, pSigalg != null, E_SYSTEM, "Unable to get certificate algorithm."); + + if (strstr(pSigalg, "WithRSA")) + { + byte* pPriKey = null; + + pX509CertificatePrivateKey->GetPrivateKeyN(privateKeyLength, &pPriKey); + SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_SYSTEM, "Unable to get certificate private key."); + + std::unique_ptr pPriKeyBuf(pPriKey); + + pPrivateKey = d2i_PrivateKey(EVP_PKEY_RSA, null, const_cast< const unsigned char** >(static_cast< unsigned char** >(&pPriKey)), privateKeyLength); + if (pPrivateKey != null) + { + retValue = X509_check_private_key(pX509Cert, pPrivateKey); + + EVP_PKEY_free(pPrivateKey); + + SysTryReturnResult(NID_SEC_CERT, retValue == 1, E_SYSTEM, "Private public key mismatch, this key does not belong to this certificate."); + + + } + else + { + r = E_SYSTEM; + SysLog(NID_SEC_CERT, "Private key conversion failed."); + } + + + } + else + { + r = E_SYSTEM; + SysLog(NID_SEC_CERT, "Unsupported Algorithm = %s", pSigalg); + } + + + return r; +} + +result +_CertManager::GetCertificateSubjectNameN(CertificateHandle certificateHandle, byte** ppSubjectName, int* pSubjectNameLength) +{ + int len = 0; + byte* pBuf = null; + _Certificate* pTempCert = static_cast< _Certificate* >(certificateHandle); + _CertFormat format = pTempCert->GetCertFormat(); + + SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + + _X509Certificate* pCert = static_cast< _X509Certificate* >(certificateHandle); + pCert->GetIssuerBuffer(pBuf, len); + + *ppSubjectName = new (std::nothrow) byte[len]; + SysTryReturnResult(NID_SEC_CERT, *ppSubjectName != null, E_OUT_OF_MEMORY, "Failed to allocate memory. "); + + memset(*ppSubjectName, 0, len); + memcpy(*ppSubjectName, pBuf, len); + *pSubjectNameLength = len; + + return E_SUCCESS; +} + +result +_CertManager::GetCertificateIssuerNameN(CertificateHandle certificateHandle, byte** ppIssuerName, int* pIssuerNameLength) +{ + _Certificate* pTempCert = static_cast< _Certificate* >(certificateHandle); + _CertFormat format = pTempCert->GetCertFormat(); + byte* pBuf = null; + int len = 0; + + SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + + _X509Certificate* pCert = static_cast< _X509Certificate* >(certificateHandle); + pCert->GetSubjectNameBuffer(pBuf, len); + + *ppIssuerName = new (std::nothrow) byte[len]; + SysTryReturnResult(NID_SEC_CERT, *ppIssuerName != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + memset(*ppIssuerName, 0, len); + memcpy(*ppIssuerName, pBuf, len); + *pIssuerNameLength = len; + + return E_SUCCESS; +} + +CertificateStoreCtx +_CertManager::OpenUserCertificateStore(int& totalCount) +{ + result r = E_SUCCESS; + UserCertRecord certRecord = {0}; + _CertRootList* pHoldList = null; + _CertFileStore fileStore; + CertificateStoreCtx certificateStoreCtx = null; + int certLength = 0; + char condition[_MAX_TYPE_CONST_SIZE] = {0}; + char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + ClearLastResult(); + + totalCount = 0; + + sprintf(condition, "installed = '%s'", installedRecord); + + std::unique_ptr<_UserCertDbStore> pUserCertDbStore(new (std::nothrow) _UserCertDbStore()); + SysTryReturn(NID_SEC_CERT, pUserCertDbStore != null, certificateStoreCtx, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pUserCertDbStore->GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, r, "[%s] Failed to get first certificate record.", GetErrorMessage(r)); + + std::unique_ptr<_CertRootList> pCertListFirstNode(new (std::nothrow) _CertRootList()); + SysTryReturn(NID_SEC_CERT, pCertListFirstNode != null, certificateStoreCtx, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + std::unique_ptr<_CertRootCaInfo> pRootCa(new (std::nothrow) _CertRootCaInfo()); + SysTryReturn(NID_SEC_CERT, pRootCa != null, certificateStoreCtx, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pRootCa.get(), 0, sizeof(*pRootCa.get())); + pCertListFirstNode->pNext = null; + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, E_SYSTEM, "E_SYSTEM Failed to set file handle."); + + r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertListFirstNode->certificate), certLength); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, E_SYSTEM, "E_SYSTEM Failed to read from file."); + + pCertListFirstNode->length = certLength; + pCertListFirstNode->format = (_CertFormat) certRecord.certFormat; + + pRootCa->pRootList = pHoldList = pCertListFirstNode.release(); + + certificateStoreCtx = (CertificateStoreCtx) pRootCa.release(); + + totalCount++; + + while ((pUserCertDbStore->GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId)) == E_SUCCESS) + { + std::unique_ptr<_CertRootList> pCertList(new (std::nothrow) _CertRootList()); + SysTryReturn(NID_SEC_CERT, pCertList != null, certificateStoreCtx, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, E_SYSTEM, "[E_SYSTEM] Failed to set file handle."); + + r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), certLength); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, E_SYSTEM, "[E_SYSTEM] Failed to read from file."); + + pCertList->pNext = null; + pCertList->length = certLength; + pCertList->format = (_CertFormat) certRecord.certFormat; + + pHoldList->pNext = pCertList.release(); + pHoldList = pHoldList->pNext; + + totalCount++; + } + + SetLastResult(E_SUCCESS); //To clear the result of GetNextRecordByCondition function + + return certificateStoreCtx; +} + + +CertificateStoreCtx +_CertManager::OpenRootCaStore(_CaCertType type, int& totalCount) // _CERT_TYPE_TRUSTED_CA or _CERT_TYPE_ROOT_CA, ? +{ + result r = E_SUCCESS; + CaCertRecord certRecord = {0}; + _CertRootList* pHoldList = null; + _CertFileStore fileStore; + CertificateStoreCtx certificateStoreCtx = null; + int certLength = 0; + char condition[_MAX_TYPE_CONST_SIZE] = {0}; + char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0"; + + ClearLastResult(); + + totalCount = 0; + + SysTryReturn(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, certificateStoreCtx, E_INVALID_ARG, "[E_INVALID_ARG] Invalid certificate type."); + SysTryReturn(NID_SEC_CERT, type < _CERT_TYPE_MAX, certificateStoreCtx, E_INVALID_ARG, "[E_INVALID_ARG] Invalid certificate type."); + + sprintf(condition, "certType = %d and installed = '%s'", static_cast< int >(type), installedRecord); + + std::unique_ptr<_CaCertDbStore> pCaCertDbStore(new (std::nothrow) _CaCertDbStore()); + SysTryReturn(NID_SEC_CERT, pCaCertDbStore != null, certificateStoreCtx, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pCaCertDbStore->GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, r, "[%s] Failed to get first certificate record.", GetErrorMessage(r)); + + std::unique_ptr<_CertRootList> pCertListFirstNode(new (std::nothrow) _CertRootList()); + SysTryReturn(NID_SEC_CERT, pCertListFirstNode != null, certificateStoreCtx, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + std::unique_ptr<_CertRootCaInfo> pRootCa(new (std::nothrow) _CertRootCaInfo()); + SysTryReturn(NID_SEC_CERT, pRootCa != null, certificateStoreCtx, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pRootCa.get(), 0, sizeof(*pRootCa.get())); + pCertListFirstNode->pNext = null; + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, E_SYSTEM, "[E_SYSTEM] Failed to set file handle."); + + r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertListFirstNode->certificate), certLength); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, E_SYSTEM, "[E_SYSTEM] Failed to read from file."); + + pCertListFirstNode->length = certLength; + pCertListFirstNode->format = (_CertFormat) certRecord.certFormat; + + pRootCa->pRootList = pHoldList = pCertListFirstNode.release(); + + certificateStoreCtx = (CertificateStoreCtx) pRootCa.release(); + + totalCount++; + + while ((pCaCertDbStore->GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId)) == E_SUCCESS) + { + std::unique_ptr<_CertRootList> pCertList(new (std::nothrow) _CertRootList()); + SysTryReturn(NID_SEC_CERT, pCertList != null, certificateStoreCtx, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, E_SYSTEM, "[E_SYSTEM] Failed to set file handle."); + r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), certLength); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), certificateStoreCtx, E_SYSTEM, "[E_SYSTEM] Failed to read from file."); + + pCertList->pNext = null; + pCertList->length = certLength; + pCertList->format = (_CertFormat) certRecord.certFormat; + + pHoldList->pNext = pCertList.release(); + pHoldList = pHoldList->pNext; + + totalCount++; + } + + SetLastResult(E_SUCCESS); //To clear the result of GetNextRecordByCondition function + + return certificateStoreCtx; +} + + +enum _Asn1EncodingStyle +{ + _ASN1_ENCODING_TYPE_PRIMITIVE = 0x00, + _ASN1_ENCODING_TYPE_CONSTRUCTED = 0x20, + _ASN1_ENCODING_TYPE_UNKNOWN = 0xFF +}; //_Asn1EncodingStyle + + +static const int _CERT_ASN1_TAG_CHECK_BIT_ = 0x7F; +static const int _CERT_ASN1_LENGTH_CHECK_BIT_ = 0x80; +static const int _CERT_ASN1_ENCODING_TYPE_OFFSET_ = 0x20; + +int +_CertManager::GetBlockSize(byte* pBuf) +{ + int length = 0; + int retVal = -1; + int contentLength = 0; + _Asn1EncodingStyle encodingType = _ASN1_ENCODING_TYPE_PRIMITIVE; + + + ClearLastResult(); + SysTryReturn(NID_SEC_CERT, pBuf != null, retVal, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument."); + + encodingType = (_Asn1EncodingStyle) (pBuf[0] & _CERT_ASN1_ENCODING_TYPE_OFFSET_); + + if (pBuf[1] > _CERT_ASN1_TAG_CHECK_BIT_) + { + // Length is in indefinite form + if (pBuf[1] == _CERT_ASN1_LENGTH_CHECK_BIT_) + { + // STRICT: indefinite form cannot be used with Primitive encoding + SysTryReturn(NID_SEC_CERT, encodingType != _ASN1_ENCODING_TYPE_PRIMITIVE, retVal, E_INVALID_CONTENT, "[E_INVALID_CONTENT] Encoding type is not valid."); + //For the indefinite form, the length octets indicate that the contents octets are terminated by end-of-contents + //octets (see 8.1.5), and shall consist of a single octet. + // 0x80 0x00 0x00 + contentLength = 2; //4 + } + // Length is in Long form + else + { + int count = 0; + int lenpos = 0; + //STRICT: Size cannot be seven "1" bits + + SysTryReturn(NID_SEC_CERT, !(((pBuf[1]) & _CERT_ASN1_TAG_CHECK_BIT_) == _CERT_ASN1_TAG_CHECK_BIT_), retVal, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument."); + + count = (pBuf[1]) & _CERT_ASN1_TAG_CHECK_BIT_; + length = 0; + for (lenpos = 2; lenpos < 2 + count; ++lenpos) + { + length = (length << 8) | pBuf[lenpos]; + } + contentLength = lenpos; + } + } + // Length is in short form + else + { + length = pBuf[1]; + contentLength = 2; + } + + length += contentLength; + return length; +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertManager.h b/src/security/cert/FSecCert_CertManager.h new file mode 100755 index 0000000..e5951ee --- /dev/null +++ b/src/security/cert/FSecCert_CertManager.h @@ -0,0 +1,99 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertManager.h + * @brief This header file contains the declarations of Certificate Manager class. + * + * This header file contains the declarations of Certificate Manager class which manage all SVC calls. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_MANAGER_H_ +#define _FSEC_CERT_INTERNAL_CERT_MANAGER_H_ + +#include "FSecCert_CertChain.h" +#include "FSecCert_CertPrivateKeyInfo.h" +#include "FSecCert_Certificate.h" +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertManager +{ +public: + static result CreateCrtFile(void); + + static result OpenContext(_CertContextType type, CertChainCtx* pHCertCtx); + + static result AddCertificate(CertChainCtx certCtx, byte* pCert, int certLen); + + static result VerifyChain(CertChainCtx certCtx, _CertDomainType* pDomain); + + static result VerifyCertificate(CertificateHandle certHandle, byte* pPublickey, int keyLen); + + static result GetPubKeyN(byte* pPublickey, int pubkeyLen, int& keyLen, byte** ppModulus, int& expLen, byte** ppExponent); + + static _CertFormat GetEncodedCertBuffer(byte* pCertBuffer, int certBufferLen, byte** pDerCertBuffer, int* pDerCertBufferLength, _CertEncodingType* encodingType); + + static result GetChainDepth(CertChainCtx certCtx, int* pDepth); + + static result GetNthCertificate(CertChainCtx certCtx, int nth, CertificateHandle* pCertHandle); + + static result GetCertBuffer(CertificateHandle certHandle, char** ppCertbuffer, int* pCertLen); + + static result CloseContext(CertChainCtx certCtx); + + static result GetCertInfo(CertificateHandle certHandle, _CertFieldType field, _CertFieldInfos* pCertInfo); + + static result GetPublicKey(CertificateHandle certificate, char* pBuffer, int* pBufLen); + + static result GetSignature(CertificateHandle certificate, char* pBuffer, int* pBufLen); + + static int GetVersion(CertificateHandle certificate); + + static result GetValidity(CertificateHandle certificate, _CertValidityType* pValidity); + + static result GetCertificateType(CertificateHandle certHandle, _CaCertType* pCertType); + + //User Certificate APIs + + static result MakeParseAndVerifyCertChainBufferN(byte* pCertChainBuffer, int certChainLength, byte* pUserPrivateKeyBuffer, int userPrivateKeyLength, _CertChain** ppX509CertChain, _CertPrivateKeyInfo** ppX509PrivateKeyInfo); + + static result CheckRsaPublicPrivateKeyPair(_X509Certificate* pX509Certificate, _CertPrivateKeyInfo* pX509CertificatePrivateKey); + + static result GetCertificateSubjectNameN(CertificateHandle certificateHandle, byte** ppSubjectName, int* pSubjectNameLength); + + static result GetCertificateIssuerNameN(CertificateHandle certificateHandle, byte** ppIssuerName, int* pIssuerNameLength); + + static CertificateStoreCtx OpenUserCertificateStore(int& count); + + static int GetBlockSize(byte* pBuf); + + static CertificateStoreCtx OpenRootCaStore(_CaCertType type, int& count); + +private: + static result ParseCertTitle(char* pSubject, char* pTitle); + + _CertManager(const _CertManager& rhs); + + _CertManager& operator =(const _CertManager& rhs); +}; //_CertManager + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_MANAGER_H_ diff --git a/src/security/cert/FSecCert_CertMgrMessages.cpp b/src/security/cert/FSecCert_CertMgrMessages.cpp new file mode 100755 index 0000000..b7640f8 --- /dev/null +++ b/src/security/cert/FSecCert_CertMgrMessages.cpp @@ -0,0 +1,46 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertMgrMessages.cpp + * @brief This is the implementation file for the _CertMgrMessages class. + */ + +#define IPC_MESSAGE_IMPL +#include "FSecCert_CertMgrMessages.h" + +// Generate constructors. +#include +#include "FSecCert_CertMgrMessages.h" +// Generate destructors. + +#include +#include "FSecCert_CertMgrMessages.h" + +// Generate param traits write methods. +#include +namespace IPC +{ +#include "FSecCert_CertMgrMessages.h" +} // namespace IPC + +// Generate param traits read methods. +#include +namespace IPC +{ +#include "FSecCert_CertMgrMessages.h" +} // namespace IPC diff --git a/src/security/cert/FSecCert_CertMgrMessages.h b/src/security/cert/FSecCert_CertMgrMessages.h new file mode 100755 index 0000000..43e46d5 --- /dev/null +++ b/src/security/cert/FSecCert_CertMgrMessages.h @@ -0,0 +1,307 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertMgrMessages.h + * @brief This is the header file for the CertMgr IPC message types. + * + * This is the header file for the CertMgr IPC message types. + */ + +#include +#include +#include +#include "FSecCert_CertTypes.h" + +#define IPC_MESSAGE_START CertMgrServiceStart + +#ifndef _FSEC_CERT_INTERNAL_CERT_MANAGER_MESSAGES_H_ +#define _FSEC_CERT_INTERNAL_CERT_MANAGER_MESSAGES_H_ + +namespace IPC +{ +template< > +struct ParamTraits< Tizen::Security::Cert::_CertFieldInfos > +{ + typedef Tizen::Security::Cert::_CertFieldInfos param_type; + static void Write(Message* pMesg, const param_type& params) + { + pMesg->WriteInt(params.certType); + pMesg->WriteInt(params.certFileId); + pMesg->WriteBytes(static_cast< const void* >(params.serialNo), Tizen::Security::Cert::_MAX_SERIAL_NUMBER_SIZE + 1); + pMesg->WriteBytes(static_cast< const void* >(params.sigAlgorithm), Tizen::Security::Cert::_MAX_CERT_ALGORITHM_SIZE + 1); + pMesg->WriteBytes(static_cast< const void* >(params.validityFrom), Tizen::Security::Cert::_MAX_CERT_VALIDITY_SIZE + 1); + pMesg->WriteBytes(static_cast< const void* >(params.validityTo), Tizen::Security::Cert::_MAX_CERT_VALIDITY_SIZE + 1); + pMesg->WriteBytes(static_cast< const void* >(params.subjectName), Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + pMesg->WriteBytes(static_cast< const void* >(params.issuerName), Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + pMesg->WriteBytes(static_cast< const void* >(params.fingerPrint), Tizen::Security::Cert::_MAX_CERT_FINGERPRINT_SIZE + 1); + pMesg->WriteInt(params.fingerPrintLen); + pMesg->WriteBytes(static_cast< const void* >(params.publicKey), Tizen::Security::Cert::_MAX_CERT_PUBLIC_KEY_SIZE + 1); + pMesg->WriteBytes(static_cast< const void* >(params.certTypeFormat), Tizen::Security::Cert::_MAX_CERT_TYPE_SIZE + 1); + pMesg->WriteInt(params.certVersion); + pMesg->WriteBytes(static_cast< const void* >(params.certTitle), Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + pMesg->WriteBytes(static_cast< const void* >(params.certSubTitle), Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + + } + static bool Read(const Message* pMesg, void** ppIter, param_type* pParam) + { + const char* pBuffer = null; + int value = 0; + + pMesg->ReadInt(ppIter, &value); + pParam->certType = static_cast< Tizen::Security::Cert::_CaCertType >(value); + + pMesg->ReadInt(ppIter, &value); + pParam->certFileId = value; + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_SERIAL_NUMBER_SIZE + 1); + memcpy(pParam->serialNo, pBuffer, Tizen::Security::Cert::_MAX_SERIAL_NUMBER_SIZE + 1); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_ALGORITHM_SIZE + 1); + memcpy(pParam->sigAlgorithm, pBuffer, Tizen::Security::Cert::_MAX_CERT_ALGORITHM_SIZE + 1); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_VALIDITY_SIZE + 1); + memcpy(pParam->validityFrom, pBuffer, Tizen::Security::Cert::_MAX_CERT_VALIDITY_SIZE + 1); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_VALIDITY_SIZE + 1); + memcpy(pParam->validityTo, pBuffer, Tizen::Security::Cert::_MAX_CERT_VALIDITY_SIZE + 1); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + memcpy(pParam->subjectName, pBuffer, Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + memcpy(pParam->issuerName, pBuffer, Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_FINGERPRINT_SIZE + 1); + memcpy(pParam->fingerPrint, pBuffer, Tizen::Security::Cert::_MAX_CERT_FINGERPRINT_SIZE + 1); + + pMesg->ReadInt(ppIter, &value); + pParam->fingerPrintLen = value; + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_PUBLIC_KEY_SIZE + 1); + memcpy(pParam->publicKey, pBuffer, Tizen::Security::Cert::_MAX_CERT_PUBLIC_KEY_SIZE + 1); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_TYPE_SIZE + 1); + memcpy(pParam->certTypeFormat, pBuffer, Tizen::Security::Cert::_MAX_CERT_TYPE_SIZE + 1); + + pMesg->ReadInt(ppIter, &value); + pParam->certVersion = value; + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + memcpy(pParam->certTitle, pBuffer, Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + memcpy(pParam->certSubTitle, pBuffer, Tizen::Security::Cert::_MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + + return true; + } + static void Log(const param_type& p, std::string* l) + { + + } +}; + +template< > +struct ParamTraits< Tizen::Security::Cert::_CertificateListInfo > +{ + typedef Tizen::Security::Cert::_CertificateListInfo param_type; + static void Write(Message* pMesg, const param_type& params) + { + int count = 0; + int index = 0; + + param_type* pTemp = const_cast< param_type* >(¶ms); + + while (pTemp) + { + pTemp = pTemp->pNext; + count++; + } + + pMesg->WriteInt(count); + + pTemp = const_cast< param_type* >(¶ms); + for (index = 0; index < count; index++) + { + pMesg->WriteInt(pTemp->certFileId); + pMesg->WriteInt(pTemp->format); + pMesg->WriteInt(pTemp->certType); + pMesg->WriteInt(pTemp->length); + pMesg->WriteInt(pTemp->priKeyLen); + pMesg->WriteBytes(static_cast< const void* >(pTemp->certificate), Tizen::Security::Cert::_MAX_CERTIFICATE_SIZE); + pMesg->WriteBytes(static_cast< const void* >(pTemp->privatekey), Tizen::Security::Cert::_MAX_CERT_PRIVATE_KEY_SIZE); + + pTemp = pTemp->pNext; + + + } + + } + static bool Read(const Message* pMesg, void** ppIter, param_type* pParam) + { + const char* pBuffer = null; + int value = 0; + int count = 0; + int index = 1; + param_type* pCurrentNode = pParam; + param_type* pNewNode = null; + + pMesg->ReadInt(ppIter, &count); + + if (count <= 0) + { + return true; + } + + pMesg->ReadInt(ppIter, &value); + pCurrentNode->certFileId = value; + + pMesg->ReadInt(ppIter, &value); + pCurrentNode->format = static_cast< Tizen::Security::Cert::_CertFormat >(value); + + pMesg->ReadInt(ppIter, &value); + pCurrentNode->certType = static_cast< Tizen::Security::Cert::_CaCertType >(value); + + pMesg->ReadInt(ppIter, &value); + pCurrentNode->length = value; + + pMesg->ReadInt(ppIter, &value); + pCurrentNode->priKeyLen = value; + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERTIFICATE_SIZE); + memcpy(pCurrentNode->certificate, pBuffer, Tizen::Security::Cert::_MAX_CERTIFICATE_SIZE); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_PRIVATE_KEY_SIZE); + memcpy(pCurrentNode->privatekey, pBuffer, Tizen::Security::Cert::_MAX_CERT_PRIVATE_KEY_SIZE); + + pCurrentNode->pNext = null; + + for (index = 1; index < count; index++) + { + pNewNode = new (std::nothrow) param_type(); + SysTryReturn(NID_SEC_CERT, pNewNode != null, false, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] failed to allocate memory"); + + pMesg->ReadInt(ppIter, &value); + pNewNode->certFileId = value; + + pMesg->ReadInt(ppIter, &value); + pNewNode->format = static_cast< Tizen::Security::Cert::_CertFormat >(value); + + pMesg->ReadInt(ppIter, &value); + pNewNode->certType = static_cast< Tizen::Security::Cert::_CaCertType >(value); + + pMesg->ReadInt(ppIter, &value); + pNewNode->length = value; + + pMesg->ReadInt(ppIter, &value); + pNewNode->priKeyLen = value; + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERTIFICATE_SIZE); + memcpy(pNewNode->certificate, pBuffer, Tizen::Security::Cert::_MAX_CERTIFICATE_SIZE); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_PRIVATE_KEY_SIZE); + memcpy(pNewNode->privatekey, pBuffer, Tizen::Security::Cert::_MAX_CERT_PRIVATE_KEY_SIZE); + + pNewNode->pNext = null; + + pCurrentNode->pNext = pNewNode; + + pCurrentNode = pNewNode; + } + + return true; + } + static void Log(const param_type& p, std::string* l) + { + + } +}; + +template< > +struct ParamTraits< Tizen::Security::Cert::_CertInfo > +{ + typedef Tizen::Security::Cert::_CertInfo param_type; + + static void Write(Message* pMesg, const param_type& params) + { + pMesg->WriteInt(params.certId); + pMesg->WriteInt(params.certFormat); + pMesg->WriteInt(params.certType); + pMesg->WriteInt(params.certLength); + pMesg->WriteInt(params.privateKeyLen); + pMesg->WriteBytes(static_cast< const void* >(params.certificate), Tizen::Security::Cert::_MAX_CERTIFICATE_SIZE); + pMesg->WriteBytes(static_cast< const void* >(params.privatekey), Tizen::Security::Cert::_MAX_CERT_PRIVATE_KEY_SIZE); + + } + + static bool Read(const Message* pMesg, void** ppIter, param_type* pParam) + { + const char* pBuffer = null; + int value = 0; + + pMesg->ReadInt(ppIter, &value); + pParam->certId = value; + + pMesg->ReadInt(ppIter, &value); + pParam->certFormat = static_cast< Tizen::Security::Cert::_CertFormat >(value); + + pMesg->ReadInt(ppIter, &value); + pParam->certType = static_cast< Tizen::Security::Cert::_CaCertType >(value); + + pMesg->ReadInt(ppIter, &value); + pParam->certLength = value; + + pMesg->ReadInt(ppIter, &value); + pParam->privateKeyLen = value; + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERTIFICATE_SIZE); + memcpy(pParam->certificate, pBuffer, Tizen::Security::Cert::_MAX_CERTIFICATE_SIZE); + + pMesg->ReadBytes(ppIter, &pBuffer, Tizen::Security::Cert::_MAX_CERT_PRIVATE_KEY_SIZE); + memcpy(pParam->privatekey, pBuffer, Tizen::Security::Cert::_MAX_CERT_PRIVATE_KEY_SIZE); + + return true; + } + static void Log(const param_type& p, std::string* l) + { + + } +}; +} + +#endif // _FSEC_CERT_INTERNAL_CERT_MANAGER_MESSAGES_H_ + +IPC_SYNC_MESSAGE_CONTROL0_1(CertService_GetName, result); +IPC_SYNC_MESSAGE_CONTROL1_1(CertService_CloseCertificateStore, int, result); +IPC_SYNC_MESSAGE_CONTROL1_3(CertService_OpenCertificateStoreByType, int, int, int, result); +IPC_SYNC_MESSAGE_CONTROL1_2(CertService_GetCertificateCount, int, int, result); +IPC_SYNC_MESSAGE_CONTROL2_2(CertService_GetNextCertificate, int, int, Tizen::Io::_IpcBuffer, result); +IPC_SYNC_MESSAGE_CONTROL3_1(CertService_InsertRootCa, int, Tizen::Io::_IpcBuffer, int, result); +IPC_SYNC_MESSAGE_CONTROL3_1(CertService_UpdateRootCa, int, Tizen::Io::_IpcBuffer, Tizen::Io::_IpcBuffer, result); +IPC_SYNC_MESSAGE_CONTROL3_1(CertService_RemoveRootCa, int, Tizen::Io::_IpcBuffer, int, result); +IPC_SYNC_MESSAGE_CONTROL1_1(CertService_UninstallUserRootCertificateByCertId, int, result); +IPC_SYNC_MESSAGE_CONTROL4_1(CertService_InsertCaCertificate, int, int, Tizen::Io::_IpcBuffer, long, result); +IPC_SYNC_MESSAGE_CONTROL3_1(CertService_InsertUserCaCertificate, int, Tizen::Io::_IpcBuffer, int, result); +IPC_SYNC_MESSAGE_CONTROL1_1(CertService_InstallUserRootCertificate, Tizen::Io::_IpcBuffer, result); +IPC_SYNC_MESSAGE_CONTROL4_1(CertService_InsertUserCertChainPrivateKey, Tizen::Io::_IpcBuffer, int, Tizen::Io::_IpcBuffer, int, result); +IPC_SYNC_MESSAGE_CONTROL2_1(CertService_InsertCertificateChainWithPrivateKey, Tizen::Io::_IpcBuffer, int, result); +IPC_SYNC_MESSAGE_CONTROL2_1(CertService_InstallPkcs12Content, Tizen::Io::_IpcBuffer, Tizen::Io::_IpcBuffer, result); +IPC_SYNC_MESSAGE_CONTROL1_1(CertService_DeleteUserCertificateByCertId, int, result); +IPC_SYNC_MESSAGE_CONTROL1_1(CertService_DeleteUserCertChainByCertId, int, result); +IPC_SYNC_MESSAGE_CONTROL4_2(CertService_GetUserCertChainByIssuerAndSubjectNameN, Tizen::Io::_IpcBuffer, int, Tizen::Io::_IpcBuffer, int, Tizen::Security::Cert::_CertificateListInfo, result); +IPC_SYNC_MESSAGE_CONTROL2_2(CertService_GetUserCertificateByCertIdN, int, int, Tizen::Security::Cert::_CertInfo, result); +IPC_SYNC_MESSAGE_CONTROL1_2(CertService_GetUserCertFieldInfoByCertId, int, Tizen::Security::Cert::_CertFieldInfos, result); diff --git a/src/security/cert/FSecCert_CertOidDef.h b/src/security/cert/FSecCert_CertOidDef.h new file mode 100755 index 0000000..1417e63 --- /dev/null +++ b/src/security/cert/FSecCert_CertOidDef.h @@ -0,0 +1,91 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertOidDef.h + * @brief This header file contains the declarations of Certificate OID List. + * + * This header file contains the declarations of Certificate OID List. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_OID_DEF_H_ +#define _FSEC_CERT_INTERNAL_CERT_OID_DEF_H_ + +namespace Tizen { namespace Security { namespace Cert +{ + +const char* const _OID_AES_128_CBC = "2.16.840.1.101.3.4.1.2"; +const char* const _OID_AES_192_CBC = "2.16.840.1.101.3.4.1.22"; +const char* const _OID_AES_256_CBC = "2.16.840.1.101.3.4.1.42"; +const char* const _OID_DES_CBC = "1.3.14.3.2.7"; +const char* const _OID_RC2_CBC = "1.2.840.113549.3.2"; +const char* const _OID_RC5_CBC = "1.2.840.113549.3.8"; +const char* const _OID_IDEA_CBC = "1.3.6.1.4.1.188.7.1.1.2"; +const char* const _OID_ECC = "1.2.840.10045.2.1"; +const char* const _OID_DES_CBC_EDE3 = "1.2.840.113549.3.7"; +const char* const _OID_SIG_SHA1_RSA = "1.2.840.113549.1.1.5"; +const char* const _OID_SIG_MD5_RSA = "1.2.840.113549.1.1.4"; +const char* const _OID_SIG_MD2_RSA = "1.2.840.113549.1.1.2"; +const char* const _OID_SIG_SHA_224_RSA = "1.2.840.113549.1.1.14"; +const char* const _OID_SIG_SHA_256_RSA = "1.2.840.113549.1.1.11"; +const char* const _OID_SIG_SHA_384_RSA = "1.2.840.113549.1.1.12"; +const char* const _OID_SIG_SHA_512_RSA = "1.2.840.113549.1.1.13"; +const char* const _OID_HASH_SHA1 = "1.3.14.3.2.26"; +const char* const _OID_CERT_COMMON_NAME = "2.5.4.3"; +const char* const _OID_CERT_ORG_UNIT_NAME = "2.5.4.11"; +const char* const _OID_CERT_ORG_NAME = "2.5.4.10"; +const char* const _OID_CERT_LOCALITY_NAME = "2.5.4.7"; +const char* const _OID_CERT_STATE_OR_PROVINCE_NAME = "2.5.4.8"; +const char* const _OID_CERT_COUNTRY_NAME = "2.5.4.6"; +const char* const _OID_CERT_EMAIL_ADDRESS = "1.2.840.113549.1.9.1"; +const char* const _OID_CERT_SERIAL_NUM = "2.5.4.5"; +const char* const _OID_CERT_GIVEN_NAME = "2.5.4.42"; +const char* const _OID_CERT_SUR_NAME = "2.5.4.4"; +const char* const _OID_SUBJECT_DIRECTORY_ATTRIBUTES = "2.5.29.9"; +const char* const _OID_SUBJECT_KEY_IDENTIFIER = "2.5.29.14"; +const char* const _OID_KEY_USAGE = "2.5.29.15"; +const char* const _OID_PRIVATE_KEY_USAGE_PERIOD = "2.5.29.16"; +const char* const _OID_SUBJECT_ALT_NAME = "2.5.29.17"; +const char* const _OID_ISSUER_ALT_NAME = "2.5.29.18"; +const char* const _OID_BASIC_CONSTRAINTS = "2.5.29.19"; +const char* const _OID_CRL_NUMBER = "2.5.29.20"; +const char* const _OID_CRL_REASON_CODE = "2.5.29.21"; +const char* const _OID_INSTRUCTION_CODE = "2.5.29.23"; +const char* const _OID_INVALIDITY_DATE = "2.5.29.24"; +const char* const _OID_DELTA_CRL_INDICATOR = "2.5.29.27"; +const char* const _OID_ISSUING_DISTRIBUTION_POINT = "2.5.29.28"; +const char* const _OID_CERTIFICATE_ISSUER = "2.5.29.29"; +const char* const _OID_NAME_CONSTRAINT = "2.5.29.30"; +const char* const _OID_CRL_DISTRIBUTION_POINT = "2.5.29.31"; +const char* const _OID_CERTIFICATE_POLICIES = "2.5.29.32"; +const char* const _OID_POLICY_MAPPINGS = "2.5.29.33"; +const char* const _OID_AUTHORITY_KEY_IDENTIFIER = "2.5.29.35"; +const char* const _OID_POLICY_CONSTRAINTS = "2.5.29.36"; +const char* const _OID_EXT_KEY_USAGE = "2.5.29.37"; +const char* const _OID_OCSP_NONCE = "1.3.6.1.5.5.7.48.1.2"; +const char* const _OID_OCSP_NO_CHECK = "1.3.6.1.5.5.7.48.1.5"; +const char* const _OID_OCSP = "1.3.6.1.5.5.7.48.1"; +const char* const _OID_CA_ISSUERS = "1.3.6.1.5.5.7.48.2"; +const char* const _OID_AUTHORITY_INFO_ACCESS = "1.3.6.1.5.5.7.1.1"; +const char* const _OID_OCSP_SIGNING = "1.3.6.1.5.5.7.3.9"; +const char* const _OID_DRM_AGENT = "2.23.43.6.1.2"; +const char* const _OID_OMA_KP_RIGHTS_ISSUER = "2.23.43.6.1.1"; +const char* const _OID_REVOKED_CERTIFICATE_RANGE = "1.3.6.1.4.1.21888.1"; + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_OID_DEF_H_ diff --git a/src/security/cert/FSecCert_CertPrivateKeyInfo.cpp b/src/security/cert/FSecCert_CertPrivateKeyInfo.cpp new file mode 100644 index 0000000..9ab22b7 --- /dev/null +++ b/src/security/cert/FSecCert_CertPrivateKeyInfo.cpp @@ -0,0 +1,309 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertPrivateKeyInfo.cpp + * @brief This file contains implementation of X509 Certificate private key. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertPrivateKeyInfo.h" + +using namespace Tizen::Base; +using namespace Tizen::Io; +using namespace Tizen::Security; + +namespace Tizen { namespace Security { namespace Cert +{ + +_CertPrivateKeyInfo::_CertPrivateKeyInfo(void) + : __privateKeyLen(0) + , __pPrivateKey(null) +{ +} + + +_CertPrivateKeyInfo::_CertPrivateKeyInfo(char* pFileName) + : __privateKeyLen(0) + , __pPrivateKey(null) +{ + SetPrivateKey(pFileName); +} + +_CertPrivateKeyInfo::_CertPrivateKeyInfo(byte* pBuf, int bufSize) +{ + __privateKeyLen = bufSize; + __pPrivateKey = std::unique_ptr (new (std::nothrow) byte[bufSize]); + SysTryReturnVoidResult(NID_SEC_CERT, __pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memcpy(__pPrivateKey.get(), pBuf, bufSize); +} + +_CertPrivateKeyInfo::~_CertPrivateKeyInfo() +{ +} + +// return DER encoded form +void +_CertPrivateKeyInfo::GetPrivateKeyN(int& keyLen, byte** ppPrivKey) +{ + SysTryReturnVoidResult(NID_SEC_CERT, __pPrivateKey != null, E_SYSTEM, "Private key is not set."); + keyLen = __privateKeyLen; + *ppPrivKey = new (std::nothrow) byte[keyLen + 1]; + SysTryReturnVoidResult(NID_SEC_CERT, *ppPrivKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(*ppPrivKey, 0, keyLen + 1); + memcpy(*ppPrivKey, __pPrivateKey.get(), keyLen); +} + +result +_CertPrivateKeyInfo::GetEncDecPrivateKeyN(int& keyLen, byte** ppPrivKey, int encDecBit) +{ + result r = E_SUCCESS; + byte uniqueKey[16] = {0}; + byte ivData[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; + int aesBlockLen = 16; + int outLength = 0; + int lenData = 0; + int err = 0; + EVP_CIPHER_CTX ctx; + + std::unique_ptr pSecKey(reinterpret_cast< ISecretKey* >(_DeviceKeyGenerator::GenerateDeviceKeyN(aesBlockLen))); + SysTryReturnResult(NID_SEC_CERT, pSecKey != null, E_SYSTEM, "Failed to generate secret key."); + + std::unique_ptr pKeyBuf(pSecKey->GetEncodedN()); + SysAssertf(pKeyBuf != null, "Failed to get encoded secret key."); + + memset(uniqueKey, 0, aesBlockLen); + memcpy(uniqueKey, reinterpret_cast< const char* >(pKeyBuf->GetPointer()), aesBlockLen); + + *ppPrivKey = new (std::nothrow) byte[__privateKeyLen + aesBlockLen + 1]; + SysTryReturnResult(NID_SEC_CERT, *ppPrivKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(*ppPrivKey, 0, __privateKeyLen + aesBlockLen + 1); + + if (encDecBit) + { + EVP_CIPHER_CTX_init(&ctx); + + err = EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), null, uniqueKey, ivData, encDecBit); + SysTryCatch(NID_SEC_CERT, err == 1, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to initialized cipher."); + + err = EVP_CipherUpdate(&ctx, *ppPrivKey, &keyLen, __pPrivateKey.get(), __privateKeyLen); + SysTryCatch(NID_SEC_CERT, err == 1, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to update cipher."); + + err = EVP_CipherFinal_ex(&ctx, *ppPrivKey + keyLen, &lenData); + SysTryCatch(NID_SEC_CERT, err == 1, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to do cipher final."); + + keyLen = keyLen + lenData; + } + else + { + //Decryption + EVP_CIPHER_CTX_init(&ctx); + + std::unique_ptr pPlainText (new (std::nothrow) byte[__privateKeyLen + 1]); + SysTryReturnResult(NID_SEC_CERT, pPlainText != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pPlainText.get(), 0, __privateKeyLen + 1); + err = EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), null, uniqueKey, ivData, encDecBit); + SysTryCatch(NID_SEC_CERT, err == 1, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to initialized cipher."); + + err = EVP_CipherUpdate(&ctx, pPlainText.get(), reinterpret_cast< int* >(&keyLen), __pPrivateKey.get(), __privateKeyLen); + SysTryCatch(NID_SEC_CERT, err == 1, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to update cipher."); + + err = EVP_CipherFinal_ex(&ctx, pPlainText.get() + keyLen, &outLength); + SysTryCatch(NID_SEC_CERT, err == 1, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Failed to do cipher final."); + + *ppPrivKey = pPlainText.release(); + keyLen = keyLen + outLength; + } + +CATCH: + EVP_CIPHER_CTX_cleanup(&ctx); + return r; +} + +result +_CertPrivateKeyInfo::GetPkcs8EncDecKeyN(int& keyLen, byte** ppPrivKey, int encDecBit) +{ + result r = E_SUCCESS; + byte uniqueKey[16] = {0}; + int aesBlockLen = 16; + const EVP_CIPHER* pCipher = null; + X509_SIG* pPkcs8Key = null; + PKCS8_PRIV_KEY_INFO* p8inf = null; + EVP_PKEY* pKey = null; + const unsigned char* pTempPriKey = null; + long tempkeyLen = 0; + byte* pPrivKey = null; + + std::unique_ptr pSecKey(reinterpret_cast< ISecretKey* >(_DeviceKeyGenerator::GenerateDeviceKeyN(aesBlockLen))); + SysTryReturnResult(NID_SEC_CERT, pSecKey != null, E_SYSTEM, "Failed to generate secret key."); + + std::unique_ptr pKeyBuf(pSecKey->GetEncodedN()); + SysAssertf(pKeyBuf != null, "Failed to get encoded secret key."); + + memset(uniqueKey, 0, aesBlockLen); + memcpy(uniqueKey, reinterpret_cast< const char* >(pKeyBuf->GetPointer()), aesBlockLen); + + std::unique_ptr pTempPrivateKey (new unsigned char[__privateKeyLen + 1]); + SysTryReturnResult(NID_SEC_CERT, pTempPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memcpy((void*) pTempPrivateKey.get(), __pPrivateKey.get(), __privateKeyLen); + tempkeyLen = __privateKeyLen; + + if (encDecBit) + { + pTempPriKey = pTempPrivateKey.get(); + pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pTempPriKey, tempkeyLen); + SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed"); + + p8inf = EVP_PKEY2PKCS8(pKey); + SysTryCatch(NID_SEC_CERT, p8inf != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed"); + + //Encryption : supported PKCS#5 v2.0 algo are PBE-SHA1-RC2-64 PBE-MD2-RC2-64 PBE-MD5-RC2-64 PBE-SHA1-DES + pPkcs8Key = PKCS8_encrypt(NID_pbeWithSHA1AndRC2_CBC, pCipher, reinterpret_cast< const char* >(uniqueKey), aesBlockLen, null, 0, PKCS5_DEFAULT_ITER, p8inf); + SysTryCatch(NID_SEC_CERT, pPkcs8Key != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key encryption failed"); + + keyLen = i2d_X509_SIG(pPkcs8Key, &pPrivKey); + SysTryCatch(NID_SEC_CERT, keyLen > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed"); + + } + else + { + //Decryption + pTempPriKey = pTempPrivateKey.get(); + pPkcs8Key = d2i_X509_SIG(null, &pTempPriKey, tempkeyLen); + SysTryCatch(NID_SEC_CERT, pPkcs8Key != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed"); + + p8inf = PKCS8_decrypt(pPkcs8Key, reinterpret_cast< const char* >(uniqueKey), aesBlockLen); + SysTryCatch(NID_SEC_CERT, p8inf != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key decryption failed"); + + pKey = EVP_PKCS82PKEY(p8inf); + SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed"); + + keyLen = i2d_PrivateKey(pKey, reinterpret_cast< unsigned char** >(&pPrivKey)); + SysTryCatch(NID_SEC_CERT, keyLen > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed"); + } + + EVP_PKEY_free(pKey); + PKCS8_PRIV_KEY_INFO_free(p8inf); + X509_SIG_free(pPkcs8Key); + + *ppPrivKey = pPrivKey; + + return r; +CATCH: + EVP_PKEY_free(pKey); + PKCS8_PRIV_KEY_INFO_free(p8inf); + X509_SIG_free(pPkcs8Key); + OPENSSL_free(pPrivKey); + + return r; +} + +result +_CertPrivateKeyInfo::SetPrivateKey(int keyLen, byte* pPrivKey) +{ + __pPrivateKey.reset(null); + __privateKeyLen = 0; + + SysTryReturnResult(NID_SEC_CERT, pPrivKey != null, E_INVALID_ARG, "Invalid input argument."); + + __pPrivateKey = std::unique_ptr (new (std::nothrow) byte[keyLen + 1]); + SysTryReturnResult(NID_SEC_CERT, __pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + __privateKeyLen = keyLen; + memcpy(__pPrivateKey.get(), pPrivKey, keyLen); + __pPrivateKey[keyLen] = 0; + + return E_SUCCESS; +} + +result +_CertPrivateKeyInfo::SetPrivateKey(char* pFileName) +{ + result r = E_SUCCESS; + String fileName(pFileName); + FileAttributes attr; + File file; + long size = 0; + int readCnt = 0; + int priKeyLen = 0; + + __pPrivateKey.reset(null); + + SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_INVALID_ARG, "Invalid input argument."); + + r = File::GetAttributes(fileName, attr); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get file attributes."); + + size = attr.GetFileSize(); + SysTryReturn(NID_SEC_CERT, size > 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, size < _MAX_CERT_PRIVATE_KEY_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r)); + + __privateKeyLen = size; + + // Open file + r = file.Construct(fileName, L"r"); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed in construct file.", GetErrorMessage(r)); + + __pPrivateKey = std::unique_ptr (new (std::nothrow) byte[size]); + SysTryReturnResult(NID_SEC_CERT, __pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + readCnt = file.Read(__pPrivateKey.get(), size); + r = GetLastResult(); + + if ((readCnt == size && !IsFailed(r))) + { + byte* pPrivateKey = null; + + GetPkcs8EncDecKeyN(priKeyLen, &pPrivateKey, 0); + SysTryReturnResult(NID_SEC_CERT, pPrivateKey, E_SYSTEM, "Failed to get decrypted private key from file."); + + std::unique_ptr pPrivateKeyAuto(pPrivateKey); + + memset(__pPrivateKey.get(), 0, __privateKeyLen); + memcpy(__pPrivateKey.get(), pPrivateKey, priKeyLen); + __privateKeyLen = priKeyLen; + } + + return r; +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertPrivateKeyInfo.h b/src/security/cert/FSecCert_CertPrivateKeyInfo.h new file mode 100755 index 0000000..6d54ac1 --- /dev/null +++ b/src/security/cert/FSecCert_CertPrivateKeyInfo.h @@ -0,0 +1,69 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertPrivateKeyInfo.h + * @brief This header file contains the declarations of Certificate Private Key operations. + * + * This header file contains the declarations of Certificate Private Key operations. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_PRIVATE_KEY_INFO_H_ +#define _FSEC_CERT_INTERNAL_CERT_PRIVATE_KEY_INFO_H_ + +#include "unique_ptr.h" +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Security { namespace Cert +{ + + +class _CertPrivateKeyInfo +{ +public: + _CertPrivateKeyInfo(void); + + _CertPrivateKeyInfo(char* pFileName); + + _CertPrivateKeyInfo(byte* pBuf, int bufSize); + + virtual ~_CertPrivateKeyInfo(void); + + void GetPrivateKeyN(int& keyLen, byte** ppPrivKey); + + result GetEncDecPrivateKeyN(int& keyLen, byte** ppPrivKey, int encDecBit); + + result GetPkcs8EncDecKeyN(int& keyLen, byte** ppPrivKey, int encDecBit); + + result SetPrivateKey(int keyLen, byte* pPrivKey); + + result SetPrivateKey(char* pFileName); + +private: + _CertPrivateKeyInfo(const _CertPrivateKeyInfo& rhs); + + _CertPrivateKeyInfo& operator =(const _CertPrivateKeyInfo& rhs); + +private: + int __privateKeyLen; + std::unique_ptr __pPrivateKey; + +}; //_CertPrivateKeyInfo + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_PRIVATE_KEY_INFO_H_ diff --git a/src/security/cert/FSecCert_CertService.cpp b/src/security/cert/FSecCert_CertService.cpp new file mode 100644 index 0000000..39afb91 --- /dev/null +++ b/src/security/cert/FSecCert_CertService.cpp @@ -0,0 +1,1995 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// +// @file FSecCert_CertService.cpp +// @brief This file contains implementation of X509 Certificate Service APIs. +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertService.h" +#include "FSecCert_CertManager.h" +#include "FSecCert_CertDbManager.h" +#include "FSecCert_Base64.h" +#include "FSecCert_CertFileStore.h" +#include "FSecCert_CertOidDef.h" +#include "FSecCert_Certificate.h" +#include "FSecCert_Base64.h" + + +using namespace Tizen::Io; +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Cert +{ + +const String _CERT_MGR_BASE_DIRECTORY = L"/opt/usr/share/certs/"; +const String _CERT_ROOT_CA_CERT_FILE_DIRECTORY = L"/opt/usr/share/certs/rootcert/"; +const String _CERT_USER_CERT_FILE_DIRECTORY = L"/opt/usr/share/certs/usercert/"; +const String _CERT_USER_PRIVKEY_FILE_DIRECTORY = L"/opt/usr/share/certs/usercert/key/"; + +const String _CERT_ROOT_CA_CERT_TABLE = L"/opt/usr/dbspace/.security-rootcert.db"; +const String _CERT_USER_CERT_TABLE = L"/opt/usr/dbspace/.security-usercert.db"; + +const String _CERT_MGR_CRT_FILE_PATH = _CERT_MGR_BASE_DIRECTORY + L"ca-certificate.crt"; +const String _TEMP_CERT_MGR_CRT_FILE_PATH = _CERT_MGR_BASE_DIRECTORY + L"tmp-ca-certificate.crt"; + +const String _CERT_DOMAIN1_CERT_FILE_PATH = L"/opt/share/cert-svc/certs/sim/thirdparty/"; +const String _CERT_DOMAIN2_CERT_FILE_PATH = L"/opt/share/cert-svc/certs/sim/operator/"; +const String _CERT_SVC_DEFAULT_CERT_DIRECTORY = L"/opt/share/cert-svc/certs/ssl/"; + +//Prefix definition for NAME Prefix +const char* _CERT_COMMON_NAME = "CN="; +const char* _CERT_ORG_UNIT_NAME = "OU="; +const char* _CERT_ORG_NAME = "O="; +const char* _CERT_LOCALITY_NAME = "L="; +const char* _CERT_STATE_OR_PROVINCE_NAME = "S="; +const char* _CERT_COUNTRY_NAME = "C="; +const char* _CERT_EMAIL_ADDRESS = "EmailAddress="; +const char* _CERT_SERIAL_NUM = "SN="; +const char* _CERT_GIVEN_NAME = "GN="; +const char* _CERT_SUR_NAME = "SUN="; +const char* _CERT_STATE_OF_PROVINCE = "ST="; +const char* _CERT_DC = "_CERT_DC="; +const char* _CERT_TK_ISSUER_NAME = "Test"; + +result +_CertService::InitializeDb(void) +{ + result r = E_SUCCESS; + int certTrustTypes = 0; + int certCount = 0; + + r = _CertService::Initialize(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Cert Manager initialisation failed."); + + certTrustTypes = static_cast< int >(_CERT_TRUST_SIM_ROOT_CA | _CERT_TRUST_SIM_DOMAIN); + + _CertService::RemoveCerts(certTrustTypes); + + // Install Certificates + certTrustTypes = static_cast< int >(_CERT_TRUST_PHONE_ROOT_CA | _CERT_TRUST_PHONE_DOMAIN | _CERT_TRUST_OSP_ROOT_CA | _CERT_TRUST_SIM_DOMAIN | _CERT_TRUST_SIM_ROOT_CA); + + r = _CertService::InsertCerts(certTrustTypes, &certCount); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to install certificates."); + + return r; +} + +result +_CertService::ReInitializeDb(void) +{ + result r = E_SUCCESS; + int certTrustTypes = 0; + int certCount = 0; + + r = _CertService::Initialize(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Db initialization failed."); + + // Install Certificates + certTrustTypes = static_cast< int >(_CERT_TRUST_PHONE_ROOT_CA | _CERT_TRUST_PHONE_DOMAIN | _CERT_TRUST_OSP_ROOT_CA | _CERT_TRUST_SIM_DOMAIN | _CERT_TRUST_SIM_ROOT_CA); + + r = _CertService::InsertCerts(certTrustTypes, &certCount); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to install certificates."); + + return r; +} + +result +_CertService::Initialize(void) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + if (!pCertDb->IsCertificateTablesCreated()) + { + r = pCertDb->CreateCertificateTables(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table."); + } + + return r; +} + +result +_CertService::DropTables(void) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + if (!pCertDb->IsCertificateTablesCreated()) + { + r = pCertDb->RemoveCertificateTables(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate table."); + } + + return r; +} + +result +_CertService::ResetTables(void) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + if (!pCertDb->IsCertificateTablesCreated()) + { + r = pCertDb->ResetCertificateTables(); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate table."); + } + + return r; +} + +result +_CertService::MasterReset(void) +{ + _CertDbManager* pCertDb = null; + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + pCertDb->RemoveAllUserCertificate(); + + _CertService::RemoveCert(_CERT_TYPE_ROOT_CA); + _CertService::RemoveCert(_CERT_TYPE_ROOT_DOMAIN1); + _CertService::RemoveCert(_CERT_TYPE_ROOT_DOMAIN2); + _CertService::RemoveCert(_CERT_TYPE_ROOT_DOMAIN3); + _CertService::RemoveCert(_CERT_TYPE_ROOT_CA_BY_USER); + _CertService::RemoveCert(_CERT_TYPE_INTERMIDIATE_CA); + _CertService::RemoveCert(_CERT_TYPE_USER_CERT); + _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL1); + _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL2); + _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL3); + _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL4); + _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL5); + _CertService::RemoveCert(_CERT_TYPE_OSP_PRELOAD_APP); + _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN1); + _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN2); + _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN3); + + return E_SUCCESS; +} + +int +_CertService::InsertCert(_CaCertType type) +{ + result r = E_SUCCESS; + byte certBufData[_MAX_CERTIFICATE_SIZE] = {0, }; + long fileSize = 0; + int count = 0; + int readCnt = 0; + _CertFormat certFormat = _CERT_UNKNOWN; + Directory dir; + Directory rootCertdir; + FileAttributes attr; + String rootCertificatePath; + + ClearLastResult(); + + SysTryReturn(NID_SEC_CERT, type >= 0, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input parameter."); + + switch (type) + { + case _CERT_TYPE_ROOT_CA: + + rootCertificatePath.Append(_CERT_SVC_DEFAULT_CERT_DIRECTORY); + break; + + case _CERT_TYPE_DEV_ROOT_DOMAIN1: + rootCertificatePath.Append(_CERT_DOMAIN1_CERT_FILE_PATH); + break; + + case _CERT_TYPE_DEV_ROOT_DOMAIN2: + rootCertificatePath.Append(_CERT_DOMAIN2_CERT_FILE_PATH); + break; + + case _CERT_TYPE_OSP_CRITICAL1: + //fall through + case _CERT_TYPE_OSP_CRITICAL2: + //fall through + case _CERT_TYPE_OSP_PRELOAD_APP: + break; + + default: + break; + } + certFormat = _CERT_X509; + + if(rootCertificatePath.GetLength() <= 0) + { + SetLastResult(E_SUCCESS); + return 0; + } + + // Open the directory + String dirName(rootCertificatePath); + + r = dir.Construct(dirName); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), -1, r, "[%s] Failed to construct directory.", GetErrorMessage(r)); + + std::unique_ptr pDirEnum(dir.ReadN()); + SysTryReturn(NID_SEC_CRYPTO, pDirEnum != null, count, GetLastResult(), "[%s] Failed to get directory enumerator instance.", GetErrorMessage(GetLastResult())); + + while (pDirEnum->MoveNext() == E_SUCCESS) + { + String fileName; + File file; + + DirEntry entry = pDirEnum->GetCurrentDirEntry(); + + fileName.Append(dirName); + fileName.Append(entry.GetName()); + if ((entry.GetName() == "..") || (entry.GetName() == ".")) + { + continue; + } + + r = file.Construct(fileName, L"r"); + if (!IsFailed(r)) + { + r = File::GetAttributes(fileName, attr); + if (!IsFailed(r)) + { + fileSize = attr.GetFileSize(); + if (fileSize > 0 && fileSize < _MAX_CERTIFICATE_SIZE) + { + readCnt = file.Read(certBufData, fileSize); + r = GetLastResult(); + if (!IsFailed(r) && readCnt == fileSize) + { + _CertService::InsertDefaultCaCertificate(type, certFormat, certBufData, readCnt); + count++; + fileSize = 0; + readCnt = 0; + } + } + } + } + } + + return count; +} + +result +_CertService::InsertDefaultCaCertificate(_CaCertType type, _CertFormat format, byte* pCertBuf, int certLen) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_INVALID_ARG, "Invalid certificate buffer."); + SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid certificate length."); + SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type."); + SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->InsertDefaultCaCertificateFromBuffer(type, format, pCertBuf, certLen); + SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install default ca certiifcates."); + + return r; +} + +result +_CertService::InsertCaCertificate(_CaCertType type, _CertFormat format, byte* pCertBuf, int certLen) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_INVALID_ARG, "Invalid certificate buffer."); + SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid certificate length."); + SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type."); + SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->InsertCaCertificateFromBuffer(type, format, pCertBuf, certLen); + SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install ca certificate from input buffer."); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::RemoveCert(_CaCertType type) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type."); + SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->RemoveCaCertificateByType(type); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate of type %d", type); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::OpenContext(_CertContextType type, CertChainCtx* pCertCtx) +{ + return _CertManager::OpenContext(type, pCertCtx); +} + + +result +_CertService::AddCertificate(CertChainCtx certCtx, byte* pCertBuf, int certLen) +{ + return _CertManager::AddCertificate(certCtx, pCertBuf, certLen); +} + +result +_CertService::VerifyChain(CertChainCtx certCtx, _CertDomainType* pDomain) +{ + result r = E_SUCCESS; + + r = _CertManager::VerifyChain(certCtx, pDomain); + + return r; +} + +result +_CertService::VerifyCert(CertificateHandle certHandle, byte* pPublickey, int keyLen) +{ + return _CertManager::VerifyCertificate(certHandle, pPublickey, keyLen); +} + +result +_CertService::GetChainDepth(CertChainCtx certCtx, int* pDepth) +{ + return _CertManager::GetChainDepth(certCtx, pDepth); +} + +result +_CertService::GetNthCert(CertChainCtx certCtx, int nth, CertificateHandle* pCertHandle) +{ + return _CertManager::GetNthCertificate(certCtx, nth, pCertHandle); +} + + +result +_CertService::GetCertBufferN(CertificateHandle certHandle, char*& pBuffer, int* pCertLen) +{ + return _CertManager::GetCertBuffer(certHandle, &pBuffer, pCertLen); +} + +result +_CertService::CloseContext(CertChainCtx certCtx) +{ + return _CertManager::CloseContext(certCtx); +} + +result +_CertService::OpenCertificate(char* pBuffer, int bufLen, CertificateHandle* pCertHandle) +{ + result r = E_SUCCESS; + _CertFormat certFormat = _CERT_X509; + _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN; + int derCertBufferLength = 0; + byte* pDerCert = null; + + *pCertHandle = null; + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input buffer."); + SysTryReturnResult(NID_SEC_CERT, bufLen > 0, E_INVALID_ARG, "Invalid input length."); + + certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pBuffer), bufLen, &pDerCert, &derCertBufferLength, &encodingType); + std::unique_ptr pDerCertBuffer(pDerCert); + pDerCert = null; + + SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_ARG, "Invalid certificate buffer."); + SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_ARG, "Invalid certificate length."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + + std::unique_ptr<_X509Certificate> pCert(new (std::nothrow) _X509Certificate()); + SysTryReturnResult(NID_SEC_CRYPTO, pCert, E_OUT_OF_MEMORY, "Allocating new _X509Certificate failed."); + + r = pCert->Parse(pDerCertBuffer.get(), derCertBufferLength); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to allocate memory.", GetErrorMessage(r)); + + //Certificate format is X509 and Buffer is Binary + + pCert->SetContextCertificate(false); + pCert->SetCertFormat(_CERT_X509); + *pCertHandle = reinterpret_cast< CertificateHandle >(pCert.release()); + + return r; +} + + +result +_CertService::CloseCertificate(CertificateHandle* pCertHandle) +{ + + SysTryReturnResult(NID_SEC_CERT, pCertHandle != null, E_INVALID_ARG, "Invalid parameter certificate handle."); + + _Certificate* pTempCert = null; + + pTempCert = static_cast< _Certificate* >(*pCertHandle); + SysTryReturnResult(NID_SEC_CERT, pTempCert != null, E_SYSTEM, "An unexpected system error occurred"); + + _CertFormat format = pTempCert->GetCertFormat(); + SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_SYSTEM, "Failed to get certificate format."); + + _X509Certificate* pCert = dynamic_cast< _X509Certificate* >(pTempCert); + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_SYSTEM, "An unexpected system error occurred."); + if (!pCert->IsContextCertificate()) + { + delete pCert; + *pCertHandle = null; + } + + return E_SUCCESS; +} + +result +_CertService::GetCaCertificateId(CertificateHandle certHandle, _CaCertType certType, int& certId) +{ + result r = E_SUCCESS; + _X509Certificate* pCert = static_cast< _X509Certificate* >(certHandle); + _X509TbsCert* pTbsCert = null; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid certificate handle, handle must not be null."); + SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type."); + SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type."); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())), + pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + certId, certType); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id of the certificate with subject name %s", GetErrorMessage(r), pTbsCert->GetSubjectName()); + + return r; + +} + +result +_CertService::GetUserCertificateId(CertificateHandle certHandle, int& certId) +{ + result r = E_SUCCESS; + _X509Certificate* pCert = static_cast< _X509Certificate* >(certHandle); + _X509TbsCert* pTbsCert = null; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid certificate handle. handle must not be null"); + + pTbsCert = pCert->GetTbsCertInstance(); + SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())), + pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())), + certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate identifier with subject name %s.", GetErrorMessage(r), pTbsCert->GetSubjectName()); + + return r; +} + +result +_CertService::GetCertInfo(CertificateHandle certHandle, _CertFieldType field, _CertFieldInfos* pCertInfo) +{ + return _CertManager::GetCertInfo(certHandle, field, pCertInfo); +} + +result +_CertService::FreeCertList(_CertificateListInfo* pCertList) +{ + _CertificateListInfo* pTemp = null; + int count = 0; + + SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_INVALID_ARG, "Invalid certificate list."); + + while (pCertList) + { + pTemp = pCertList->pNext; + delete (pCertList); + pCertList = pTemp; + count++; + } + + return E_SUCCESS; +} + +result +_CertService::FreeCertificateInfo(_CertInfo* pCertInfo) +{ + delete pCertInfo; + + return E_SUCCESS; +} + +result +_CertService::GetCertListByFormatN(_CertFormat certFormat, _CertificateListInfo*& pCertList, int* pCount) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + SysTryReturnResult(NID_SEC_CERT, pCount != null, E_INVALID_ARG, "Invalid certificate count."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->GetCertificateListByFormat(certFormat, &pCertList, *pCount); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get certificate list."); + + return r; +} + +result +_CertService::GetCaCertListByCertIdN(int certId, _CertificateListInfo*& pCertList) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->GetCaCertificateListByCertId(certId, &pCertList); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get ca certificate list."); + + return r; +} + +result +_CertService::RemoveCerts(int certTrustTypes) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC_CERT, certTrustTypes >= 0, E_INVALID_ARG, "Invalid certificate trust type."); + + if (certTrustTypes & _CERT_TRUST_SIM_DOMAIN) + { + r = _CertService::RemoveCert(_CERT_TYPE_SIM_ROOT_DOMAIN1); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain1."); + + r = RemoveCert(_CERT_TYPE_SIM_ROOT_DOMAIN3); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain3."); + } + + if (certTrustTypes & _CERT_TRUST_DEV_ROOT_CA) + { + r = _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_CA); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove root ca certificate."); + } + + if (certTrustTypes & _CERT_TRUST_DEV_DOMAIN) + { + r = _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN1); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain1."); + r = _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN2); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain2."); + r = _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN3); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain3."); + } + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::InsertCerts(int certTrustTypes, int* pCertCount) +{ + result r = E_SUCCESS; + int certCount = 0; + int certTotalCount = 0; + + SysTryReturnResult(NID_SEC_CERT, certTrustTypes != _CERT_TRUST_NONE, E_INVALID_ARG, "Invalid certificate trust type."); + SysTryReturnResult(NID_SEC_CERT, certTrustTypes > 0, E_INVALID_ARG, "Invalid certificate trust type."); + + if (certTrustTypes & _CERT_TRUST_OSP_ROOT_CA) + { + certCount = _CertService::InsertCert(_CERT_TYPE_OSP_PRELOAD_APP); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL2); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL1); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL3); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL4); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL5); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + } + if (certTrustTypes & _CERT_TRUST_PHONE_ROOT_CA) + { + //Install trusted by default certificates + certCount = _CertService::InsertCert(_CERT_TYPE_TRUSTED_CA); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + + certCount = _CertService::InsertCert(_CERT_TYPE_ROOT_CA); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + } + if (certTrustTypes & _CERT_TRUST_PHONE_DOMAIN) + { + certCount = _CertService::InsertCert(_CERT_TYPE_ROOT_DOMAIN1); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_ROOT_DOMAIN2); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_ROOT_DOMAIN3); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + } + if (certTrustTypes & _CERT_TRUST_SIM_DOMAIN) + { + certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN1); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN2); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN3); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + } + if (certTrustTypes & _CERT_TRUST_SIM_ROOT_CA) + { + certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_CA); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + } + if (certTrustTypes & _CERT_TRUST_DEV_ROOT_CA) + { + certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_CA); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + } + if (certTrustTypes & _CERT_TRUST_DEV_DOMAIN) + { + certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN1); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN2); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN3); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + } + + if (certTrustTypes & _CERT_TRUST_CSC_CA) + { + certCount = _CertService::InsertCert(_CERT_TYPE_CSC_ROOT_CA); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN1); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN2); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + certCount = _CertService::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN3); + if (certCount == -1) + { + r = E_SYSTEM; + } + else + { + certTotalCount += certCount; + } + } + + if (pCertCount != null) + { + *pCertCount = certTotalCount; + } + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +CertificateStoreCtx +_CertService::OpenCertificateStoreByType(_CaCertType type, int* pCount) +{ + CertificateStoreCtx retCtx; + int count = 0; + + if (type == _CERT_TYPE_USER_CERT) + { + retCtx = _CertManager::OpenUserCertificateStore(count); + } + else + { + retCtx = _CertManager::OpenRootCaStore(type, count); + } + + if (pCount != null) + { + *pCount = count; + } + + return retCtx; +} + +int +_CertService::GetCertificateCount(CertificateStoreCtx certificateStoreCtx) +{ + _CertRootCaInfo* pRootCa = null; + int count = 0; + _CertRootList* pTemp = null; + + ClearLastResult(); + + if (certificateStoreCtx != null) + { + pRootCa = reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx); + if (pRootCa->pRootList != null) + { + pTemp = pRootCa->pRootList; + } + else + { + return 0; + } + while (pTemp != null) + { + count++; + pTemp = pTemp->pNext; + } + } + + return count; +} + +result +_CertService::GetNextCertificate(CertificateStoreCtx certificateStoreCtx, char* pBuffer, int* pBufferLen) +{ + _CertRootCaInfo* pRootCa = null; + _CertRootList* pTemp = null; + int count = 0; + + SysTryReturnResult(NID_SEC_CERT, certificateStoreCtx != null, E_INVALID_ARG, "Invalid certificate store context."); + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input buffer."); + SysTryReturnResult(NID_SEC_CERT, pBufferLen != null, E_INVALID_ARG, "Invalid input buffer length."); + + pRootCa = reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx); + SysTryReturnResult(NID_SEC_CERT, pRootCa->pRootList != null, E_OBJ_NOT_FOUND, "Certificate list is empty."); + + pTemp = pRootCa->pRootList; + + while (count != pRootCa->curPos) + { + count++; + SysTryReturnResult(NID_SEC_CERT, pTemp->pNext != null, E_OBJ_NOT_FOUND, "Certificate index not found."); + + pTemp = pTemp->pNext; + } + + pRootCa->pCurrRootList = pTemp; + if (*pBufferLen > static_cast< int >(pRootCa->pCurrRootList->length)) + { + memcpy(pBuffer, pRootCa->pCurrRootList->certificate, pRootCa->pCurrRootList->length); + *pBufferLen = pRootCa->pCurrRootList->length; + } + else + { + memcpy(pBuffer, pRootCa->pCurrRootList->certificate, *pBufferLen); + } + + pRootCa->curPos++; + + return E_SUCCESS; +} + + +result +_CertService::UpdateCaCertificate(_CaCertType type, char* pOldCert, int oldCertLen, char* pNewCert, int newCertLen) // if same certificate is in Db, replace the certificate using buffer2 and bufferLen2. +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + _CertFormat certFormat = _CERT_UNKNOWN; + int derCertBufferLengthOld = 0; + int derCertBufferLengthNew = 0; + byte* pDerCertOld = null; + byte* pDerCertNew = null; + _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN; + + SysTryReturnResult(NID_SEC_CERT, pOldCert != null, E_INVALID_ARG, "Invalid old certificate buffer."); + SysTryReturnResult(NID_SEC_CERT, oldCertLen > 0, E_INVALID_ARG, "Invalid old certificate length."); + SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_INVALID_ARG, "Invalid new certificate buffer."); + SysTryReturnResult(NID_SEC_CERT, newCertLen > 0, E_INVALID_ARG, "Invalid new certificate length."); + SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type."); + SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pOldCert), oldCertLen, &pDerCertOld, &derCertBufferLengthOld, &encodingType); + SysTryReturnResult(NID_SEC_CERT, pDerCertOld != null, E_SYSTEM, "Invalid old certificate buffer."); + + std::unique_ptrpDerCertBufferOld(pDerCertOld); + SysTryReturnResult(NID_SEC_CERT, pDerCertBufferOld != null, E_INVALID_ARG, "Invalid old certificate buffer."); + + pDerCertOld = null; + SysTryReturnResult(NID_SEC_CERT, derCertBufferLengthOld > 0, E_SYSTEM, "Invalid old certificate length."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format."); + + certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pNewCert), newCertLen, &pDerCertNew, &derCertBufferLengthNew, &encodingType); + SysTryReturnResult(NID_SEC_CERT, pDerCertNew != null, E_SYSTEM, "Invalid new certificate buffer."); + + std::unique_ptrpDerCertBufferNew(pDerCertNew); + SysTryReturnResult(NID_SEC_CERT, pDerCertBufferNew != null, E_SYSTEM, "Invalid new certificate buffer."); + + pDerCertNew = null; + + SysTryReturnResult(NID_SEC_CERT, derCertBufferLengthNew > 0, E_SYSTEM, "Invalid new certificate length."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format."); + + r = pCertDb->UpdateCaCertificateFromBuffer(type, certFormat, reinterpret_cast< byte* >(pDerCertBufferOld.get()), derCertBufferLengthOld, reinterpret_cast< byte* >(pDerCertBufferNew.get()), derCertBufferLengthNew); + if (r == E_DATA_NOT_FOUND) + { + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "Certificate not found in db."); + } + + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "An unexpected system error occurred."); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + + +result +_CertService::RemoveCaCertificate(_CaCertType type, char* pBuffer, int bufLen) // if same certificate is in Db, remove the certificate. +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + _CertFormat certFormat = _CERT_UNKNOWN; + byte* pDerCert = null; + int derCertBufferLength = 0; + _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN; + + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input certificate buffer."); + SysTryReturnResult(NID_SEC_CERT, bufLen > 0, E_INVALID_ARG, "Invalid input certificate length."); + + SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type."); + SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pBuffer), bufLen, &pDerCert, &derCertBufferLength, &encodingType); + SysTryReturnResult(NID_SEC_CERT, pDerCert != null, E_SYSTEM, "Input certificate buffer."); + + std::unique_ptrpDerCertBuffer(pDerCert); + SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_SYSTEM, "Invalid certificate buffer."); + pDerCert = null; + + SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_SYSTEM, "Invalid certificate length."); + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format."); + + r = pCertDb->RemoveCaCertificateFromBuffer(type, certFormat, reinterpret_cast< byte* >(pDerCertBuffer.get()), derCertBufferLength); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to remove Ca certificate.", GetErrorMessage(r)); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + + +result +_CertService::CloseCertificateStore(CertificateStoreCtx certificateStoreCtx) +{ + _CertRootList* pTemp = null; + + SysTryReturnResult(NID_SEC_CERT, certificateStoreCtx != null, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr<_CertRootCaInfo> pRootCa(reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx)); + SysTryReturnResult(NID_SEC_CERT, pRootCa->pRootList != null, E_INVALID_ARG, "Allocating new _CertRootCaInfo failed."); + + while (pRootCa->pRootList != null) + { + pTemp = pRootCa->pRootList->pNext; + delete (pRootCa->pRootList); + pRootCa->pRootList = pTemp; + } + if (pRootCa->curPos) + { + pRootCa->curPos = 0; + } + + return E_SUCCESS; +} + +result +_CertService::GetCertPublicKey(CertificateHandle certHandle, char* pBuffer, int* bufLen) +{ + memset(pBuffer, 0, *bufLen); + return _CertManager::GetPublicKey(certHandle, pBuffer, bufLen); +} + +result +_CertService::GetCertSignature(CertificateHandle certHandle, char* pBuffer, int* bufLen) +{ + memset(pBuffer, 0, *bufLen); + return _CertManager::GetSignature(certHandle, pBuffer, bufLen); +} + +int +_CertService::GetCertVersion(CertificateHandle certHandle) +{ + ClearLastResult(); + return _CertManager::GetVersion(certHandle); +} + +result +_CertService::CheckCertValidity(CertificateHandle certHandle, _CertValidityType* pValidity) +{ + return _CertManager::GetValidity(certHandle, pValidity); +} + +result +_CertService::CheckCertType(CertificateHandle certHandle, _CaCertType* certType) +{ + return _CertManager::GetCertificateType(certHandle, certType); +} + +int +_CertService::GetDomainCertInfoN(_CertFieldInfos*& pDcInfoRef) +{ + result r = E_SUCCESS; + std::unique_ptr<_CertFieldInfos[]> pDcInfo(null); + CertificateHandle certHandle = null; + _CertificateListInfo* pCertList = null; + _CertificateListInfo* pHoldList = null; + int totalCount = 0; + int certId = 0; + + ClearLastResult(); + + r = _CertService::GetCertListByFormatN(_CERT_X509, pCertList, &totalCount); + SysTryReturn(NID_SEC_CERT, pCertList != null, -1, E_SYSTEM, "[E_SYSTEM] Get cert list failed."); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), -1, r, "[E_SYSTEM] An unexpected system error occurred."); + SysTryReturn(NID_SEC_CERT, totalCount > 0, 0, E_SUCCESS, "[E_SUCCESS] No certificate found in store."); + + pDcInfo = std::unique_ptr<_CertFieldInfos[]>(new (std::nothrow) _CertFieldInfos[totalCount]); + SysTryCatch(NID_SEC_CERT, pDcInfo != null, certId = -1, r, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pDcInfo.get(), 0, sizeof(_CertFieldInfos) * totalCount); + + pHoldList = pCertList; + while (pCertList != null && pCertList->length != 0) + { + r = _CertService::OpenCertificate(reinterpret_cast< char* >(pCertList->certificate), pCertList->length, &certHandle); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), certId = -1, E_SYSTEM, "[E_SYSTEM] Failed to open certificate."); + + r = _CertService::GetCertInfo(certHandle, _CERT_FIELD_ALL, &pDcInfo[certId]); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), certId = -1, E_SYSTEM, "[E_SYSTEM] Failed to get certificate info."); + + pDcInfo[certId].certType = pCertList->certType; + pDcInfo[certId].certFileId = pCertList->certFileId; + certId++; + pCertList = pCertList->pNext; + _CertService::CloseCertificate(&certHandle); + } + _CertService::FreeCertList(pHoldList); + pHoldList = null; + pDcInfoRef = pDcInfo.release(); + + return certId; + +CATCH: + _CertService::CloseCertificate(&certHandle); + _CertService::FreeCertList(pHoldList); + pHoldList = null; + return certId; +} + +result +_CertService::GetCaCertInfoByCertId(int certId, _CertFieldInfos* pDcInfo) +{ + result r = E_SUCCESS; + _CertificateListInfo* pCertList = null; + CertificateHandle certHandle = null; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id."); + SysTryReturnResult(NID_SEC_CERT, pDcInfo != null, E_INVALID_ARG, "Invalid input parameter."); + + r = _CertService::GetCaCertListByCertIdN(certId, pCertList); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate list.", GetErrorMessage(r)); + + memset(pDcInfo, 0, sizeof(*pDcInfo)); + if (pCertList != null && pCertList->length != 0) + { + r = _CertService::OpenCertificate(reinterpret_cast< char* >(pCertList->certificate), pCertList->length, &certHandle); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open certificate."); + + r = _CertService::GetCertInfo(certHandle, _CERT_FIELD_ALL, pDcInfo); + + pDcInfo[0].certType = pCertList->certType; + pDcInfo[0].certFileId = pCertList->certFileId; + _CertService::CloseCertificate(&certHandle); + } + +CATCH: + CloseCertificate(&certHandle); + FreeCertList(pCertList); + return r; +} + +result +_CertService::InsertUserCaCertificate(byte* pFilePath) +{ + result r = E_SUCCESS; + _CertFormat certFormat = _CERT_X509; + _CertDomainType res; + CertChainCtx certCtx = null; + File file; + FileAttributes attr; + int certLen = 0; + int readCnt = 0; + long fileSize = 0; + String fileName(reinterpret_cast< char* >(pFilePath)); + + SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid file path."); + + r = File::GetAttributes(fileName, attr); + + fileSize = attr.GetFileSize(); + SysTryReturn(NID_SEC_CERT, fileSize > 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r)); + + r = file.Construct(fileName, L"r"); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct file.", GetErrorMessage(r)); + + std::unique_ptr pCertBuf(new (std::nothrow) char[fileSize + 1]); + SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Allocating new char array failed."); + memset(pCertBuf.get(), 0, (fileSize + 1)); + + readCnt = file.Read(pCertBuf.get(), fileSize); + r = GetLastResult(); + SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r)); + + certLen = readCnt; + + r = _CertService::OpenContext(_CERT_CONTEXT_CERT, &certCtx); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to open certificate context."); + + r = _CertService::AddCertificate(certCtx, reinterpret_cast< byte* >(pCertBuf.get()), certLen); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to add certificate to context."); + + r = _CertService::VerifyChain(certCtx, &res); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to verify certificate chain context."); + + r = _CertService::InsertUserCaCertificate(certFormat, pCertBuf.get(), certLen); + SysTryCatch(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to insert user ca certificate context."); + + r = _CertManager::CreateCrtFile(); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + +CATCH: + + if (certCtx) + { + CloseContext(certCtx); + } + + return r; +} + +result +_CertService::RemoveUserCaCertificateByCertId(int certId) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->RemoveUserCaCertificateByCertId(certId); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete root ca certificate."); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::InsertUserCaCertificate(_CertFormat format, char* pCert, int certLen) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid input certificate buffer."); + SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid input certificate length."); + + _CertDbManager* pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->InsertCaCertificateFromBuffer(_CERT_TYPE_ROOT_CA_BY_USER, format, reinterpret_cast< byte* >(pCert), certLen); + SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install certificate from input buffer."); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +//User Certificate APIs +int +_CertService::InsertUserCaCertificatesToRootDb(void) +{ + result r = E_SUCCESS; + int certTrustTypes = 0; + int certCount = 0; + + ClearLastResult(); + + certTrustTypes = static_cast< int >(_CERT_TRUST_DEV_ROOT_CA | _CERT_TRUST_DEV_DOMAIN); + + _CertService::RemoveCerts(certTrustTypes); + + r = _CertService::InsertCerts(certTrustTypes, &certCount); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), 0, E_SYSTEM, "[E_SYSTEM] Failed to install certificates."); + + return certCount; +} + +result +_CertService::RemoveUserCaCertificatesFromRootDb(void) +{ + result r = E_SUCCESS; + int certTrustTypes = 0; + + certTrustTypes = static_cast< int >(_CERT_TRUST_DEV_ROOT_CA | _CERT_TRUST_DEV_DOMAIN); + + r = _CertService::RemoveCerts(static_cast< _CaCertType >(certTrustTypes)); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate."); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::InsertUserCertChainPrivateKey(char* pCertChainBuffer, int certChainLength, char* pUserPrivateKey, int userPrivateKeyLength) +{ + result r = E_SUCCESS; + _CertChain* pCertTempChain = null; + _CertPrivateKeyInfo* pPrivateKeyTempInfo = null; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, pCertChainBuffer != null, E_INVALID_ARG, "Failed to insert user certificate chain."); + SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Failed to insert user certificate chain."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = _CertManager::MakeParseAndVerifyCertChainBufferN(reinterpret_cast< byte* >(pCertChainBuffer), certChainLength, reinterpret_cast< byte* >(pUserPrivateKey), userPrivateKeyLength, &pCertTempChain, &pPrivateKeyTempInfo); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse and verify certificate chain buffer.", GetErrorMessage(r)); + + std::unique_ptr<_CertChain> pCertChain(pCertTempChain); + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_SYSTEM, "Invalid certificate chain."); + pCertTempChain = null; + + std::unique_ptr<_CertPrivateKeyInfo> pPrivateKeyInfo(pPrivateKeyTempInfo); + pPrivateKeyTempInfo = null; + + r = pCertDb->InsertCertificateChain(pCertChain->GetCertFormat(), pCertChain.get(), pPrivateKeyInfo.get()); + SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[%s] Failed to insert certificate chain.", GetErrorMessage(r)); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::InsertCertificateChainWithPrivateKey(char* pCertChainPrivateKeyBuffer, int certChainPrivateKeyLength) +{ + result r = E_SUCCESS; + int privateKeyLen = 0; + int certChainLength = 0; + char* pCertChainBuffer = null; + _CertChain* pCertTempChain = null; + _CertDbManager* pCertDb = null; + _CertPrivateKeyInfo* pPrivateKeyTempInfo = null; + + SysTryReturnResult(NID_SEC_CERT, pCertChainPrivateKeyBuffer != null, E_INVALID_ARG, "Invalid private key buffer."); + SysTryReturnResult(NID_SEC_CERT, certChainPrivateKeyLength > 0, E_INVALID_ARG, "Invalid private key length."); + + privateKeyLen = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pCertChainPrivateKeyBuffer)); + SysTryReturnResult(NID_SEC_CERT, privateKeyLen > 0, E_SYSTEM, "Failed to get private key length."); + + pCertChainBuffer = pCertChainPrivateKeyBuffer + privateKeyLen; + certChainLength = certChainPrivateKeyLength - privateKeyLen; + + SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Invalid private key length."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = _CertManager::MakeParseAndVerifyCertChainBufferN(reinterpret_cast< byte* >(pCertChainBuffer), certChainLength, reinterpret_cast< byte* >(pCertChainPrivateKeyBuffer), privateKeyLen, &pCertTempChain, &pPrivateKeyTempInfo); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse and verify certificate chain.", GetErrorMessage(r)); + + std::unique_ptr<_CertChain> pCertChain(pCertTempChain); + SysTryReturnResult(NID_SEC_CERT, pCertTempChain != null, E_SYSTEM, "Invalid certificate chain."); + pCertTempChain = null; + + std::unique_ptr<_CertPrivateKeyInfo> pPrivateKeyInfo(pPrivateKeyTempInfo); + SysTryReturnResult(NID_SEC_CERT, pPrivateKeyTempInfo != null, E_SYSTEM, "Invalid private key info."); + pPrivateKeyTempInfo = null; + + r = pCertDb->InsertCertificateChain(pCertChain->GetCertFormat(), pCertChain.get(), pPrivateKeyInfo.get()); + SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to insert certificate chain"); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::InsertPkcs12Content(char* pPkcs12FilePath, char* pPkcs12ImportPassword) +{ + result r = E_SUCCESS; + unsigned char* pTempPriKey = null; + unsigned char* pTempUserCertBuffer = null; + unsigned char* pTempCertBuffer = null; + std::unique_ptr priKey; + std::unique_ptr pCertChainBuffer; + std::unique_ptr pCertBuffer; + std::unique_ptr pUserCertBuffer; + int index = 0; + int curIndex = 0; + int priKeyLen = 0; + int userCertBufferLen = 0; + int certBufferLen = 0; + int certChainBufferLen = 0; + STACK_OF(X509)* pCaCertChain = null; + X509* pUserCert = null; + EVP_PKEY* pUserKey = null; + FILE* pFile = null; + PKCS12* pPkcs12Content = null; + + SysTryReturnResult(NID_SEC_CERT, pPkcs12FilePath != null, E_INVALID_ARG, "Invalid pkcs12 file path."); + SysTryReturnResult(NID_SEC_CERT, pPkcs12ImportPassword != null, E_INVALID_ARG, "Invalid pkcs12 password buffer."); + + pFile = fopen(pPkcs12FilePath, "rb"); + SysTryReturnResult(NID_SEC_CERT, pFile != null, E_SYSTEM, "Pkcs#12 file open failed."); + + pPkcs12Content = d2i_PKCS12_fp(pFile, (PKCS12**) null); + SysTryCatch(NID_SEC_CERT, pPkcs12Content != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Pkcs 12 encoding failed."); + + index = PKCS12_parse(pPkcs12Content, pPkcs12ImportPassword, &pUserKey, &pUserCert, &pCaCertChain); + SysTryCatch(NID_SEC_CERT, index != 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Pkcs 12 parsing failed."); + + if (pUserKey != null) + { + priKeyLen = i2d_PrivateKey(pUserKey, &pTempPriKey); + priKey = std::unique_ptr(pTempPriKey); + pTempPriKey = null; + } + + userCertBufferLen = i2d_X509(pUserCert, &pTempUserCertBuffer); + pUserCertBuffer = std::unique_ptr(pTempUserCertBuffer); + pTempUserCertBuffer = null; + certChainBufferLen = userCertBufferLen; + + if (pCaCertChain && sk_num((_STACK*) pCaCertChain)) + { + for (index = 0; index < sk_X509_num(pCaCertChain); index++) + { + certBufferLen = i2d_X509(sk_X509_value(pCaCertChain, index), &pTempCertBuffer); + certChainBufferLen = certChainBufferLen + certBufferLen; + pCertBuffer = std::unique_ptr (pTempCertBuffer); + pTempCertBuffer = null; + certBufferLen = 0; + } + + pCertChainBuffer = std::unique_ptr (new (std::nothrow) unsigned char[certChainBufferLen]); + SysTryCatch(NID_SEC_CERT, pCertChainBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s] Allocating new char array failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(pCertChainBuffer.get(), 0, certChainBufferLen); + memcpy(pCertChainBuffer.get(), pUserCertBuffer.get(), userCertBufferLen); + curIndex = userCertBufferLen; + + for (index = 0; index < sk_X509_num(pCaCertChain); index++) + { + certBufferLen = i2d_X509(sk_X509_value(pCaCertChain, index), &pTempCertBuffer); + pCertBuffer = std::unique_ptr (pTempCertBuffer); + pTempCertBuffer = null; + memcpy((pCertChainBuffer.get() + curIndex), pCertBuffer.get(), certBufferLen); + curIndex = curIndex + certBufferLen; + certBufferLen = 0; + } + } + else + { + pCertChainBuffer = std::unique_ptr (new (std::nothrow) unsigned char[certChainBufferLen]); + SysTryCatch(NID_SEC_CERT, pCertChainBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s] Allocating new char array failed.", GetErrorMessage(E_OUT_OF_MEMORY)); + + memset(pCertChainBuffer.get(), 0, certChainBufferLen); + memcpy(pCertChainBuffer.get(), pUserCertBuffer.get(), userCertBufferLen); + } + + r = InsertUserCertChainPrivateKey(reinterpret_cast< char* >(pCertChainBuffer.get()), certChainBufferLen, reinterpret_cast< char* >(priKey.get()), priKeyLen); + SysTryCatch(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), , r, "[%s] Failed to insert user certificate chain.", GetErrorMessage(r)); + + r = _CertManager::CreateCrtFile(); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + +CATCH: + fclose(pFile); + PKCS12_free(pPkcs12Content); + EVP_PKEY_free(pUserKey); + X509_free(pUserCert); + sk_X509_free(pCaCertChain); + return r; +} + +result +_CertService::GetParsedCertificateChainN(char* pCertChainBuffer, int certChainLength, CertChainCtx* pCertCtx) +{ + result r = E_SUCCESS; + CertChainCtx certChainCtx = null; + char* pTmpBuf = null; + int dataOffset = 0; + int dataLength = 0; + int bufSize = 0; + + SysTryReturnResult(NID_SEC_CERT, pCertChainBuffer != null, E_INVALID_ARG, "Invalid certificate chain buffer."); + SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Invalid certificate chain length"); + SysTryReturnResult(NID_SEC_CERT, pCertCtx != null, E_INVALID_ARG, "Invalid certificate chain context."); + + r = _CertService::OpenContext(_CERT_CONTEXT_CERT, &certChainCtx); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open context."); + + bufSize = certChainLength; + + pTmpBuf = pCertChainBuffer + dataOffset; + dataLength = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pTmpBuf)); + SysTryCatch(NID_SEC_CERT, dataLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get decoded block size."); + + r = _CertService::AddCertificate(certChainCtx, reinterpret_cast< byte* >(pTmpBuf), dataLength); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to add certificate."); + + dataOffset += dataLength; + + while (dataOffset < bufSize) + { + pTmpBuf = pCertChainBuffer + dataOffset; + dataLength = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pTmpBuf)); + SysTryCatch(NID_SEC_CERT, dataLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get decoded block size."); + + r = _CertService::AddCertificate(certChainCtx, reinterpret_cast< byte* >(pTmpBuf), dataLength); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to add certificate."); + + dataOffset += dataLength; + } + + *pCertCtx = certChainCtx; + return r; + +CATCH: + CloseContext(certChainCtx); + return r; + +} + +result +_CertService::VerifyCertificateChain(CertChainCtx pCertCtx) +{ + result r = E_SUCCESS; + _CertChain* pCertChain = null; + + SysTryReturnResult(NID_SEC_CERT, pCertCtx != null, E_INVALID_ARG, "Invalid certificate chain context."); + + pCertChain = reinterpret_cast< _CertChain* >(pCertCtx); + + r = pCertChain->VerifyCertChainWithDb(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate chain.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::InsertCertificateChainContext(CertChainCtx pCertCtx) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + _CertChain* pCertChain = null; + + SysTryReturnResult(NID_SEC_CERT, pCertCtx != null, E_INVALID_ARG, "Invalid certificate chain context."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + pCertChain = reinterpret_cast< _CertChain* >(pCertCtx); + + r = pCertDb->InsertCertChain(_CERT_X509, pCertChain); + SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && (r != E_OBJ_ALREADY_EXIST) && (r != E_FILE_ALREADY_EXIST)), r, r, "[%s] Failed to install certificate chain.", GetErrorMessage(r)); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::MakeCertChainFromBufferN(char* pCertChainBuffer, int certChainLength, _CertRootList*& pCertChainListRef) +{ + result r = E_SUCCESS; + char* pTmpBuf = null; + int dataOffset = 0; + int dataLength = 0; + int bufSize = 0; + _CertRootList* pCertChainHead = null; + _CertRootList* pCertChainCurrent = null; + + SysTryReturnResult(NID_SEC_CERT, pCertChainBuffer != null, E_INVALID_ARG, "Invalid certificate chain buffer."); + SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Invalid certificate chain length."); + + bufSize = certChainLength; + + pTmpBuf = pCertChainBuffer + dataOffset; + dataLength = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pTmpBuf)); + SysTryReturnResult(NID_SEC_CERT, dataLength > 0, E_SYSTEM, "Failed to get decoded block size."); + + std::unique_ptr<_CertRootList> pCertChainList(new (std::nothrow) _CertRootList()); + SysTryReturnResult(NID_SEC_CERT, pCertChainList != null, E_OUT_OF_MEMORY, "Allocating new _CertRootList failed."); + + memcpy(pCertChainList->certificate, pTmpBuf, dataLength); + pCertChainList->length = dataLength; + pCertChainList->format = _CERT_X509; + pCertChainList->pNext = null; + + pCertChainCurrent = pCertChainList.release(); + pCertChainHead = pCertChainCurrent; + + dataOffset += dataLength; + + while (dataOffset < bufSize) + { + pTmpBuf = pCertChainBuffer + dataOffset; + dataLength = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pTmpBuf)); + SysTryCatch(NID_SEC_CERT, dataLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM]Failed to get decoded block size."); + + std::unique_ptr<_CertRootList> pCertChainList (new (std::nothrow) _CertRootList()); + SysTryCatch(NID_SEC_CERT, pCertChainList != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]Failed to allocate memory."); + + pCertChainList->pNext = null; + + memcpy(pCertChainList->certificate, pTmpBuf, dataLength); + pCertChainList->length = dataLength; + pCertChainList->format = _CERT_X509; + + pCertChainCurrent->pNext = pCertChainList.release(); + + dataOffset += dataLength; + } + + pCertChainListRef = pCertChainHead; + + return E_SUCCESS; + +CATCH: + FreeRootCertList(pCertChainHead); + return r; + + +} +result +_CertService::RemoveUserCertificateByCertId(int certId) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->RemoveUserCertificateByCertId(certId); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete root ca certificate."); + + return r; +} + + +result +_CertService::RemoveUserCertChainByCertId(int certId) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->RemoveCertificateChainByCertId(certId); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete user certificate chain."); + + r = _CertManager::CreateCrtFile(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::GetUserCertChainByIssuerAndSubjectNameN(char* pIssuerName, int issuerNameLength, char* pSubjectName, int subjectNameLength, _CertificateListInfo*& pUserCertListInfoTypesRef) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid certificate's issuer name."); + SysTryReturnResult(NID_SEC_CERT, issuerNameLength > 0, E_INVALID_ARG, "Invalid certificate's issuer name length."); + SysTryReturnResult(NID_SEC_CERT, issuerNameLength < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_INVALID_ARG, "Invalid certificate's issuer name length."); + SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid certificate's subject name."); + SysTryReturnResult(NID_SEC_CERT, subjectNameLength > 0, E_INVALID_ARG, "Invalid certificate's subject name length."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->GetUserCertificateChain(pIssuerName, issuerNameLength, pSubjectName, subjectNameLength, _CERT_ENC_TYPE_BINARY, &pUserCertListInfoTypesRef); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get user certificate chain."); + + return r; +} + +result +_CertService::GetUserCertChainBySubjectName(char* pSubjectName, int subjectNameLength, CertChainCtx* pCertChainCtx, PrivateKeyCtx* pPrivateKeyCtx) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + std::unique_ptr<_CertPrivateKeyInfo> pPrivateKeyInfo; + _CertFormat certFormat = _CERT_X509; + + SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid certificate's subject name."); + SysTryReturnResult(NID_SEC_CERT, subjectNameLength > 0, E_INVALID_ARG, "Invalid certificate's subject name length."); + SysTryReturnResult(NID_SEC_CERT, subjectNameLength <= _MAX_ISSUER_SUBJECT_NAME_SIZE, E_INVALID_ARG, "Invalid certificate's subject name length."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + std::unique_ptr<_CertChain> pCertChain(new (std::nothrow) _CertChain()); + SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Allocating new _CertChain failed."); + + if (pPrivateKeyCtx != null) + { + pPrivateKeyInfo = std::unique_ptr<_CertPrivateKeyInfo> (new (std::nothrow) _CertPrivateKeyInfo()); + SysTryReturnResult(NID_SEC_CERT, pPrivateKeyInfo != null, E_OUT_OF_MEMORY, "Allocating new _CertPrivateKeyInfo failed."); + } + + r = pCertDb->GetUserCertificateChain(certFormat, pCertChain.get(), pPrivateKeyInfo.get(), reinterpret_cast< char* >(pSubjectName)); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to extract certificate chain."); + + if (pCertChainCtx != null) + { + *pCertChainCtx = pCertChain.release(); + } + + if (pPrivateKeyCtx != null) + { + *pPrivateKeyCtx = pPrivateKeyInfo.release(); + } + + return r; + +} + +result +_CertService::GetUserCertListInfoTypesByFormatN(_CertFormat certFormat, _CertificateListInfo*& pUserCertListInfoTypesRef, int* pCount) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format."); + SysTryReturnResult(NID_SEC_CERT, pCount != null, E_INVALID_ARG, "Invalid certificate format."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->GetUserCertificateListByFormat(certFormat, &pUserCertListInfoTypesRef, *pCount); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate list.", GetErrorMessage(r)); + + return r; +} + +result +_CertService::GetUserCertificateByCertIdN(int certId, _CertEncodingType encodingType, _CertInfo*& pUserCertificateInfoRef) +{ + result r = E_SUCCESS; + _CertDbManager* pCertDb = null; + + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter."); + + pCertDb = _CertDbManager::GetInstance(); + SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager."); + + r = pCertDb->GetUserCertificateInfoByCertId(certId, encodingType, &pUserCertificateInfoRef); + SysTryReturn(NID_SEC_CERT, pCertDb != null, r, r, "[%s]Failed to get user certificate by input cert identifier: (%d).", GetErrorMessage(r), certId); + + return r; +} + +int +_CertService::GetUserCertFieldInfoN(_CertFieldInfos*& pCertFieldInfosRef) +{ + result r = E_SUCCESS; + int totalCount = 0; + int certIdx = 0; + _CertificateListInfo* pCertList = null; + _CertificateListInfo* pHoldList = null; + CertificateHandle certificateHandle = null; + + ClearLastResult(); + + r = GetUserCertListInfoTypesByFormatN(_CERT_X509, pCertList, &totalCount); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), -1, E_SYSTEM, "[E_SYSTEM] Failed to get user certificate list info."); + + if (pCertList == null || totalCount == 0) // regard as the success in the case of 0 + { + SysLog(NID_SEC_CERT, "[E_SUCCESS] No user certificate in database."); + return 0; + } + + pHoldList = pCertList; + + std::unique_ptr<_CertFieldInfos[]> pDCInfo(new (std::nothrow) _CertFieldInfos[totalCount]); + SysTryCatch(NID_SEC_CERT, pDCInfo != null, certIdx = -1, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pDCInfo.get(), 0, sizeof(_CertFieldInfos) * totalCount); + + while (pCertList != null && pCertList->length > 0) + { + r = _CertService::OpenCertificate(reinterpret_cast< char* >(pCertList->certificate), pCertList->length, &certificateHandle); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), certIdx = -1, E_SYSTEM, "[E_SYSTEM] Failed to open certificates."); + + r = _CertService::GetCertInfo(certificateHandle, _CERT_FIELD_ALL, &pDCInfo[certIdx]); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), certIdx = -1, E_SYSTEM, "[E_SYSTEM] Failed to get certificate info."); + + pDCInfo[certIdx].certType = pCertList->certType; + pDCInfo[certIdx].certFileId = pCertList->certFileId; + certIdx++; + pCertList = pCertList->pNext; + _CertService::CloseCertificate(&certificateHandle); + } + + pCertFieldInfosRef = pDCInfo.release(); + + FreeCertList(pHoldList); + SetLastResult(E_SUCCESS); + return certIdx; + +CATCH: + FreeCertList(pHoldList); + _CertService::CloseCertificate(&certificateHandle); + return certIdx; + +} + +result +_CertService::GetUserCertFieldInfoByCertId(int certId, _CertFieldInfos* pCertFieldInfos) +{ + result r = E_SUCCESS; + _CertInfo* pCertInfo = null; + CertificateHandle certificateHandle = null; + + SysTryReturnResult(NID_SEC_CERT, pCertFieldInfos != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter."); + + r = GetUserCertificateByCertIdN(certId, _CERT_ENC_TYPE_BINARY, pCertInfo); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get user certificate.", GetErrorMessage(r)); + + memset(pCertFieldInfos, 0, sizeof(*pCertFieldInfos)); + + if (pCertInfo != null && pCertInfo->certLength != 0) + { + r = OpenCertificate(reinterpret_cast< char* >(pCertInfo->certificate), pCertInfo->certLength, &certificateHandle); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open certificate."); + + r = GetCertInfo(certificateHandle, _CERT_FIELD_ALL, pCertFieldInfos); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate info."); + + pCertFieldInfos[0].certType = _CERT_TYPE_USER_CERT; + pCertFieldInfos[0].certFileId = pCertInfo->certId; + CloseCertificate(&certificateHandle); + } + +CATCH: + FreeCertificateInfo(pCertInfo); + CloseCertificate(&certificateHandle); + return r; + +} + +result +_CertService::GetSubjectNameN(CertificateHandle certificateHandle, byte*& pSubjectNameRef, int* pSubjectNameLength) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC_CERT, certificateHandle != null, E_INVALID_ARG, "Invalid certificate handle."); + SysTryReturnResult(NID_SEC_CERT, pSubjectNameLength != null, E_INVALID_ARG, "Invalid certificate's subject name length."); + + r = _CertManager::GetCertificateIssuerNameN(certificateHandle, &pSubjectNameRef, pSubjectNameLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get certificate's issuer name."); + + return E_SUCCESS; +} + +result +_CertService::GetIssuerNameN(CertificateHandle certificateHandle, byte*& pIssuerNameRef, int* pIssuerNameLength) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SEC_CERT, certificateHandle != null, E_INVALID_ARG, "Invalid input parameter."); + SysTryReturnResult(NID_SEC_CERT, pIssuerNameLength != null, E_INVALID_ARG, "Invalid input parameter."); + + r = _CertManager::GetCertificateSubjectNameN(certificateHandle, &pIssuerNameRef, pIssuerNameLength); + SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get certificate subject name."); + + return E_SUCCESS; +} + +Tizen::Base::String +_CertService::GetCertificateCrtFilePath(void) +{ + return _CERT_MGR_CRT_FILE_PATH; +} + +result +_CertService::FreeRootCertList(_CertRootList* pRootCertList) +{ + result r = E_SUCCESS; + _CertRootList* pTemp = null; + SysTryReturnResult(NID_SEC_CERT, pRootCertList != null, E_INVALID_ARG, "Invalid input parameter."); + + while (pRootCertList) + { + pTemp = pRootCertList->pNext; + delete pRootCertList; + pRootCertList = pTemp; + } + + return r; +} + +result +_CertService::ClosePrivateKeyContext(PrivateKeyCtx privateKeyCtx) +{ + + std::unique_ptr<_CertPrivateKeyInfo> pPrivateKeyInfo (static_cast< _CertPrivateKeyInfo* >(privateKeyCtx)); + SysTryReturnResult(NID_SEC_CERT, pPrivateKeyInfo != null, E_INVALID_ARG, "Allocating new _CertPrivateKeyInfo failed."); + + return E_SUCCESS; +} + + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertServiceProxy.cpp b/src/security/cert/FSecCert_CertServiceProxy.cpp new file mode 100755 index 0000000..f62207e --- /dev/null +++ b/src/security/cert/FSecCert_CertServiceProxy.cpp @@ -0,0 +1,562 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertServiceProxy.cpp + * @brief This is the implementation file for the _CertServiceProxy class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertMgrMessages.h" +#include "FSecCert_CertServiceProxy.h" +#include "FSecCert_CertService.h" + +using namespace std; + +using namespace Tizen::Io; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace Security { namespace Cert +{ + +_IpcClient* _CertServiceProxy::__pIpcClient = null; +_CertServiceProxy* _CertServiceProxy::__pCertServiceProxy = null; + +_CertServiceProxy::_CertServiceProxy(void) +{ + // Empty Body +} + +_CertServiceProxy::~_CertServiceProxy(void) +{ + // Empty Body +} + +_CertServiceProxy* +_CertServiceProxy::GetInstance(void) +{ + + static pthread_once_t once_block = PTHREAD_ONCE_INIT; + if (__pCertServiceProxy == null) + { + pthread_once(&once_block, Construct); + } + + return __pCertServiceProxy; +} + + +void +_CertServiceProxy::Construct(void) +{ + static _CertServiceProxy certServiceProxy; + static _IpcClient ipcClient; + + result r = ipcClient.Construct(L"osp.security.ipcserver.certmanager", null); + SysTryReturnVoidResult(NID_SEC_CERT, !IsFailed(r), r, "[%s] Failed to construct IPC client(Cert-Mgr)", GetErrorMessage(r)); + + __pIpcClient = &ipcClient; + __pCertServiceProxy = &certServiceProxy; +} + + +result +_CertServiceProxy::GetName() +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + + std::unique_ptr pMessage(new (std::nothrow) CertService_GetName(&ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + + +result +_CertServiceProxy::CloseCertificateStore(int certificateStoreCtx) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + + std::unique_ptr pMessage(new (std::nothrow) CertService_CloseCertificateStore(certificateStoreCtx, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::OpenCertificateStoreByType(int type, int& count, int& certificateStoreCtx) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + + std::unique_ptr pMessage(new (std::nothrow) CertService_OpenCertificateStoreByType(type, &count, &certificateStoreCtx, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::GetCertificateCount(int certificateStoreCtx, int& totalCertCount) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + + std::unique_ptr pMessage(new (std::nothrow) CertService_GetCertificateCount(certificateStoreCtx, &totalCertCount, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::GetNextCertificate(int certificateStoreCtx, byte* pBuffer, int& bufferLen) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + Tizen::Io::_IpcBuffer certBufferIpc; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid parameter."); + + certBufferIpc.pBuffer = null; + certBufferIpc.size = 0; + + std::unique_ptr pMessage(new (std::nothrow) CertService_GetNextCertificate(certificateStoreCtx, bufferLen, &certBufferIpc, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + memcpy(pBuffer, certBufferIpc.pBuffer, certBufferIpc.size); + bufferLen = certBufferIpc.size; + + return r; +} + +result +_CertServiceProxy::UpdateCaCertificate(int type, byte* pOldCert, int oldCertLen, byte* pNewCert, int newCertLen) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + Tizen::Io::_IpcBuffer oldBufferIpc = {0, }; + Tizen::Io::_IpcBuffer newBufferIpc = {0, }; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, ((pOldCert != null) && (oldCertLen > 0)), E_INVALID_ARG, "Invalid input old certificate parameter."); + SysTryReturnResult(NID_SEC_CERT, ((pNewCert != null) && (newCertLen > 0)), E_INVALID_ARG, "Invalid input new certificate parameter."); + + oldBufferIpc.pBuffer = pOldCert; + oldBufferIpc.size = oldCertLen; + + newBufferIpc.pBuffer = pNewCert; + newBufferIpc.size = newCertLen; + + std::unique_ptr pMessage(new (std::nothrow) CertService_UpdateRootCa(type, oldBufferIpc, newBufferIpc, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::RemoveCaCertificate(int type, byte* pBuffer, int bufLen) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + Tizen::Io::_IpcBuffer certBufferIpc; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, ((pBuffer != null) && (bufLen > 0)), E_INVALID_ARG, "Invalid input parameters."); + + certBufferIpc.pBuffer = pBuffer; + certBufferIpc.size = bufLen; + + std::unique_ptr pMessage(new (std::nothrow) CertService_RemoveRootCa(type, certBufferIpc, bufLen, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::RemoveUserCaCertificateByCertId(int certId) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, certId >= 1, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr pMessage(new (std::nothrow) CertService_UninstallUserRootCertificateByCertId(certId, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::InsertCaCertificate(int type, int format, byte* pCert, long certLen) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + Tizen::Io::_IpcBuffer certBufferIpc; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, ((pCert != null) && (certLen > 0)), E_INVALID_ARG, "Invalid input parameter."); + + certBufferIpc.pBuffer = pCert; + certBufferIpc.size = certLen; + + std::unique_ptr pMessage(new (std::nothrow) CertService_InsertCaCertificate(type, format, certBufferIpc, certLen, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::InsertUserCaCertificate(int format, char* pCert, int certLen) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + Tizen::Io::_IpcBuffer certBufferIpc; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, ((pCert != null) && (certLen > 0)), E_INVALID_ARG, "Invalid input parameter."); + + certBufferIpc.pBuffer = pCert; + certBufferIpc.size = certLen; + + std::unique_ptr pMessage(new (std::nothrow) CertService_InsertUserCaCertificate(format, certBufferIpc, certLen, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::InsertUserCaCertificate(byte* pFilePath) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + Tizen::Io::_IpcBuffer certBufferIpc; + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid input parameter."); + + certBufferIpc.pBuffer = pFilePath; + certBufferIpc.size = strlen(reinterpret_cast< char* >(pFilePath)) + 1; + + std::unique_ptr pMessage(new (std::nothrow) CertService_InstallUserRootCertificate(certBufferIpc, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + + +//User Certificate APIs + +result +_CertServiceProxy::InsertUserCertChainPrivateKey(char* pCertchainBuffer, int certChainLen, char* pUserPrivateKey, int userPrivateKeyLen) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + Tizen::Io::_IpcBuffer certPackBufferIPC; + Tizen::Io::_IpcBuffer privateKeyBufferIpc; + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, ((pCertchainBuffer != null) && (certChainLen > 0)), E_INVALID_ARG, "Invalid input parameter."); + + certPackBufferIPC.pBuffer = pCertchainBuffer; + certPackBufferIPC.size = certChainLen; + + privateKeyBufferIpc.pBuffer = pUserPrivateKey; + privateKeyBufferIpc.size = userPrivateKeyLen; + + std::unique_ptr pMessage(new (std::nothrow) CertService_InsertUserCertChainPrivateKey(certPackBufferIPC, certChainLen, privateKeyBufferIpc, userPrivateKeyLen, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::InsertCertificateChainWithPrivateKey(char* pCertchainPrivateKeyBuffer, int certChainPrivateKeyLength) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + Tizen::Io::_IpcBuffer certChainPriKeyBufferIpc; + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, ((pCertchainPrivateKeyBuffer != null) && (certChainPrivateKeyLength > 0)), E_INVALID_ARG, "Invalid input parameter."); + + certChainPriKeyBufferIpc.pBuffer = pCertchainPrivateKeyBuffer; + certChainPriKeyBufferIpc.size = certChainPrivateKeyLength; + + std::unique_ptr pMessage(new (std::nothrow) CertService_InsertCertificateChainWithPrivateKey(certChainPriKeyBufferIpc, certChainPrivateKeyLength, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::InsertPkcs12Content(char* pPkcs12FilePath, char* pPkcs12ImportPassword) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + Tizen::Io::_IpcBuffer pkcs12FileBufferIpc; + Tizen::Io::_IpcBuffer pkcs12PasswdBufferIpc; + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, pPkcs12FilePath != null, E_INVALID_ARG, "Invalid input parameter."); + + pkcs12FileBufferIpc.pBuffer = pPkcs12FilePath; + pkcs12FileBufferIpc.size = strlen(reinterpret_cast< char* >(pPkcs12FilePath)) + 1; + + pkcs12PasswdBufferIpc.pBuffer = pPkcs12ImportPassword; + pkcs12PasswdBufferIpc.size = strlen(reinterpret_cast< char* >(pPkcs12ImportPassword)) + 1; + + std::unique_ptr pMessage(new (std::nothrow) CertService_InstallPkcs12Content(pkcs12FileBufferIpc, pkcs12PasswdBufferIpc, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} +result +_CertServiceProxy::RemoveUserCertificateByCertId(int certId) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "Instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, certId >= 1, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr pMessage(new (std::nothrow) CertService_DeleteUserCertificateByCertId(certId, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::RemoveUserCertChainByCertId(int certId) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "Instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, certId >= 1, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr pMessage(new (std::nothrow) CertService_DeleteUserCertChainByCertId(certId, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} + +result +_CertServiceProxy::GetUserCertChainByIssuerAndSubjectNameN(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subNameLen, _CertificateListInfo*& pUserCertListInfoTypesRef) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + _CertificateListInfo* pRetNode = null; + Tizen::Io::_IpcBuffer issuerBufferIpc; + Tizen::Io::_IpcBuffer subjectBufferIpc; + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPCInstance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid Parameters"); + SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid Parameters"); + + issuerBufferIpc.pBuffer = pIssuerName; + issuerBufferIpc.size = issuerNameLen; + + subjectBufferIpc.pBuffer = pSubjectName; + subjectBufferIpc.size = subNameLen; + + pRetNode = new (std::nothrow) _CertificateListInfo(); + SysTryReturnResult(NID_SEC_CERT, pRetNode != null, E_OUT_OF_MEMORY, "Unable to allocate"); + + memset(pRetNode, 0, sizeof(*pRetNode)); + + std::unique_ptr pMessage(new (std::nothrow) CertService_GetUserCertChainByIssuerAndSubjectNameN(issuerBufferIpc, issuerNameLen, subjectBufferIpc, subNameLen, pRetNode, &ret)); + SysTryReturn(NID_SEC_CERT, pMessage != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryCatch(NID_SEC_CERT, !IsFailed(ret), r = ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + pUserCertListInfoTypesRef = pRetNode; + +CATCH: + if (IsFailed(r)) + { + _CertService::FreeCertList(pRetNode); + pRetNode = null; + } + + + return r; +} + +_CertInfo* +_CertServiceProxy::GetUserCertificateByCertIdN(int certId, int encodingType) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + _CertInfo* pRetNode = null; + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, null, "IPC instance is not constructed."); + + pRetNode = new (std::nothrow) _CertInfo(); + SysTryReturnResult(NID_SEC_CERT, pRetNode != null, null, "Unable to allocate"); + + memset(pRetNode, 0, sizeof(*pRetNode)); + + std::unique_ptr pMessage(new (std::nothrow) CertService_GetUserCertificateByCertIdN(certId, encodingType, pRetNode, &ret)); + SysTryCatch(NID_SEC_CERT, pMessage != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryCatch(NID_SEC_CERT, !IsFailed(ret), r = ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + +CATCH: + if (IsFailed(r)) + { + _CertService::FreeCertificateInfo(pRetNode); + pRetNode = null; + } + + return pRetNode; +} + +result +_CertServiceProxy::GetUserCertFieldInfoByCertId(int certId, _CertFieldInfos* pCertFieldInfos) +{ + result r = E_SUCCESS; + result ret = E_SUCCESS; + + ClearLastResult(); + + SysTryReturnResult(NID_SEC_CERT, __pIpcClient != null, E_SYSTEM, "IPC instance is not constructed."); + SysTryReturnResult(NID_SEC_CERT, pCertFieldInfos != null, E_INVALID_ARG, "Invalid input parameter."); + + std::unique_ptr pMessage(new (std::nothrow) CertService_GetUserCertFieldInfoByCertId(certId, pCertFieldInfos, &ret)); + SysTryReturnResult(NID_SEC_CERT, pMessage != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = __pIpcClient->SendRequest(pMessage.get()); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to send message.", GetErrorMessage(r)); + SysTryReturn(NID_SEC_CERT, !IsFailed(ret), ret, ret, "[%s] Stub function failed on service side.", GetErrorMessage(ret)); + + return r; +} +} } } diff --git a/src/security/cert/FSecCert_CertServiceStub.cpp b/src/security/cert/FSecCert_CertServiceStub.cpp new file mode 100755 index 0000000..4c43688 --- /dev/null +++ b/src/security/cert/FSecCert_CertServiceStub.cpp @@ -0,0 +1,436 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// +// @file FSecCert_CertServiceStub.cpp +// @brief This is the implementation file for the _CertServiceStub class. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertServiceStub.h" +#include "FSecCert_CertMgrMessages.h" +#include "FSecCert_CertService.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::App; +using namespace Tizen::Io; + +namespace Tizen { namespace Security { namespace Cert +{ + +_CertServiceStub::_CertServiceStub(void) + : __pIpcServer(null) +{ + +} + +_CertServiceStub::~_CertServiceStub(void) +{ + if (__pIpcServer != null) + { + __pIpcServer->Stop(); + delete __pIpcServer; + } +} + +result +_CertServiceStub::Construct(void) +{ + result r = E_SUCCESS; + + std::unique_ptr<_IpcServer> pIpcServer(new (std::nothrow) _IpcServer()); + SysTryReturnResult(NID_SEC_CERT, pIpcServer != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + r = pIpcServer->Construct(L"osp.security.ipcserver.certmanager", *this); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create IPC server(%s)", GetErrorMessage(r), "CertService"); + + __pIpcServer = pIpcServer.release(); + + _CertService::InitializeDb(); + + return r; +} + +bool +_CertServiceStub::OnUpdateRootCa(int type, Tizen::Io::_IpcBuffer certOldBufferIpc, Tizen::Io::_IpcBuffer certNewBufferIpc, result* pRet) +{ + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_WRITE); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pRet = _CertService::UpdateCaCertificate(static_cast< _CaCertType >(type), static_cast< char* >(certOldBufferIpc.pBuffer), certOldBufferIpc.size, + static_cast< char* >(certNewBufferIpc.pBuffer), certNewBufferIpc.size); + +CATCH: + return true; +} + +bool +_CertServiceStub::OnRemoveRootCa(int type, Tizen::Io::_IpcBuffer certBufferIpc, int bufLen, result* pRet) +{ + + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_WRITE); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pRet = _CertService::RemoveCaCertificate(static_cast< _CaCertType >(type), static_cast< char* >(certBufferIpc.pBuffer), bufLen); + +CATCH: + return true; +} + +bool +_CertServiceStub::OnInsertCaCertificate(int type, int format, Tizen::Io::_IpcBuffer pCert, long certLen, result* pRet) +{ + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_WRITE); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pRet = _CertService::InsertCaCertificate(static_cast< _CaCertType >(type), static_cast< _CertFormat >(format), static_cast< byte* >(pCert.pBuffer), certLen); +CATCH: + return true; +} + +bool +_CertServiceStub::OnInsertUserCaCertificate(int format, Tizen::Io::_IpcBuffer pCert, int certLen, result* pRet) +{ + *pRet = _CertService::InsertUserCaCertificate(static_cast< _CertFormat >(format), static_cast< char* >(pCert.pBuffer), certLen); + + return true; +} + +bool +_CertServiceStub::OnInstallUserRootCertificate(Tizen::Io::_IpcBuffer filePath, result* pRet) +{ + *pRet = _CertService::InsertUserCaCertificate(static_cast< byte* >(filePath.pBuffer)); + + return true; +} + +//User Certificate APIs +bool +_CertServiceStub::OnInsertUserCertChainPrivateKey(Tizen::Io::_IpcBuffer certChainBufferIpc, int certSize, Tizen::Io::_IpcBuffer privateKeyBufferIpc, int userPriKeyLen, result* pRet) +{ + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_WRITE); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pRet = _CertService::InsertUserCertChainPrivateKey(static_cast< char* >(certChainBufferIpc.pBuffer), certSize, static_cast< char* >(privateKeyBufferIpc.pBuffer), userPriKeyLen); + +CATCH: + return true; +} + +bool +_CertServiceStub::OnInsertCertificateChainWithPrivateKey(Tizen::Io::_IpcBuffer certChainPrivateKeyBufferIpc, int certChainPrivateKeyLength, result* pRet) +{ + *pRet = _CertService::InsertCertificateChainWithPrivateKey(static_cast< char* >(certChainPrivateKeyBufferIpc.pBuffer), certChainPrivateKeyLength); + + return true; +} + +bool +_CertServiceStub::OnInstallPkcs12Content(Tizen::Io::_IpcBuffer pkcs12FilePath, Tizen::Io::_IpcBuffer pkcs12ImportPassword, result* pRet) +{ + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_WRITE); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pRet = _CertService::InsertPkcs12Content(static_cast< char* >(pkcs12FilePath.pBuffer), static_cast< char* >(pkcs12ImportPassword.pBuffer)); + +CATCH: + return true; +} + +bool +_CertServiceStub::OnDeleteUserCertificateByCertId(int certId, result* pRet) +{ + *pRet = _CertService::RemoveUserCertificateByCertId(certId); + + return true; +} + +bool +_CertServiceStub::OnDeleteUserCertChainByCertId(int certId, result* pRet) +{ + *pRet = _CertService::RemoveUserCertChainByCertId(certId); + + return true; +} + +bool +_CertServiceStub::OnUninstallUserRootCertificateByCertId(int certId, result* pRet) +{ + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_WRITE); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pRet = _CertService::RemoveUserCaCertificateByCertId(certId); + +CATCH: + return true; +} + +bool +_CertServiceStub::OnGetUserCertChainByIssuerAndSubjectNameN(Tizen::Io::_IpcBuffer issuerBufferIpc, int issuerNameLen, Tizen::Io::_IpcBuffer subjectBufferIpc, int subNameLen, _CertificateListInfo* pCertList, result* pRet) +{ + _CertificateListInfo* pCertListIpc = null; + + *pRet = _CertService::GetUserCertChainByIssuerAndSubjectNameN(static_cast< char* >(issuerBufferIpc.pBuffer), issuerNameLen, static_cast< char* >(subjectBufferIpc.pBuffer), subNameLen, pCertListIpc); + + if (pCertListIpc != null) + { + std::unique_ptr<_CertificateListInfo> pCertListAuto(pCertListIpc); + + pCertList->certFileId = pCertListIpc->certFileId; + + pCertList->format = pCertListIpc->format; + pCertList->certType = pCertListIpc->certType; + pCertList->length = pCertListIpc->length; + pCertList->priKeyLen = pCertListIpc->priKeyLen; + + memcpy(pCertList->certificate, pCertListIpc->certificate, _MAX_CERTIFICATE_SIZE); + memcpy(pCertList->privatekey, pCertListIpc->privatekey, _MAX_CERT_PRIVATE_KEY_SIZE); + + pCertList->pNext = pCertListIpc->pNext; + } + else + { + memset(pCertList, 0, sizeof(*pCertList)); + } + + return true; +} + +bool +_CertServiceStub::OnGetUserCertificateByCertIdN(int certId, int encodingType, _CertInfo* pUserCertificateList, result* pRet) +{ + _CertInfo* pUserCertificateInfoIpc = null; + + *pRet = _CertService::GetUserCertificateByCertIdN(certId, static_cast< _CertEncodingType >(encodingType), pUserCertificateInfoIpc); + + if (pUserCertificateInfoIpc != null) + { + std::unique_ptr<_CertInfo> pCertInfoAuto(pUserCertificateInfoIpc); + + pUserCertificateList->certId = pUserCertificateInfoIpc->certId; + pUserCertificateList->certFormat = pUserCertificateInfoIpc->certFormat; + pUserCertificateList->certType = pUserCertificateInfoIpc->certType; + pUserCertificateList->certLength = pUserCertificateInfoIpc->certLength; + pUserCertificateList->privateKeyLen = pUserCertificateInfoIpc->privateKeyLen; + + memcpy(pUserCertificateList->certificate, pUserCertificateInfoIpc->certificate, _MAX_CERTIFICATE_SIZE); + memcpy(pUserCertificateList->privatekey, pUserCertificateInfoIpc->privatekey, _MAX_CERT_PRIVATE_KEY_SIZE); + } + else + { + memset(pUserCertificateList, 0, sizeof(*pUserCertificateList)); + } + return true; +} + +bool +_CertServiceStub::OnGetUserCertFieldInfoByCertId(int certId, _CertFieldInfos* pCertInfoBufferIpc, result* pRet) +{ + _CertFieldInfos certInfo; + + *pRet = _CertService::GetUserCertFieldInfoByCertId(certId, &certInfo); + + if (!IsFailed(*pRet)) + { + pCertInfoBufferIpc->certType = certInfo.certType; + pCertInfoBufferIpc->certFileId = certInfo.certFileId; + + memcpy(pCertInfoBufferIpc->serialNo, certInfo.serialNo, _MAX_SERIAL_NUMBER_SIZE + 1); + memcpy(pCertInfoBufferIpc->sigAlgorithm, certInfo.sigAlgorithm, _MAX_CERT_ALGORITHM_SIZE + 1); + memcpy(pCertInfoBufferIpc->validityFrom, certInfo.validityFrom, _MAX_CERT_VALIDITY_SIZE + 1); + memcpy(pCertInfoBufferIpc->validityTo, certInfo.validityTo, _MAX_CERT_VALIDITY_SIZE + 1); + memcpy(pCertInfoBufferIpc->subjectName, certInfo.subjectName, _MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + memcpy(pCertInfoBufferIpc->issuerName, certInfo.issuerName, _MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + memcpy(pCertInfoBufferIpc->fingerPrint, certInfo.fingerPrint, _MAX_CERT_FINGERPRINT_SIZE + 1); + + pCertInfoBufferIpc->fingerPrintLen = certInfo.fingerPrintLen; + + memcpy(pCertInfoBufferIpc->publicKey, certInfo.publicKey, _MAX_CERT_PUBLIC_KEY_SIZE + 1); + memcpy(static_cast< void* >(pCertInfoBufferIpc->certTypeFormat), static_cast< const void* >(certInfo.certTypeFormat), _MAX_CERT_TYPE_SIZE + 1); + + pCertInfoBufferIpc->certVersion = certInfo.certVersion; + + memcpy(pCertInfoBufferIpc->certTitle, certInfo.certTitle, _MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + memcpy(pCertInfoBufferIpc->certSubTitle, certInfo.certSubTitle, _MAX_ISSUER_SUBJECT_NAME_SIZE + 1); + + } + else + { + memset(pCertInfoBufferIpc, 0, sizeof(*pCertInfoBufferIpc)); + } + return true; +} + + +bool +_CertServiceStub::OnGetName(result* pRet) +{ + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_READ); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pRet = E_SUCCESS; + +CATCH: + return true; +} + +bool +_CertServiceStub::OnCloseCertificateStore(int certificateStoreCtx, result* pRet) +{ + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_READ); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pRet = _CertService::CloseCertificateStore(reinterpret_cast< CertificateStoreCtx >(certificateStoreCtx)); + +CATCH: + return true; +} + +bool +_CertServiceStub::OnOpenCertificateStoreByType(int type, int* pCount, int* pCertCtx, result* pRet) +{ + void* pCertList = null; + + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_READ); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + pCertList = _CertService::OpenCertificateStoreByType(static_cast< _CaCertType >(type), pCount); + + *pCertCtx = reinterpret_cast< int >(pCertList); + + *pRet = E_SUCCESS; + +CATCH: + return true; +} + +bool +_CertServiceStub::OnGetCertificateCount(int certificateStoreCtx, int* pCertCount, result* pRet) +{ + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_READ); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + *pCertCount = _CertService::GetCertificateCount(reinterpret_cast< CertificateStoreCtx >(certificateStoreCtx)); + + *pRet = E_SUCCESS; + +CATCH: + return true; +} + +bool +_CertServiceStub::OnGetNextCertificate(int certificateStoreCtx, int length, Tizen::Io::_IpcBuffer* pCertBufferIpc, result* pRet) +{ + char* pBuffer = null; + + *pRet = _AccessController::CheckSystemPrivilege(__pIpcServer->GetClientAppId(), _PRV_CERTIFICATE_READ); + SysTryCatch(NID_SEC_CERT, !IsFailed(*pRet), *pRet = E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method."); + + pBuffer = new (std::nothrow) char[length]; + SysTryCatch(NID_SEC_CERT, pBuffer, *pRet = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]Allocation failed"); + + *pRet = _CertService::GetNextCertificate(reinterpret_cast< CertificateStoreCtx >(certificateStoreCtx), pBuffer, &length); + +CATCH: + if (!IsFailed(*pRet)) + { + pCertBufferIpc->size = length; + pCertBufferIpc->pBuffer = pBuffer; + } + else + { + pCertBufferIpc->size = 0; + pCertBufferIpc->pBuffer = null; + } + + return true; +} + +void +_CertServiceStub::OnIpcRequestReceived(_IpcServer& server, const IPC::Message& message) +{ + IPC_BEGIN_MESSAGE_MAP(_CertServiceStub, message) + IPC_MESSAGE_HANDLER_EX(CertService_GetName, &server, OnGetName) + IPC_MESSAGE_HANDLER_EX(CertService_CloseCertificateStore, &server, OnCloseCertificateStore) + IPC_MESSAGE_HANDLER_EX(CertService_OpenCertificateStoreByType, &server, OnOpenCertificateStoreByType) + IPC_MESSAGE_HANDLER_EX(CertService_GetCertificateCount, &server, OnGetCertificateCount) + IPC_MESSAGE_HANDLER_EX(CertService_GetNextCertificate, &server, OnGetNextCertificate) + IPC_MESSAGE_HANDLER_EX(CertService_UpdateRootCa, &server, OnUpdateRootCa) + IPC_MESSAGE_HANDLER_EX(CertService_RemoveRootCa, &server, OnRemoveRootCa) + IPC_MESSAGE_HANDLER_EX(CertService_UninstallUserRootCertificateByCertId, &server, OnUninstallUserRootCertificateByCertId) + IPC_MESSAGE_HANDLER_EX(CertService_InsertCaCertificate, &server, OnInsertCaCertificate) + IPC_MESSAGE_HANDLER_EX(CertService_InsertUserCaCertificate, &server, OnInsertUserCaCertificate) + IPC_MESSAGE_HANDLER_EX(CertService_InstallUserRootCertificate, &server, OnInstallUserRootCertificate) + + //User Certificates API + IPC_MESSAGE_HANDLER_EX(CertService_InsertUserCertChainPrivateKey, &server, OnInsertUserCertChainPrivateKey) + IPC_MESSAGE_HANDLER_EX(CertService_InsertCertificateChainWithPrivateKey, &server, OnInsertCertificateChainWithPrivateKey) + IPC_MESSAGE_HANDLER_EX(CertService_InstallPkcs12Content, &server, OnInstallPkcs12Content) + IPC_MESSAGE_HANDLER_EX(CertService_DeleteUserCertChainByCertId, &server, OnDeleteUserCertChainByCertId) + IPC_MESSAGE_HANDLER_EX(CertService_DeleteUserCertificateByCertId, &server, OnDeleteUserCertificateByCertId) + IPC_MESSAGE_HANDLER_EX(CertService_GetUserCertChainByIssuerAndSubjectNameN, &server, OnGetUserCertChainByIssuerAndSubjectNameN) + IPC_MESSAGE_HANDLER_EX(CertService_GetUserCertificateByCertIdN, &server, OnGetUserCertificateByCertIdN) + IPC_MESSAGE_HANDLER_EX(CertService_GetUserCertFieldInfoByCertId, &server, OnGetUserCertFieldInfoByCertId) + + IPC_END_MESSAGE_MAP_EX(); +} + + +void +_CertServiceStub::OnIpcServerStarted(const _IpcServer& server) +{ + +} + +void +_CertServiceStub::OnIpcServerStopped(const _IpcServer& server) +{ + +} + +void +_CertServiceStub::OnIpcClientConnected(const _IpcServer& server, int clientId) +{ + +} + +void +_CertServiceStub::OnIpcClientDisconnected(const _IpcServer& server, int clientId) +{ + +} + +} } } diff --git a/src/security/cert/FSecCert_CertSignature.cpp b/src/security/cert/FSecCert_CertSignature.cpp new file mode 100755 index 0000000..a7fcf05 --- /dev/null +++ b/src/security/cert/FSecCert_CertSignature.cpp @@ -0,0 +1,253 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// +// @file FSecCert_CertSignature.cpp +// @brief This file contains implementation of X509 Certificate signature. +// + +#undef USE_MD2 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef USE_MD2 +#include +#endif +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertSignature.h" +#include "FSecCert_CertOidDef.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Cert +{ + +// _CertSignature class + +_CertSignature::_CertSignature(void) + : __signLen(0) + , __pSignValue(null) + , __pSignatureAlgId(null) +{ +} + +_CertSignature::_CertSignature(const char* pSigAlgId, int len, byte* pValue) +{ + SetSignature(pSigAlgId, len, pValue); +} + +_CertSignature::~_CertSignature(void) +{ +} + +void +_CertSignature::SetSignature(const char* pSigAlgId, int len, byte* pValue) +{ + ClearLastResult(); + + if (pSigAlgId != null) + { + int algLen = strlen(pSigAlgId); + + __pSignatureAlgId = std::unique_ptr(new (std::nothrow) char[algLen + 1]); + SysTryReturn(NID_SEC_CERT, __pSignatureAlgId != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new char array failed."); + + memcpy(__pSignatureAlgId.get(), pValue, algLen); + __pSignatureAlgId[algLen] = 0x00; + } + + __signLen = 0; + + if (pValue != null && len > 0) + { + __pSignValue = std::unique_ptr(new (std::nothrow) byte[len + 1]); + SysTryReturn(NID_SEC_CERT, __pSignValue != null, , E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + memcpy(__pSignValue.get(), pValue, len); + __pSignValue[len] = 0x00; + __signLen = len; + } +} + +result +_CertSignature::Verify(byte* pData, int dataLen, byte* pModulus, int keyLen, byte* pExponent, int expLen) +{ + result r = E_SUCCESS; + std::unique_ptr pDataHash(null); + int dataHashLen = 0; + int secRes = 0; + int rsaType = 0; + int ret = 0; + int tempSignLen = 0; + + SysTryReturnResult(NID_SEC_CERT, pData != null, E_INVALID_ARG, "Invalid input data."); + SysTryReturnResult(NID_SEC_CERT, pExponent != null, E_INVALID_ARG, "Invalid exponent buffer."); + SysTryReturnResult(NID_SEC_CERT, pModulus != null, E_INVALID_ARG, "Invalid modulus buffer."); + SysTryReturnResult(NID_SEC_CERT, dataLen > 0, E_INVALID_ARG, "Invalid data length."); + SysTryReturnResult(NID_SEC_CERT, expLen > 0, E_INVALID_ARG, "Invalid exponent length."); + SysTryReturnResult(NID_SEC_CERT, keyLen > 0, E_INVALID_ARG, "Invalid key length."); + + + if (memcmp(__pSignatureAlgId.get(), _OID_SIG_SHA1_RSA, strlen(__pSignatureAlgId.get())) == 0) + { + rsaType = NID_sha1; // NID_sha1WithRSAEncryption; // sha1 with RSA + dataHashLen = SHA_DIGEST_LENGTH; + pDataHash = std::unique_ptr (new (std::nothrow) byte[SHA_DIGEST_LENGTH + 1]); + SysTryReturnResult(NID_SEC_CERT, pDataHash != null, E_OUT_OF_MEMORY, "Allocating new byte array failed."); + + memset(pDataHash.get(), 0, SHA_DIGEST_LENGTH + 1); + //As per OpenSSL APIs, it takes input as unsigned data types + ret = EVP_Digest(pData, dataLen, pDataHash.get(), reinterpret_cast< unsigned int* >(&dataHashLen), EVP_sha1(), 0); + SysTryReturnResult(NID_SEC_CERT, ret == 1, E_SYSTEM, "Failed to create digest hash."); + } + else if (memcmp(__pSignatureAlgId.get(), _OID_SIG_MD5_RSA, strlen(__pSignatureAlgId.get())) == 0) + { + rsaType = NID_md5; // NID_md5WithRSAEncryption; //MD5 with RSA + dataHashLen = MD5_DIGEST_LENGTH; + pDataHash = std::unique_ptr (new (std::nothrow) byte[MD5_DIGEST_LENGTH + 1]); + SysTryReturnResult(NID_SEC_CERT, pDataHash != null, E_OUT_OF_MEMORY, "Allocating new byte array failed."); + + memset(pDataHash.get(), 0, MD5_DIGEST_LENGTH + 1); + //As per OpenSSL APIs, it takes input as unsigned data types + ret = EVP_Digest(pData, dataLen, pDataHash.get(), reinterpret_cast< unsigned int* >(&dataHashLen), EVP_md5(), 0); + SysTryReturnResult(NID_SEC_CERT, ret == 1, E_SYSTEM, "Failed to create digest hash."); + } + else if (memcmp(__pSignatureAlgId.get(), _OID_SIG_MD2_RSA, strlen(__pSignatureAlgId.get())) == 0) + { + rsaType = NID_md2; // NID_md2WithRSAEncryption; +#ifdef _USE_MD2 + dataHashLen = MD2_DIGEST_LENGTH; + pDataHash = new (std::nothrow) byte[MD2_DIGEST_LENGTH + 1]; + SysTryReturnResult(NID_SEC_CERT, pDataHash != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + memset(pDataHash, 0, MD2_DIGEST_LENGTH + 1); + //As per OpenSSL APIs, it takes input as unsigned data types + ret = EVP_Digest(pData, dataLen, pDataHash, &dataHashLen, EVP_md2(), 0); + SysTryReturnResult(NID_SEC_CERT, ret == 1, E_SYSTEM, "Failed to create digest hash."); + +#else + SysLogException(NID_SEC_CERT, E_FAILURE, "[E_FAILURE] Md2 with RSA algorithm not supported."); + return E_SYSTEM; +#endif + } + else if (memcmp(__pSignatureAlgId.get(), _OID_SIG_SHA_224_RSA, strlen(__pSignatureAlgId.get())) == 0) + { + rsaType = NID_sha224; // NID_sha224WithRSAEncryption; + dataHashLen = SHA224_DIGEST_LENGTH; + pDataHash = std::unique_ptr (new (std::nothrow) byte[SHA224_DIGEST_LENGTH + 1]); + SysTryReturnResult(NID_SEC_CERT, pDataHash != null, E_OUT_OF_MEMORY, "Allocating new byte array failed."); + + memset(pDataHash.get(), 0, SHA224_DIGEST_LENGTH + 1); + //As per OpenSSL APIs, it takes input as unsigned data types + ret = EVP_Digest(pData, dataLen, pDataHash.get(), reinterpret_cast< unsigned int* >(&dataHashLen), EVP_sha224(), 0); + SysTryReturnResult(NID_SEC_CERT, ret == 1, E_SYSTEM, "Failed to create digest hash."); + } + else if (memcmp(__pSignatureAlgId.get(), _OID_SIG_SHA_256_RSA, strlen(__pSignatureAlgId.get())) == 0) + { + rsaType = NID_sha256; // NID_sha256WithRSAEncryption; + dataHashLen = SHA256_DIGEST_LENGTH; + pDataHash = std::unique_ptr (new (std::nothrow) byte[SHA256_DIGEST_LENGTH + 1]); + SysTryReturnResult(NID_SEC_CERT, pDataHash != null, E_OUT_OF_MEMORY, "Allocating new byte array failed."); + + memset(pDataHash.get(), 0, SHA256_DIGEST_LENGTH + 1); + //As per OpenSSL APIs, it takes input as unsigned data types + ret = EVP_Digest(pData, dataLen, pDataHash.get(), reinterpret_cast< unsigned int* >(&dataHashLen), EVP_sha256(), 0); + SysTryReturnResult(NID_SEC_CERT, ret == 1, E_SYSTEM, "Failed to create digest hash."); + } + else if (memcmp(__pSignatureAlgId.get(), _OID_SIG_SHA_384_RSA, strlen(__pSignatureAlgId.get())) == 0) + { + rsaType = NID_sha384; // NID_sha384WithRSAEncryption; + dataHashLen = SHA384_DIGEST_LENGTH; + pDataHash = std::unique_ptr (new (std::nothrow) byte[SHA384_DIGEST_LENGTH + 1]); + SysTryReturnResult(NID_SEC_CERT, pDataHash != null, E_OUT_OF_MEMORY, "Allocating new byte array failed."); + + memset(pDataHash.get(), 0, SHA384_DIGEST_LENGTH + 1); + //As per OpenSSL APIs, it takes input as unsigned data types + ret = EVP_Digest(pData, dataLen, pDataHash.get(), reinterpret_cast< unsigned int* >(&dataHashLen), EVP_sha384(), 0); + SysTryReturnResult(NID_SEC_CERT, ret == 1, E_SYSTEM, "Failed to create digest hash."); + } + else if (memcmp(__pSignatureAlgId.get(), _OID_SIG_SHA_512_RSA, strlen(__pSignatureAlgId.get())) == 0) + { + rsaType = NID_sha512; // NID_sha512WithRSAEncryption; + dataHashLen = SHA512_DIGEST_LENGTH; + pDataHash = std::unique_ptr (new (std::nothrow) byte[SHA512_DIGEST_LENGTH + 1]); + SysTryReturnResult(NID_SEC_CERT, pDataHash != null, E_OUT_OF_MEMORY, "Allocating new byte array failed."); + + memset(pDataHash.get(), 0, SHA512_DIGEST_LENGTH + 1); + //As per OpenSSL APIs, it takes input as unsigned data types + ret = EVP_Digest(pData, dataLen, pDataHash.get(), reinterpret_cast< unsigned int* >(&dataHashLen), EVP_sha512(), 0); + SysTryReturnResult(NID_SEC_CERT, ret == 1, E_SYSTEM, "Failed to create digest hash."); + } + else + { + SysLogException(NID_SEC_CERT, E_FAILURE, "[E_FAILURE] Signature algorithm unknown."); + return E_SYSTEM; + } + + if (pDataHash != null) + { + RSA* pPubKey = null; + pPubKey = RSA_new(); + SysTryReturnResult(NID_SEC_CERT, pPubKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory."); + + pPubKey->n = BN_bin2bn(static_cast< const byte* >(pModulus), keyLen, pPubKey->n); + pPubKey->e = BN_bin2bn(static_cast< const byte* >(pExponent), expLen, pPubKey->e); + tempSignLen = static_cast< short >(__signLen); + //As per OpenSSL APIs, it takes input as unsigned data types + secRes = RSA_verify(rsaType, pDataHash.get(), dataHashLen, __pSignValue.get(), static_cast< unsigned int >(tempSignLen), pPubKey); + SysTryReturnResult(NID_SEC_CERT, secRes == 1, E_SYSTEM, "RSA verification failed."); + + r = E_SUCCESS; + + RSA_free(pPubKey); + } + + return r; +} + +char* +_CertSignature::GetSignatureAlgo(void) +{ + ClearLastResult(); + return __pSignatureAlgId.release(); +} + +byte* +_CertSignature::GetSignatureInfo(int& sigLen) +{ + ClearLastResult(); + sigLen = __signLen; + return __pSignValue.get(); +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertSignature.h b/src/security/cert/FSecCert_CertSignature.h new file mode 100755 index 0000000..b3bc3df --- /dev/null +++ b/src/security/cert/FSecCert_CertSignature.h @@ -0,0 +1,65 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertSignature.h + * @brief This header file contains the declarations of certificate signature verification. + * + * This header file contains the declarations of certificate signature verification. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_SIGNATURE_H_ +#define _FSEC_CERT_INTERNAL_CERT_SIGNATURE_H_ + +#include +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertSignature +{ +public: + _CertSignature(void); + + _CertSignature(const char* pSigAlgId, int len, byte* pValue); + + virtual ~_CertSignature(void); + + void SetSignature(const char* pSigAlgId, int len, byte* pValue); + + result Verify(byte* data, int dataLen, byte* pModulus, int keyLen, byte* pExponent, int expLen); + + byte* GetSignatureInfo(int& sigLen); + + char* GetSignatureAlgo(void); + +private: + _CertSignature(const _CertSignature& rhs); + + _CertSignature& operator =(const _CertSignature& rhs); + +private: + int __signLen; + std::unique_ptr __pSignValue; + std::unique_ptr __pSignatureAlgId; + +}; //_CertSignature + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_SIGNATURE_H_ diff --git a/src/security/cert/FSecCert_CertTime.cpp b/src/security/cert/FSecCert_CertTime.cpp new file mode 100755 index 0000000..cedb913 --- /dev/null +++ b/src/security/cert/FSecCert_CertTime.cpp @@ -0,0 +1,173 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +// +// @file FSecCert_CertTime.cpp +// @brief This file contains implementation of X509 Certificate Time. +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_CertTime.h" + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Locales; + +namespace Tizen { namespace Security { namespace Cert +{ + + +void +_CertTime::FormatDateTime(Tizen::Base::DateTime& time, char* pFormattedDatTime) +{ + result r = E_SUCCESS; + String formattedStr; + String cutomizedPattern = L"yyyy-MM-dd HH:mm:ss"; + LocaleManager localeManager; + + ClearLastResult(); + SysTryReturnVoidResult(NID_SEC_CERT, pFormattedDatTime != null, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument."); + + r = localeManager.Construct(); + SysTryReturnVoidResult(NID_SEC_CERT, !IsFailed(r), E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + Locale systemLocale = localeManager.GetSystemLocale(); + + std::unique_ptr pDateFormatter(DateTimeFormatter::CreateDateFormatterN(systemLocale, DATE_TIME_STYLE_FULL)); + SysTryReturnVoidResult(NID_SEC_CERT, pDateFormatter != null, GetLastResult(), "[%s] Failed to create date formet.", GetErrorMessage(GetLastResult())); + + pDateFormatter->ApplyPattern(cutomizedPattern); + + r = pDateFormatter->Format(time, formattedStr); + SysTryReturnVoidResult(NID_SEC_CERT, !IsFailed(r), r, "[%s] Failed to create time formet.", GetErrorMessage(r)); + + std::unique_ptr pTemp(Tizen::Base::_StringConverter::CopyToCharArrayN(formattedStr)); + SysTryReturnVoidResult(NID_SEC_CERT, pTemp != null, GetLastResult(), "[%s] Failed to convert string array.", GetErrorMessage(GetLastResult())); + + memcpy(pFormattedDatTime, pTemp.get(), strlen(pTemp.get()) + 1); +} + + +_CertTime::_CertTime(void) +{ + memset(__value, 0, _MAX_CERT_TIME_LEN + 1); +} + +_CertTime::_CertTime(_CertTimeType type, byte* pValue) +{ + // CertExtType = type; + SysTryReturnVoidResult(NID_SEC_CERT, pValue != null, E_INVALID_ARG, "Invalid input argument."); + SetTime(type, pValue); +} + +_CertTime::~_CertTime(void) +{ + //Empty statement +} + +void +_CertTime::SetTime(_CertTimeType type, byte* pValue) +{ + int len = 0; + // YYMMDDHHMMSSZ + + ClearLastResult(); + SysTryReturnVoidResult(NID_SEC_CERT, pValue != null, E_INVALID_ARG, "Invalid input argument."); + + if (type == CERT_TIME_UTC) + { + byte tmpTime[_MAX_CERT_TIME_LEN + 1] = {0, }; + if (pValue[0] < '5') + { + strcpy(reinterpret_cast< char* >(tmpTime), reinterpret_cast< const char* >("20")); + } + else + { + strcpy(reinterpret_cast< char* >(tmpTime), reinterpret_cast< const char* >("19")); + } + + strcat(reinterpret_cast< char* >(tmpTime), reinterpret_cast< char* >(pValue)); + strcpy(reinterpret_cast< char* >(__value), reinterpret_cast< char* >(tmpTime)); + } + else + { + len = strlen((reinterpret_cast< const char* >(pValue))); + SysTryReturnVoidResult(NID_SEC_CERT, len <= _MAX_CERT_TIME_LEN, E_OUT_OF_RANGE, "[E_OUT_OF_RANGE] Timestamp string's length out of range."); + + strcpy(reinterpret_cast< char* >(__value), reinterpret_cast< char* >(pValue)); + } +} + +void +_CertTime::SetTime(byte* pValue) +{ + ClearLastResult(); + SysTryReturnVoidResult(NID_SEC_CERT, pValue != null, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input argument."); + + memcpy(__value, pValue, _MAX_CERT_TIME_LEN + 1); +} + +byte* +_CertTime::GetTime(void) +{ + ClearLastResult(); + return __value; +} + +void +_CertTime::ConvertToDateTime(Tizen::Base::DateTime& cmTime) +{ + char tYear[5] = {0, }; + char tMonth[3] = {0, }; + char tDay[3] = {0, }; + char tHour[3] = {0, }; + char tMinute[3] = {0, }; + char tSecond[3] = {0, }; + + ClearLastResult(); + + strncpy(tYear, reinterpret_cast< const char* >(&__value[0]), 4); + tYear[4] = '\0'; + strncpy(tMonth, reinterpret_cast< const char* >(&__value[4]), 2); + tMonth[2] = '\0'; + strncpy(tDay, reinterpret_cast< const char* >(&__value[6]), 2); + tDay[2] = '\0'; + strncpy(tHour, reinterpret_cast< const char* >(&__value[8]), 2); + tHour[2] = '\0'; + strncpy(tMinute, reinterpret_cast< const char* >(&__value[10]), 2); + tMinute[2] = '\0'; + strncpy(tSecond, reinterpret_cast< const char* >(&__value[12]), 2); + tSecond[2] = '\0'; + cmTime.SetValue((atoi(tYear) % 10000), ((atoi(tMonth)) % 13), ((atoi(tDay)) % 32), ((atoi(tHour)) % 24), ((atoi(tMinute)) % 60), + ((atoi(tSecond)) % 60)); +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_CertTime.h b/src/security/cert/FSecCert_CertTime.h new file mode 100755 index 0000000..30ba720 --- /dev/null +++ b/src/security/cert/FSecCert_CertTime.h @@ -0,0 +1,71 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertTime.h + * @brief This header file contains the declarations of certificate time. + * + * This header file contains the declarations of certificate time. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_TIME_H_ +#define _FSEC_CERT_INTERNAL_CERT_TIME_H_ + +#include +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertTime +{ +public: + enum _CertTimeType + { + CERT_TIME_UTC = 0, + CERT_TIME_GENERAL = 1 + }; //_CertTimeType + + _CertTime(void); + + _CertTime(_CertTimeType type, byte* pValue); + + virtual ~_CertTime(void); + + void SetTime(_CertTimeType type, byte* pValue); + + void SetTime(byte* pValue); + + byte* GetTime(void); + + void ConvertToDateTime(Tizen::Base::DateTime& cmTime); + + static void FormatDateTime(Tizen::Base::DateTime& time, char* pFormattedDatTime); + +private: + _CertTime(const _CertTime& rhs); + + _CertTime& operator =(const _CertTime& rhs); + +private: + byte __value[_MAX_CERT_TIME_LEN + 1]; // stored GeneralizedTime format - YYYYMMDDHHMMSSZ + +}; //_CertTime + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_TIME_H_ diff --git a/src/security/cert/FSecCert_Certificate.cpp b/src/security/cert/FSecCert_Certificate.cpp new file mode 100644 index 0000000..89f7fb5 --- /dev/null +++ b/src/security/cert/FSecCert_Certificate.cpp @@ -0,0 +1,968 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_Certificate.cpp + * @brief This file contains implementation of X509 Certificate. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCert_Certificate.h" +#include "FSecCert_CertOidDef.h" + +using namespace Tizen::Base; +using namespace Tizen::System; + +namespace Tizen { namespace Security { namespace Cert +{ + + +// _X509CertSubPublicKeyInfo class +_X509CertSubPublicKeyInfo::_X509CertSubPublicKeyInfo(void) + : __pPubKeyAlg(null) + , __publicKey(null) + , __publicKeySize(0) +{ + +} + +_X509CertSubPublicKeyInfo::_X509CertSubPublicKeyInfo(const char* pAlg, int keyLen, byte* pPubKey) + : __pPubKeyAlg(null) + , __publicKey(null) + , __publicKeySize(0) +{ + // MAY need alg ID check. + SetPubKeyAlgoId(pAlg); + + // pubKey MUST DER-decoded BIT STRING + SetPubKey(keyLen, pPubKey); +} + +_X509CertSubPublicKeyInfo::~_X509CertSubPublicKeyInfo(void) +{ +} + +result +_X509CertSubPublicKeyInfo::GetPubKeyN(int& keyLen, byte** ppPubKey) +{ + keyLen = 0; + *ppPubKey = null; + + SysTryReturnResult(NID_SEC_CERT, __publicKeySize > 0, E_SYSTEM, "Public key is not set as public key length is 0."); + SysTryReturnResult(NID_SEC_CERT, __publicKey != null, E_SYSTEM, "Public key is not set."); + + keyLen = __publicKeySize; + *ppPubKey = new (std::nothrow) byte[keyLen + 1]; + SysTryReturnResult(NID_SEC_CERT, *ppPubKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memset(*ppPubKey, 0, keyLen + 1); + memcpy(*ppPubKey, __publicKey.get(), keyLen); + + return E_SUCCESS; +} + +result +_X509CertSubPublicKeyInfo::SetPubKey(int keyLen, byte* pPubKey) +{ + __publicKey.reset(null); + + __publicKey = std::unique_ptr (new (std::nothrow) byte[keyLen + 1]); + SysTryReturnResult(NID_SEC_CERT, __publicKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memcpy(__publicKey.get(), pPubKey, keyLen); + __publicKey[keyLen] = 0x00; + __publicKeySize = keyLen; + + return E_SUCCESS; +} + +char* +_X509CertSubPublicKeyInfo::GetPubKeyAlgoId() +{ + return __pPubKeyAlg.get(); +} + +result +_X509CertSubPublicKeyInfo::SetPubKeyAlgoId(const char* pPubKeyAlgoId) +{ + __pPubKeyAlg.reset(null); + + if (pPubKeyAlgoId) + { + int algSize = strlen(pPubKeyAlgoId); + + __pPubKeyAlg = std::unique_ptr (new (std::nothrow) char[algSize + 1]); + SysTryReturnResult(NID_SEC_CERT, __pPubKeyAlg != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memcpy(__pPubKeyAlg.get(), pPubKeyAlgoId, algSize); + __pPubKeyAlg[algSize] = 0x00; + } + + return E_SUCCESS; +} + + +// _X509CertValidity class +_X509CertValidity::_X509CertValidity(void) +{ +} + +_X509CertValidity::_X509CertValidity(byte* pNotBefore, byte* pNotAfter) +{ + SetTimes(pNotBefore, pNotAfter); +} + +_X509CertValidity::~_X509CertValidity(void) +{ +} + +result +_X509CertValidity::GetValidity(Tizen::Base::DateTime& drmTime) +{ + char validityFrom[_MAX_CERT_VALIDITY_SIZE + 1]; + char validityTo[_MAX_CERT_VALIDITY_SIZE + 1]; + char current[_MAX_CERT_VALIDITY_SIZE + 1]; + Tizen::Base::DateTime notAfter; + Tizen::Base::DateTime notBefore; + + __notAfter.ConvertToDateTime(notAfter); + __notBefore.ConvertToDateTime(notBefore); + + _CertTime::FormatDateTime(notBefore, validityFrom); + + //notBefore Format (Tizen::Base::DateTime::YYYYMMDD_HHMMSS, validityFrom) + _CertTime::FormatDateTime(drmTime, current); + + //drmTime Format (Tizen::Base::DateTime::YYYYMMDD_HHMMSS, current) + _CertTime::FormatDateTime(notAfter, validityTo); + + //notAfter Format(Tizen::Base::DateTime::YYYYMMDD_HHMMSS, validityTo) + + if (drmTime <= notAfter && drmTime >= notBefore) + { + return E_SUCCESS; + } + + return E_SYSTEM; +} + +result +_X509CertValidity::SetTimes(byte* pNotBefore, byte* pNotAfter) +{ + _CertTime::_CertTimeType beforeTimeType = _CertTime::CERT_TIME_UTC; + _CertTime::_CertTimeType afterTimeType = _CertTime::CERT_TIME_UTC; + + if (strlen(reinterpret_cast< const char* >(pNotBefore)) == static_cast< int >(_MAX_CERT_TIME_LEN)) + { + beforeTimeType = _CertTime::CERT_TIME_GENERAL; + } + + if (strlen(reinterpret_cast< const char* >(pNotBefore)) == static_cast< int >(_MAX_CERT_TIME_LEN)) + { + afterTimeType = _CertTime::CERT_TIME_GENERAL; + } + + __notBefore.SetTime(beforeTimeType, pNotBefore); + __notAfter.SetTime(afterTimeType, pNotAfter); + return E_SUCCESS; +} + +result +_X509CertValidity::GetBeforeTimes(Tizen::Base::DateTime& notBefore) +{ + __notBefore.ConvertToDateTime(notBefore); + return E_SUCCESS; +} + +result +_X509CertValidity::GetAfterTimes(Tizen::Base::DateTime& notAfter) +{ + __notAfter.ConvertToDateTime(notAfter); + return E_SUCCESS; +} + + +// _X509TbsCert class +_X509TbsCert::_X509TbsCert(void) + : __version(3) + , __serialNumberLen(null) + , __pIssuer(null) + , __pSubject(null) + , __pSignatureAlgoId(null) +{ + memset(__serialNumber, 0, _MAX_SERIAL_NUMBER_SIZE); +} + +_X509TbsCert::~_X509TbsCert(void) +{ +} + +// Version +void +_X509TbsCert::SetVersion(byte* pVersion, int len) +{ + __version = pVersion[0] + 1; // MUST be 3 +} + +void +_X509TbsCert::SetVersion(int version) +{ + __version = version; +} + +int +_X509TbsCert::GetVersion(void) +{ + return __version; +} + +// CertificateSerialNumber +void +_X509TbsCert::SetSerialNumber(byte* pSerial, int len) +{ + memcpy(__serialNumber, pSerial, len); + __serialNumberLen = len; +} + +result +_X509TbsCert::GetSerialNumber(byte*& pSerial, int& len) +{ + pSerial = __serialNumber; + len = __serialNumberLen; + + return E_SUCCESS; +} + +// AlgorithmIdentifier +result +_X509TbsCert::SetSignatureAlgoId(const char* pAlgoId) +{ + __pSignatureAlgoId.reset(null); + + if (pAlgoId) + { + int sigLen = strlen(pAlgoId); + + __pSignatureAlgoId = std::unique_ptr(new (std::nothrow) char[sigLen + 1]); + SysTryReturnResult(NID_SEC_CERT, __pSignatureAlgoId != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memcpy(__pSignatureAlgoId.get(), pAlgoId, sigLen); + __pSignatureAlgoId[sigLen] = 0x00; + } + + return E_SUCCESS; + +} + +char* +_X509TbsCert::GetSignatureAlgoId(void) +{ + return __pSignatureAlgoId.get(); +} + +// Issuer Name +result +_X509TbsCert::SetIssuerName(byte* pName) +{ + __pIssuer.reset(null); + + if (pName != null) + { + int len = strlen(reinterpret_cast< const char* >(pName)); + + __pIssuer = std::unique_ptr(new (std::nothrow) byte[len + 1]); + SysTryReturnResult(NID_SEC_CERT, __pIssuer != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memset(__pIssuer.get(), 0, len + 1); + strcpy(reinterpret_cast< char* >(__pIssuer.get()), reinterpret_cast< const char* >(pName)); + } + + return E_SUCCESS; +} + +byte* +_X509TbsCert::GetIssuerName(void) +{ + return __pIssuer.get(); +} + +// Validity +result +_X509TbsCert::SetValidity(byte* pNotBefore, byte* pNotAfter) +{ + return __validity.SetTimes(pNotBefore, pNotAfter); +} + +result +_X509TbsCert::GetValidity() +{ + Tizen::Base::DateTime curTime; + + Tizen::System::SystemTime::GetCurrentTime(UTC_TIME, curTime); + + return __validity.GetValidity(curTime); +} + +result +_X509TbsCert::GetBeforeTimes(Tizen::Base::DateTime& notBefore) +{ + __validity.GetBeforeTimes(notBefore); + return E_SUCCESS; +} + +result +_X509TbsCert::GetAfterTimes(Tizen::Base::DateTime& notAfter) +{ + return __validity.GetAfterTimes(notAfter); +} + +// Subject Name +result +_X509TbsCert::SetSubjectName(byte* pName) +{ + __pSubject.reset(null); + + if (pName != null) + { + int len = strlen(reinterpret_cast< const char* >(pName)); + + __pSubject = std::unique_ptr(new (std::nothrow) byte[len + 1]); + SysTryReturnResult(NID_SEC_CERT, __pSubject != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memset(__pSubject.get(), 0, len + 1); + strcpy(reinterpret_cast< char* >(__pSubject.get()), reinterpret_cast< const char* >(pName)); + } + + return E_SUCCESS; +} + +byte* +_X509TbsCert::GetSubjectName() +{ + return __pSubject.get(); +} + + +// Subject Public Key Info +result +_X509TbsCert::SetPublicKeyInfo(int keyLen, byte* pPubKey) +{ + return __subPubKeyInfo.SetPubKey(keyLen, pPubKey); +} + +result +_X509TbsCert::GetPublicKeyInfoN(int& keyLen, byte** ppPubKey) +{ + return __subPubKeyInfo.GetPubKeyN(keyLen, ppPubKey); +} + +result +_X509TbsCert::SetPublicKeyAlgoIdInfo(const char* pPubKeyAlgoId) +{ + return __subPubKeyInfo.SetPubKeyAlgoId(pPubKeyAlgoId); +} + +char* +_X509TbsCert::GetPublicKeyAlgoIdInfo() +{ + return __subPubKeyInfo.GetPubKeyAlgoId(); +} + +//Extensions +result +_X509TbsCert::AddExtension(byte* pOid, bool critical, byte* pValue, int len) +{ + if (pOid && pValue) + { + __extension.AddExt(pOid, critical, pValue, len); + return E_SUCCESS; + } + + return E_INVALID_ARG; +} + +_CertExtension* +_X509TbsCert::GetCertExtension() +{ + return &__extension; +} + +// _Certificate class +_Certificate::_Certificate(void) +{ + __certFormat = _CERT_X509; +} + +_Certificate::~_Certificate() +{ + //Empty body +} + +result +_Certificate::ParseObject(void) +{ + return E_UNSUPPORTED_OPERATION; +} + +result +_Certificate::GetKeyIdN(byte** ppKeyid) +{ + return E_UNSUPPORTED_OPERATION; +} + +bool +_Certificate::IsSelfSigned(void) +{ + return false; +} + +_CertFormat +_Certificate::GetCertFormat(void) +{ + return __certFormat; +} + +void +_Certificate::SetCertFormat(_CertFormat certFormat) +{ + __certFormat = certFormat; +} + +// +// _X509Certificate class +// +_X509Certificate::_X509Certificate(void) + : __contextCert(false) + , __isCaCert(false) + , __x509IsSelfSign(false) + , __pX509Certificate(null) +{ + SetCertFormat(_CERT_X509); +} + +_X509TbsCert* +_X509Certificate::GetTbsCertInstance(void) +{ + return &__tbsCert; +} + +_CertSignature* +_X509Certificate::GetSignInstance(void) +{ + return &__signautreInfo; +} + +_X509Certificate::~_X509Certificate(void) +{ + + if (__pX509Certificate != null) + { + X509_free(static_cast< X509* >(__pX509Certificate)); + } + +} + +bool +_X509Certificate::IsCaCertificate() +{ + return __isCaCert; +} + + +result +_X509Certificate::GetKeyIdN(byte** ppKeyid) +{ + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + byte* pPublicKey = null; + int len = 0; + int outLen = SHA_DIGEST_LENGTH; + int resValue = 0; + + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + pPublicKey = pX509Certificate->cert_info->key->public_key->data; + len = pX509Certificate->cert_info->key->public_key->length; + + if (pPublicKey[0] == 0x00) + { + pPublicKey++; + len--; + } + + std::unique_ptr pKeyId(new (std::nothrow) byte[SHA_DIGEST_LENGTH + 1]); + SysTryReturnResult(NID_SEC_CERT, pKeyId != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memset(pKeyId.get(), 0, SHA_DIGEST_LENGTH + 1); + //As per OpenSSL APIs, it takes input as unsigned data types + resValue = EVP_Digest(pPublicKey, len, pKeyId.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0); + SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to calculate digest hash."); + *ppKeyid = pKeyId.release(); + + return E_SUCCESS; +} + +result +_X509Certificate::GetCertBuffer(byte*& pBuf, int& bufSize) +{ + SysTryReturnResult(NID_SEC_CERT, _pX509Buff != null, E_SYSTEM, "Initial parameters are not set"); + + pBuf = _pX509Buff.get(); + bufSize = _x509BuffSize; + return E_SUCCESS; +} + +result +_X509Certificate::GetIssuerBuffer(byte*& pBuf, int& bufSize) +{ + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + pBuf = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->issuer, null, 0)); + bufSize = strlen(reinterpret_cast< char* >(pBuf)); + return E_SUCCESS; +} + +result +_X509Certificate::GetSubjectNameBuffer(byte*& pBuf, int& bufSize) +{ + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + pBuf = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->subject, null, 0)); + bufSize = strlen(reinterpret_cast< char* >(pBuf)); + return E_SUCCESS; +} + +bool +_X509Certificate::IsSelfSigned(void) +{ + return __x509IsSelfSign; +} + +void* +_X509Certificate::GetX509CertObject() +{ + return __pX509Certificate; +} + +bool +_X509Certificate::IsIssuer(Tizen::Security::Cert::_X509Certificate* pIssuerCert) +{ + SysTryReturnResult(NID_SEC_CERT, pIssuerCert != null, E_INVALID_ARG, "Invalid input parameters issuer certificate."); + + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + X509* pX509IssuerCertificate = static_cast< X509* >(pIssuerCert->__pX509Certificate); + + SysTryReturnResult(NID_SEC_CERT, pX509IssuerCertificate != null, E_INVALID_ARG, "Invalid input parameters issuer certificate."); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + if (X509_check_issued(pX509IssuerCertificate, pX509Certificate) == X509_V_OK) + { + return true; + } + + return false; +} + +bool +_X509Certificate::IsContextCertificate(void) +{ + return __contextCert; +} + +void +_X509Certificate::SetContextCertificate(bool contextCert) +{ + __contextCert = contextCert; +} + +result +_X509Certificate::VerifySignature(byte* pPublicKey, int keySize) +{ + result r = E_SUCCESS; + EVP_PKEY* pKey = null; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + const unsigned char* pPublicKeyBuffer = const_cast< const unsigned char* >(pPublicKey); + + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + if (pPublicKeyBuffer != null && keySize > 0) + { + pKey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &pPublicKeyBuffer, keySize); + } + else //check if self signed + { + pKey = X509_get_pubkey(pX509Certificate); + } + + SysTryReturnResult(NID_SEC_CERT, pKey != null, E_SYSTEM, "Public key could not be constructed."); + + if (X509_verify(pX509Certificate, pKey) <= 0) + { + SysTryReturnResult(NID_SEC_CERT, false, E_SYSTEM, "Openssl X509 certificate verify function failed."); + } + + + return r; +} + +// Get Total length + +// Get TBSCertificate length +result +_X509Certificate::ParseTbsCertHeader(void) +{ + if (ParseVersion() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + + if (ParseSerialNumber() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + + if (ParseAlgorithmIdentifier() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + + if (ParseIssuerName() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + + if (ParseValidity() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + + if (ParseSubjectName() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + + + if (ParseSubjectPublicKeyInfo() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + + if (ParseExtensions() != E_SUCCESS) + { + return E_PARSING_FAILED; + } + return E_SUCCESS; +} + + +// Get Header Info +// version [0] Version DEFAULT v1 +// Version ::= INTEGER {v1(0), v2(1), v3(2)} + +result +_X509Certificate::ParseVersion(void) +{ + int version = 0; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + + version = ASN1_INTEGER_get(pX509Certificate->cert_info->version) + 1; // default is 0 --> version 1 + __tbsCert.SetVersion(version); + + return E_SUCCESS; +} + +// CertificateSerialNumber ::= INTEGER +result +_X509Certificate::ParseSerialNumber(void) +{ + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + __tbsCert.SetSerialNumber(pX509Certificate->cert_info->serialNumber->data, pX509Certificate->cert_info->serialNumber->length); + return E_SUCCESS; +} + + +// AlgorithmIdentifier ::= SEQUENCE { +// algorithm ALGORITHM.&id({SupportedAlgorithms}), +// parameters ALGORITHM.&Type({SupportedAlgorithms}{@algorithm}) OPTIONAL +// } +// 1.2.840.113549.1.1.5 - SHA1RSA + +result +_X509Certificate::ParseAlgorithmIdentifier(void) +{ + const char* pAlgorithmIdentifier = null; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + pAlgorithmIdentifier = OBJ_nid2ln(OBJ_obj2nid(pX509Certificate->cert_info->signature->algorithm)); + + return __tbsCert.SetSignatureAlgoId(pAlgorithmIdentifier); +} + +// SEQUENCE > [SET > SEQUENCE > [OID > VALUE]] + +result +_X509Certificate::ParseIssuerName(void) +{ + byte* pName = null; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + pName = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->issuer, null, 0)); + SysTryReturnResult(NID_SEC_CERT, pName != null, E_PARSING_FAILED, "Failed to get certificate issuer name."); + + __tbsCert.SetIssuerName(pName); + + return E_SUCCESS; +} + +// Validity ::= SEQUENCE {notBefore Time, +// notAfter Time +// } +// Time ::= CHOICE {utcTime UTCTime, +// generalizedTime GeneralizedTime +// } + +result +_X509Certificate::ParseValidity(void) +{ + result r = E_SUCCESS; + ASN1_GENERALIZEDTIME* timeNotBefore = NULL; + ASN1_GENERALIZEDTIME* timeNotAfter = NULL; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + + ASN1_TIME_to_generalizedtime(pX509Certificate->cert_info->validity->notBefore, &timeNotBefore); + ASN1_TIME_to_generalizedtime(pX509Certificate->cert_info->validity->notAfter, &timeNotAfter); + + std::unique_ptr pNotBefore(new (std::nothrow) byte[timeNotBefore->length + 1]); + SysTryReturnResult(NID_SEC_CERT, pNotBefore != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memcpy(pNotBefore.get(), timeNotBefore->data, timeNotBefore->length); + pNotBefore[timeNotBefore->length] = 0x00; + + // get Time + + std::unique_ptr pNotAfter(new (std::nothrow) byte[timeNotAfter->length + 1]); + SysTryReturnResult(NID_SEC_CERT, pNotAfter != null, E_OUT_OF_MEMORY, "Failed to allocate memory"); + + memcpy(pNotAfter.get(), timeNotAfter->data, timeNotAfter->length); + pNotAfter[timeNotAfter->length] = 0x00; + + __tbsCert.SetValidity(pNotBefore.get(), pNotAfter.get()); + + return r; +} + +// SEQUENCE > [SET > SEQUENCE > [OID > VALUE]]+ +result +_X509Certificate::ParseSubjectName(void) +{ + result r = E_SUCCESS; + byte* pSubject = null; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + pSubject = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->subject, null, 0)); + SysTryReturnResult(NID_SEC_CERT, pSubject != null, E_PARSING_FAILED, "Failed to get certificate subject name."); + + __tbsCert.SetSubjectName(pSubject); + + if (X509_check_issued(pX509Certificate, pX509Certificate) == X509_V_OK) + { + __x509IsSelfSign = true; + } + else + { + __x509IsSelfSign = false; + } + + return r; +} + + +// SubjectPublicKeyInfo ::= SEQUENCE { +// algorithm AlgorithmIdentifier, +// subjectPublicKey BIT STRING +// } +// AlgorithmIdentifier ::= SEQUENCE { +// algorithm ALGORITHM.&id({SupportedAlgorithms}), +// parameters ALGORITHM.&Type({SupportedAlgorithms}{@algorithm}) OPTIONAL + +result +_X509Certificate::ParseSubjectPublicKeyInfo(void) +{ + result r = E_SUCCESS; + const char* pAlgorithmIdentifier = null; + byte* pPubKey = null; + int pubKeyLen = 0; + EVP_PKEY* pKey = null; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + pAlgorithmIdentifier = OBJ_nid2ln(OBJ_obj2nid(pX509Certificate->cert_info->key->algor->algorithm)); + __tbsCert.SetPublicKeyAlgoIdInfo(pAlgorithmIdentifier); + + /* get public key */ + pKey = X509_get_pubkey(pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pKey != null, E_PARSING_FAILED, "Failed to get certificate public key."); + + pubKeyLen = i2d_PublicKey(pKey, &pPubKey); + + __tbsCert.SetPublicKeyInfo(pubKeyLen, pPubKey); + +CATCH: + OPENSSL_free(pPubKey); + return r; +} + +/** + Extensions ::= SEQUENCE OF Extension + Extension ::= SEQUENCE { + extnId EXTENSION.&id({ExtensionSet}), + critical BOOLEAN DEFAULT false, + extnValue OCTET STRING-- contains a DER encoding of a value of type &ExtnType + -- for the extension object identified by extnId + } + */ +result +_X509Certificate::ParseExtensions(void) +{ + byte* pValue = null; + byte* pOid = null; + bool critical = false; + int fieldCount = 0; + int extLen = 0; + int count = 0; + X509_EXTENSION* pExt = NULL; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + if(pX509Certificate->cert_info->extensions == null) + { + return E_SUCCESS; + } + + fieldCount = sk_X509_EXTENSION_num(pX509Certificate->cert_info->extensions); + + for (count = 0; count < fieldCount; count++) + { + pExt = sk_X509_EXTENSION_value(pX509Certificate->cert_info->extensions, count); + + if (pExt != null) + { + pOid = reinterpret_cast< byte* >(const_cast< char* >(OBJ_nid2ln(OBJ_obj2nid(pExt->object)))); + + critical = pExt->critical; + pValue = pExt->value->data; + extLen = pExt->value->length; + + + if (pOid != null) + { + __tbsCert.AddExtension(pOid, critical, pValue, extLen); + } + } + + } // End of while loop + + return E_SUCCESS; + +} + +result +_X509Certificate::ParseSignature(void) +{ + result r = E_SUCCESS; + const char* pAlgorithmIdentifier = null; + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set"); + + pAlgorithmIdentifier = OBJ_nid2ln(OBJ_obj2nid(pX509Certificate->sig_alg->algorithm)); + SysTryReturnResult(NID_SEC_CERT, pAlgorithmIdentifier != null, E_SYSTEM, "Signature algorithm not present in certificate."); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate->signature->data != null, E_SYSTEM, "Signature data not present in certificate."); + + __signautreInfo.SetSignature(pAlgorithmIdentifier, pX509Certificate->signature->length, pX509Certificate->signature->data); + + return r; +} + +result +_X509Certificate::ParseRun(void) +{ + result r = E_PARSING_FAILED; + + r = ParseTbsCertHeader(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse tbs certificate.", GetErrorMessage(r)); + + r = ParseSignature(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse cert signature.", GetErrorMessage(r)); + + return r; +} + +result +_X509Certificate::ParseObject(void) +{ + X509* pX509Certificate = static_cast< X509* >(__pX509Certificate); + const unsigned char* pX509Buff = const_cast< const unsigned char* >(_pX509Buff.get()); + + SysAssertf(pX509Buff != null, "Not yet constructed. Reconstructor the object."); + + if (pX509Certificate != null) + { + X509_free(pX509Certificate); + __pX509Certificate = null; + } + + d2i_X509(&pX509Certificate, &pX509Buff, _x509BuffSize); + SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_PARSING_FAILED, "Failed to parse certificate."); + + __pX509Certificate = pX509Certificate; + + if (X509_check_ca(pX509Certificate) > 0) + { + __isCaCert = true; + } + + + return ParseRun(); +} + +} } } //Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_Certificate.h b/src/security/cert/FSecCert_Certificate.h new file mode 100755 index 0000000..b3a4f86 --- /dev/null +++ b/src/security/cert/FSecCert_Certificate.h @@ -0,0 +1,271 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_Certificate.h + * @brief This header file contains the declarations of parsing class. + * + * This header file contains the declarations of parsing class. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERTIFICATE_H_ +#define _FSEC_CERT_INTERNAL_CERTIFICATE_H_ + +#include +#include +#include "FSecCert_CertExtension.h" +#include "FSecCert_CertSignature.h" +#include "FSecCert_CertTime.h" +#include "FSecCert_Asn1Parser.h" +#include "FSecCert_CertTypes.h" + + +namespace Tizen { namespace Security { namespace Cert +{ + +class _OSP_EXPORT_ _X509CertValidity +{ +public: + _X509CertValidity(void); + + _X509CertValidity(byte* pNotBefore, byte* pNotAfter); + + virtual ~_X509CertValidity(void); + + result GetValidity(Tizen::Base::DateTime& drmTime); + + result SetTimes(byte* pNotBefore, byte* pNotAfter); + + result GetBeforeTimes(Tizen::Base::DateTime& notBefore); + + result GetAfterTimes(Tizen::Base::DateTime& notAfter); + +private: + _X509CertValidity(const _X509CertValidity& rhs); + + _X509CertValidity& operator =(const _X509CertValidity& rhs); + +private: + _CertTime __notBefore; + _CertTime __notAfter; + +}; //_X509CertValidity + +class _OSP_EXPORT_ _X509CertSubPublicKeyInfo +{ +public: + _X509CertSubPublicKeyInfo(void); + + _X509CertSubPublicKeyInfo(const char* pAlg, int keyLen, byte* pPubKey); + + virtual ~_X509CertSubPublicKeyInfo(void); + + result GetPubKeyN(int& keyLen, byte** ppPubKey); + + result SetPubKey(int keyLen, byte* pPubKey); + + char* GetPubKeyAlgoId(void); + + result SetPubKeyAlgoId(const char* pPubKeyAlgoId); + +private: + _X509CertSubPublicKeyInfo(const _X509CertSubPublicKeyInfo& rhs); + + _X509CertSubPublicKeyInfo& operator =(const _X509CertSubPublicKeyInfo& rhs); + +private: + std::unique_ptr __pPubKeyAlg; + std::unique_ptr __publicKey; + int __publicKeySize; + +}; //_X509CertSubPublicKeyInfo + +class _OSP_EXPORT_ _X509TbsCert +{ +public: + _X509TbsCert(void); + + virtual ~_X509TbsCert(void); + + void SetVersion(byte* pVersion, int len); + + void SetVersion(int version); + + int GetVersion(void); + + void SetSerialNumber(byte* pSerial, int len); + + result GetSerialNumber(byte*& pSerial, int& len); + + result SetSignatureAlgoId(const char* pAlgoId); + + char* GetSignatureAlgoId(void); + + result SetIssuerName(byte* pName); + + byte* GetIssuerName(void); + + result SetValidity(byte* pNotBefore, byte* pNotAfter); + + result GetValidity(void); + + result GetBeforeTimes(Tizen::Base::DateTime& notBefore); + + result GetAfterTimes(Tizen::Base::DateTime& notAfter); + + result SetSubjectName(byte* pName); + + byte* GetSubjectName(void); + + result SetPublicKeyInfo(int keyLen, byte* pPubKey); + + result GetPublicKeyInfoN(int& keyLen, byte** ppPubKey); + + char* GetPublicKeyAlgoIdInfo(void); + + result SetPublicKeyAlgoIdInfo(const char* pPubKeyAlgoId); + + result AddExtension(byte* pOid, bool critical, byte* pValue, int len); + + _CertExtension* GetCertExtension(void); + +private: + _X509TbsCert(const _X509TbsCert& rhs); + + _X509TbsCert& operator =(const _X509TbsCert& rhs); + +private: + int __version; + int __serialNumberLen; + byte __serialNumber[_MAX_SERIAL_NUMBER_SIZE]; + std::unique_ptr __pIssuer; + std::unique_ptr __pSubject; + std::unique_ptr __pSignatureAlgoId; + _CertExtension __extension; + _X509CertSubPublicKeyInfo __subPubKeyInfo; + _X509CertValidity __validity; + +}; //_X509TbsCert + +class _OSP_EXPORT_ _Certificate + : public _Asn1Parser +{ +public: + _Certificate(void); + + virtual ~_Certificate(void); + + result ParseObject(void); + + virtual result GetKeyIdN(byte** ppKeyid); + + virtual bool IsSelfSigned(void); + + _Certificate* GetNextEntry(void); + + void SetCertFormat(_CertFormat certFormat); + + _CertFormat GetCertFormat(void); + +private: + _Certificate(const _Certificate& rhs); + + _Certificate& operator =(const _Certificate& rhs); + +private: + _CertFormat __certFormat; + +}; //_Certificate + +class _OSP_EXPORT_ _X509Certificate + : public _Certificate +{ +public: + _X509Certificate(void); + + virtual ~_X509Certificate(void); + + result ParseObject(void); + + _X509TbsCert* GetTbsCertInstance(void); + + _CertSignature* GetSignInstance(void); + + result GetKeyIdN(byte** ppKeyid); + + bool IsSelfSigned(void); + + bool IsContextCertificate(void); + + void SetContextCertificate(bool contextCert); + + result GetCertBuffer(byte*& pBuf, int& bufSize); + + result GetIssuerBuffer(byte*& pBuf, int& bufSize); + + result GetSubjectNameBuffer(byte*& pBuf, int& bufSize); + + result VerifySignature(byte* pPublicKey, int keySize); + + bool IsCaCertificate(); + + _X509Certificate* GetNextEntry(void); + + bool IsIssuer(_X509Certificate* pCertIssuer); + + void* GetX509CertObject(); + +private: + _X509Certificate(const _X509Certificate& rhs); + + _X509Certificate& operator =(const _X509Certificate& rhs); + + result ParseRun(void); + + result ParseTbsCertHeader(void); + + result ParseVersion(void); + + result ParseSerialNumber(void); + + result ParseAlgorithmIdentifier(void); + + result ParseIssuerName(void); + + result ParseValidity(void); + + result ParseSubjectName(void); + + result ParseSubjectPublicKeyInfo(void); + + result ParseExtensions(void); + + result ParseSignature(void); + +private: + bool __contextCert; + bool __isCaCert; + bool __x509IsSelfSign; + void* __pX509Certificate; + _X509TbsCert __tbsCert; + _CertSignature __signautreInfo; + +}; //_X509Certificate + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERTIFICATE_H_ diff --git a/src/security/cert/FSecCert_X509CertificateStoreImpl.cpp b/src/security/cert/FSecCert_X509CertificateStoreImpl.cpp new file mode 100755 index 0000000..b787943 --- /dev/null +++ b/src/security/cert/FSecCert_X509CertificateStoreImpl.cpp @@ -0,0 +1,424 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_X509CertificateStoreImpl.cpp + * @brief This is the implementation file for _X509CertificateStoreImpl class. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Cert +{ + +static const int _MAX_CERT_BUFFER_SIZE = 2048; + +_X509CertificateStoreImpl::_X509CertificateStoreImpl(void) + : __certType(static_cast< int >(_CERT_TYPE_NOT_BOUNDED)) + , __certificateStoreCtx(0) +{ + ClearLastResult(); + + __pCertServiceProxy = _CertServiceProxy::GetInstance(); + SysTryReturnVoidResult(NID_SEC_CERT, __pCertServiceProxy != null, E_SYSTEM, "[E_SYSTEM] Failed to get certificate proxy instance."); +} + +_X509CertificateStoreImpl::~_X509CertificateStoreImpl(void) +{ + + if (__certificateStoreCtx != 0) + { + __pCertServiceProxy->CloseCertificateStore(__certificateStoreCtx); + } +} + +result +_X509CertificateStoreImpl::GetName(String& name) const +{ + result r = __pCertServiceProxy->GetName(); + if (!IsFailed(r)) + { + name = L"CertServiceStore"; + } + + return r; +} + +result +_X509CertificateStoreImpl::SetCertificateSelector(const Tizen::Security::Cert::ICertificateSelector& selector) +{ + int count = 0; + + CertificateType certType = (const_cast< ICertificateSelector& >(selector)).GetType(); + + switch (certType) + { + case ROOT_CA: + __certType = _CERT_TYPE_ROOT_CA; + break; + + case OPERATOR_DOMAIN: + __certType = _CERT_TYPE_ROOT_DOMAIN1; + break; + + case TRUSTED_THIRD_PARTY_DOMAIN: + __certType = _CERT_TYPE_ROOT_DOMAIN3; + break; + + case USER_CERT: + __certType = _CERT_TYPE_USER_CERT; + break; + + default: + SysTryReturnResult(NID_SEC_CERT, false, E_INVALID_ARG, "Invalid certificate type."); + break; + } + + if (__certificateStoreCtx != 0) + { + __pCertServiceProxy->CloseCertificateStore(__certificateStoreCtx); + __certificateStoreCtx = 0; + } + + return __pCertServiceProxy->OpenCertificateStoreByType(static_cast< _CaCertType >(__certType), count, __certificateStoreCtx); +} + +result +_X509CertificateStoreImpl::GetCertificateCount(int& count) const +{ + if (__certificateStoreCtx != 0) + { + return __pCertServiceProxy->GetCertificateCount(__certificateStoreCtx, count); + } + + count = 0; + return E_SUCCESS; +} + + +Tizen::Security::Cert::ICertificate* +_X509CertificateStoreImpl::GetNextCertificateN(void) const +{ + result r = E_SUCCESS; + ByteBuffer certBuffer; + byte certBytes[_MAX_CERT_BUFFER_SIZE] = {0, }; + int certLen = sizeof(certBytes); + + ClearLastResult(); + + SysTryReturn(NID_SEC_CERT, __certificateStoreCtx != 0, null, E_SYSTEM, "[E_SYSTEM] Certificate list is empty, call SetCertificateSelector() function."); + + r = __pCertServiceProxy->GetNextCertificate(__certificateStoreCtx, certBytes, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Failed to get next root certificate.", GetErrorMessage(r)); + + r = certBuffer.Construct(certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, r, "[%s] Failed to allocate memory.", GetErrorMessage(r)); + + r = certBuffer.SetArray(certBytes, 0, certLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM]An unexpected system error occurred."); + + certBuffer.Flip(); + + std::unique_ptr< X509Certificate > pCert(new (std::nothrow) X509Certificate()); + SysTryReturn(NID_SEC_CERT, pCert != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pCert->Construct(certBuffer); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] X509Certificate instance is not constructed."); + + return pCert.release(); +} + + +result +_X509CertificateStoreImpl::Insert(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate) +{ + result r = E_SUCCESS; + byte* pBuffer = null; + int bufferLen = 0; + _CaCertType certType = _CERT_TYPE_NOT_BOUNDED; + + switch (certificateType) + { + case ROOT_CA: + certType = _CERT_TYPE_ROOT_CA; + break; + + case OPERATOR_DOMAIN: + certType = _CERT_TYPE_ROOT_DOMAIN1; + break; + + case TRUSTED_THIRD_PARTY_DOMAIN: + certType = _CERT_TYPE_ROOT_DOMAIN3; + break; + + case USER_CERT: + certType = _CERT_TYPE_USER_CERT; + break; + + default: + SysTryReturnResult(NID_SEC_CERT, false, E_INVALID_ARG, "Invalid certificate type."); + break; + } + + std::unique_ptr< ByteBuffer > pEncodedData(certificate.GetEncodedDataN()); + SysTryReturnResult(NID_SEC_CERT, pEncodedData != null, E_INVALID_ARG, "Failed to get encoded data on input certificate."); + + pBuffer = const_cast< byte* >(pEncodedData->GetPointer()); + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input argument passed."); + + bufferLen = pEncodedData->GetRemaining(); + SysTryReturnResult(NID_SEC_CERT, bufferLen > 0, E_INVALID_ARG, "Length value is not positive."); + + if (certType == _CERT_TYPE_USER_CERT) + { + r = __pCertServiceProxy->InsertUserCertChainPrivateKey(reinterpret_cast< char* >(pBuffer), bufferLen, null, 0); + } + else + { + r = __pCertServiceProxy->InsertCaCertificate(static_cast< int >(certType), _CERT_X509, pBuffer, bufferLen); + } + + if (r == E_FILE_ALREADY_EXIST) + { + r = E_SUCCESS; + } + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to insert root certificate.", GetErrorMessage(r)); + + r = UpdateCertStoreContext(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to open certificate store context.", GetErrorMessage(r)); + + return r; +} + +result +_X509CertificateStoreImpl::InsertPkcs12(const String& filePath, const String& password) +{ + result r = E_SUCCESS; + std::unique_ptr< char[] > pFilePath(_StringConverter::CopyToCharArrayN(filePath)); + std::unique_ptr< char[] > pPassword(_StringConverter::CopyToCharArrayN(password)); + + SysTryReturnResult(NID_SEC_CERT, filePath.GetLength() > 0, E_INVALID_ARG, "Length of file path is not positive."); + SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "File path is invalid."); + + //password can be null + r = __pCertServiceProxy->InsertPkcs12Content(pFilePath.get(), pPassword.get()); + if (r == E_FILE_ALREADY_EXIST) + { + r = E_SUCCESS; + } + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to insert pkcs 12 user certificate.", GetErrorMessage(r)); + + r = UpdateCertStoreContext(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to open certificate store context.", GetErrorMessage(r)); + return r; +} + + +result +_X509CertificateStoreImpl::Update(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& oldCert, const Tizen::Security::Cert::ICertificate& newCert) +{ + result r = E_SUCCESS; + byte* pOldBuffer = null; + byte* pNewBuffer = null; + int oldBufferLen = 0; + int newBufferLen = 0; + _CaCertType certType = _CERT_TYPE_NOT_BOUNDED; + + switch (certificateType) + { + case ROOT_CA: + certType = _CERT_TYPE_ROOT_CA; + break; + + case OPERATOR_DOMAIN: + certType = _CERT_TYPE_ROOT_DOMAIN1; + break; + + case TRUSTED_THIRD_PARTY_DOMAIN: + certType = _CERT_TYPE_ROOT_DOMAIN3; + break; + + case USER_CERT: + certType = _CERT_TYPE_USER_CERT; + break; + + default: + SysTryReturnResult(NID_SEC_CERT, false, E_INVALID_ARG, "Invalid certificate type."); + break; + } + + std::unique_ptr< ByteBuffer > pOldEncodedData(oldCert.GetEncodedDataN()); + SysTryReturnResult(NID_SEC_CERT, pOldEncodedData != null, E_INVALID_ARG, "Failed to get encoded data on old input certificate."); + + pOldBuffer = const_cast< byte* >(pOldEncodedData->GetPointer()); + SysTryReturnResult(NID_SEC_CERT, pOldBuffer != null, E_INVALID_ARG, "Invalid input argument passed."); + + oldBufferLen = pOldEncodedData->GetRemaining(); + SysTryReturnResult(NID_SEC_CERT, oldBufferLen > 0, E_INVALID_ARG, "Input old certificate length is not positive."); + + pOldEncodedData.reset(null); + + std::unique_ptr< ByteBuffer > pNewEncodedData(newCert.GetEncodedDataN()); + SysTryReturnResult(NID_SEC_CERT, pNewEncodedData != null, E_INVALID_ARG, "Failed to get encoded data on new input certificate."); + + pNewBuffer = const_cast< byte* >(pNewEncodedData->GetPointer()); + SysTryReturnResult(NID_SEC_CERT, pNewBuffer != null, E_INVALID_ARG, "Invalid input argument passed."); + + newBufferLen = pNewEncodedData->GetRemaining(); + SysTryReturnResult(NID_SEC_CERT, newBufferLen > 0, E_INVALID_ARG, "Input new certificate length is not positive."); + + if (certType == _CERT_TYPE_USER_CERT) + { + CertificateHandle certHandle = 0; + int certId = 0; + + r = _CertService::OpenCertificate(reinterpret_cast< char* >(pOldBuffer), oldBufferLen, &certHandle); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to open certificates.", GetErrorMessage(r)); + + r = _CertService::GetUserCertificateId(certHandle, certId); + + _CertService::CloseCertificate(&certHandle); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to find user certificates in store.", GetErrorMessage(r)); + + r = __pCertServiceProxy->RemoveUserCaCertificateByCertId(certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to remove/update user certificates from store.", GetErrorMessage(r)); + + r = __pCertServiceProxy->InsertUserCertChainPrivateKey(reinterpret_cast< char* >(pNewBuffer), newBufferLen, null, 0); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to install/update user certificates.", GetErrorMessage(r)); + } + else + { + r = __pCertServiceProxy->UpdateCaCertificate(static_cast< int >(certType), pOldBuffer, oldBufferLen, pNewBuffer, newBufferLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to update certificate.", GetErrorMessage(r)); + } + + r = UpdateCertStoreContext(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to open certificate store context.", GetErrorMessage(r)); + + return r; +} + + +result +_X509CertificateStoreImpl::Remove(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate) +{ + result r = E_SUCCESS; + byte* pBuffer = null; + int bufferLen = 0; + _CaCertType certType = _CERT_TYPE_NOT_BOUNDED; + + switch (certificateType) + { + case ROOT_CA: + certType = _CERT_TYPE_ROOT_CA; + break; + + case OPERATOR_DOMAIN: + certType = _CERT_TYPE_ROOT_DOMAIN1; + break; + + case TRUSTED_THIRD_PARTY_DOMAIN: + certType = _CERT_TYPE_ROOT_DOMAIN3; + break; + + case USER_CERT: + certType = _CERT_TYPE_USER_CERT; + break; + + default: + SysTryReturnResult(NID_SEC_CERT, false, E_INVALID_ARG, "Invalid certificate type."); + break; + } + + std::unique_ptr< ByteBuffer > pEncodedData(certificate.GetEncodedDataN()); + SysTryReturnResult(NID_SEC_CERT, pEncodedData != null, E_INVALID_ARG, "Failed to get encoded data on input certificate."); + + pBuffer = const_cast< byte* >(pEncodedData->GetPointer()); + SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input argument passed."); + + bufferLen = pEncodedData->GetRemaining(); + SysTryReturnResult(NID_SEC_CERT, bufferLen > 0, E_INVALID_ARG, "Input certificate length is not positive."); + + if (certType == _CERT_TYPE_USER_CERT) + { + CertificateHandle certHandle = 0; + int certId = 0; + + r = _CertService::OpenCertificate(reinterpret_cast< char* >(pBuffer), bufferLen, &certHandle); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to open certificates.", GetErrorMessage(r)); + + r = _CertService::GetUserCertificateId(certHandle, certId); + _CertService::CloseCertificate(&certHandle); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to find user certificates in store.", GetErrorMessage(r)); + + r = __pCertServiceProxy->RemoveUserCertificateByCertId(certId); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s]Failed to remove user certificates.", GetErrorMessage(r)); + } + else + { + r = __pCertServiceProxy->RemoveCaCertificate(static_cast< int >(certType), pBuffer, bufferLen); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to remove certificate.", GetErrorMessage(r)); + } + + r = UpdateCertStoreContext(); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to open certificate store context.", GetErrorMessage(r)); + + return r; + +} +_X509CertificateStoreImpl* +_X509CertificateStoreImpl::GetInstance(X509CertificateStore& x509CertificateStore) +{ + return x509CertificateStore.__pX509CertificateStoreImpl; +} + +const _X509CertificateStoreImpl* +_X509CertificateStoreImpl::GetInstance(const X509CertificateStore& x509CertificateStore) +{ + return x509CertificateStore.__pX509CertificateStoreImpl; +} + +result +_X509CertificateStoreImpl::UpdateCertStoreContext(void) +{ + result r = E_SUCCESS; + int count =0; + + if (__certificateStoreCtx != 0) + { + __pCertServiceProxy->CloseCertificateStore(__certificateStoreCtx); + r = __pCertServiceProxy->OpenCertificateStoreByType(static_cast< _CaCertType >(__certType), count, __certificateStoreCtx); + SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to open certificate store context.", GetErrorMessage(r)); + } + + return r; +} + + + +} } } // Tizen::Security::Cert diff --git a/src/security/cert/FSecCert_X509CertificateStoreImpl.h b/src/security/cert/FSecCert_X509CertificateStoreImpl.h new file mode 100755 index 0000000..e171929 --- /dev/null +++ b/src/security/cert/FSecCert_X509CertificateStoreImpl.h @@ -0,0 +1,210 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_X509CertificateStoreImpl.h + * @brief This is the header file for the %_X509CertificateStoreImpl class. + * + * This header file contains the declarations of the %_X509CertificateStoreImpl class. + */ +#ifndef _FSEC_CERT_INTERNAL_X509_CERTIFICATE_STORE_H_ +#define _FSEC_CERT_INTERNAL_X509_CERTIFICATE_STORE_H_ + +#include +#include +#include +#include +#include +#include + +namespace Tizen { namespace Security { namespace Cert +{ + +class _CertServiceProxy; +/** + * @brief This class is used for retrieving and managing certificates from a repository. + * @since 2.1 + * + * The %_X509CertificateStoreImpl class is used for retrieving and managing certificates from a repository. + */ +class _X509CertificateStoreImpl +{ + +public: + /** + * This is the default constructor for this class. + * + * @since 2.1 + */ + _X509CertificateStoreImpl(void); + + /** + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_X509CertificateStoreImpl(void); + + /** + * Gets the name of the current certificate store. + * + * @since 2.1 + * + * @return An error code + * @param[out] name The name of the certificate store + * @exception E_SUCCESS The method is successful. + */ + result GetName(Tizen::Base::String& name) const; + + /** + * Sets a list of certificates that match the specified selector. + * + * @since 2.1 + * + * @return An error code + * @param[in] selector A selector that defines a set of criterion for selecting certificates + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * @exception E_INVALID_ARG The specified @c selector is invalid. + * @exception E_UNSUPPORTED_OPERATION The type of selector is invalid. + * @endif + */ + result SetCertificateSelector(const Tizen::Security::Cert::ICertificateSelector& selector); + + /** + * Gets a count of certificates that match the specified selector. + * + * @since 2.1 + * + * @return An error code + * @param[out] count The count of certificates + * @exception E_SUCCESS The method is successful. + */ + result GetCertificateCount(int& count) const; + + /** + * Gets each certificate that matches the specified selector. + * + * @since 2.1 + * + * @return The certificates that matches the specified selector + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. + * - ByteBuffer operation failed. + */ + Tizen::Security::Cert::ICertificate* GetNextCertificateN(void) const; + + /** + * Inserts the certificate into the certificate store. + * + * @since 2.1 + * + * @return An error code + * @param[in] certificateType The type of the Certificate (ROOT_CA, OPERATOR_DOMAIN, or TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] certificate A reference to the certificate to insert + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, + * or the specified @c certificateType is invalid. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result Insert(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate); + + /** + * Inserts the user certificate of Pkcs 12 format into the certificate store. + * + * @since 2.1 + * + * @return An error code + * @param[in] filePath The file path of pkcs 12 certificate to insert. + * @param[in] password Password string to decrypt pkcs 12 certificate. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result InsertPkcs12(const Tizen::Base::String& filePath, const Tizen::Base::String& password); + + /** + * Updates the certificate in the certificate store. + * + * @since 2.1 + * + * @return An error code + * @param[in] certificateType The type of the Certificate (ROOT_CA, OPERATOR_DOMAIN, or TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] oldCert A reference to the old certificate + * @param[in] newCert A reference to the new certificate + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, + * or the specified @c certificateType is invalid. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result Update(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& oldCert, const Tizen::Security::Cert::ICertificate& newCert); + + /** + * Removes the certificate from the certificate store. + * + * @since 2.1 + * + * @return An error code + * @param[in] certificateType The type of the Certificate (ROOT_CA, OPERATOR_DOMAIN, TRUSTED_THIRD_PARTY_DOMAIN) + * @param[in] certificate A reference to the certificate to remove + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified @c certificate or the certificate data is invalid, + * or the specified @c certificateType is invalid. + * @exception E_OBJ_NOT_FOUND The certificate is not found. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result Remove(CertificateType certificateType, const Tizen::Security::Cert::ICertificate& certificate); + + static _X509CertificateStoreImpl* GetInstance(X509CertificateStore& x509CertificateStore); + static const _X509CertificateStoreImpl* GetInstance(const X509CertificateStore& x509CertificateStore); + +private: + result UpdateCertStoreContext(void); + _X509CertificateStoreImpl(const _X509CertificateStoreImpl& rhs); + _X509CertificateStoreImpl& operator =(const _X509CertificateStoreImpl& rhs); + +private: + int __certType; + int __certificateStoreCtx; + _CertServiceProxy* __pCertServiceProxy; + friend class X509CertificateStore; +}; //X509CertificateStoreImpl + +} } } //Tizen::Security::Cert + +#endif //_FSEC_CERT_INTERNAL_X509_CERTIFICATE_STORE_H_ diff --git a/src/security/crypto/FSecCryptoAesCipher.cpp b/src/security/crypto/FSecCryptoAesCipher.cpp new file mode 100644 index 0000000..5ed4d51 --- /dev/null +++ b/src/security/crypto/FSecCryptoAesCipher.cpp @@ -0,0 +1,314 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoAesCipher.cpp + * @brief This file contains the declaration of Tizen::Security::Crypto::AesCipher. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_SymmetricCipher.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _TRANSFORMATION_STRING_PART_1_LENGTH = 3; +static const int _TRANSFORMATION_STRING_PART_2_BEGIN = 4; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH = 3; +static const int _TRANSFORMATION_STRING_PART_3_BEGIN = 8; +static const int _TRANSFORMATION_STRING_PART_3_LENGTH_A = 9; +static const int _TRANSFORMATION_STRING_PART_3_LENGTH_B = 12; + +AesCipher::AesCipher(void) + : __pSymmetricCipher(null) // Default is AES/CBC/128 + , __pCipherAlgorithm(null) + , __pAesCipherImpl(null) +{ +} + +AesCipher::~AesCipher(void) +{ + delete __pSymmetricCipher; +} + +result +AesCipher::Construct(const Tizen::Base::String& transformation, CipherOperation opMode) +{ + result r = E_SUCCESS; + bool padVal = false; + String cipherMode = null; + String padding = null; + String keyBit = null; + + SysAssertf(__pSymmetricCipher == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pSymmetricCipher = new (std::nothrow) _SymmetricCipher(); + SysTryReturn(NID_SEC_CRYPTO, __pSymmetricCipher != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + SysTryCatch(NID_SEC_CRYPTO, transformation.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The transformation string should be valid."); + + // Setting the key size, cipher mode and padding for the Aes Construct + r = transformation.SubString(0, _TRANSFORMATION_STRING_PART_1_LENGTH, cipherMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (cipherMode.CompareTo(L"CBC") == E_SUCCESS) + { + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH, keyBit); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (keyBit.CompareTo(L"128") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_aes_128_cbc(); + } + else if (keyBit.CompareTo(L"192") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_aes_192_cbc(); + } + else if (keyBit.CompareTo(L"256") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_aes_256_cbc(); + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested key length is not supported."); + goto CATCH; + } + } + else if (cipherMode.CompareTo(L"ECB") == E_SUCCESS) + { + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH, keyBit); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (keyBit.CompareTo(L"128") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_aes_128_ecb(); + } + else if (keyBit.CompareTo(L"192") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_aes_192_ecb(); + } + else if (keyBit.CompareTo(L"256") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_aes_256_ecb(); + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested key length is not supported."); + goto CATCH; + } + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested mode is not supported."); + goto CATCH; + } + + r = transformation.SubString(_TRANSFORMATION_STRING_PART_3_BEGIN, _TRANSFORMATION_STRING_PART_3_LENGTH_A, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"NOPADDING") == E_SUCCESS) + { + padVal = false; + } + else + { + r = transformation.SubString(_TRANSFORMATION_STRING_PART_3_BEGIN, _TRANSFORMATION_STRING_PART_3_LENGTH_B, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"PKCS7PADDING") == E_SUCCESS) + { + padVal = true; + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested padding is not supported."); + goto CATCH; + } + } + + // sets the Transformation String + r = __pSymmetricCipher->SetTransformation(__pCipherAlgorithm, padVal); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set transformation operation.", GetErrorMessage(r)); + + SysTryCatch(NID_SEC_CRYPTO, opMode == CIPHER_ENCRYPT || opMode == CIPHER_DECRYPT || opMode == CIPHER_WRAP || opMode == CIPHER_UNWRAP, + r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The opMode should be valid."); + + // sets the CipherOpearation + r = __pSymmetricCipher->SetCipherOperation(opMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] The cipher operation request should be valid.", GetErrorMessage(r)); + +CATCH: + if (IsFailed(r)) + { + delete __pSymmetricCipher; + __pSymmetricCipher = null; + } + return r; +} + +result +AesCipher::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int keyLen = 0; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + std::unique_ptr pKey(key.GetEncodedN()); + SysTryReturnResult(NID_SEC_CRYPTO, pKey != null, E_INVALID_ARG, "Input key data should be valid."); + + keyLen = static_cast< int >(pKey->GetRemaining()); + SysTryReturnResult(NID_SEC_CRYPTO, keyLen == __pCipherAlgorithm->key_len, E_INVALID_ARG, "Input key length should be equal to algorithm key length."); + + r = __pSymmetricCipher->SetKey(key); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + + return r; +} + +result +AesCipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->SetInitialVector(initialVector); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set initial vector operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +AesCipher::EncryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do encrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +AesCipher::DecryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do decrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +result +AesCipher::Initialize(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->Initialize(); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do initialize operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +AesCipher::UpdateN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->UpdateN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do update operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +AesCipher::FinalizeN(void) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->FinalizeN(); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do finalize operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +AesCipher::WrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->WrapN(secretKey); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do wrap operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +AesCipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->UnwrapN(wrappedKey); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do unwrap operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoCastCipher.cpp b/src/security/crypto/FSecCryptoCastCipher.cpp new file mode 100644 index 0000000..3fb9e9f --- /dev/null +++ b/src/security/crypto/FSecCryptoCastCipher.cpp @@ -0,0 +1,255 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoCastCipher.cpp + * @brief This file contains the implementation of Tizen::Security::Crypto::CastCipher. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_SymmetricCipher.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _TRANSFORMATION_STRING_PART_1_LENGTH = 3; +static const int _TRANSFORMATION_STRING_PART_2_BEGIN = 4; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_A = 9; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_B = 12; + +CastCipher::CastCipher(void) + : __pSymmetricCipher(null) // Default is CAST/CBC/128 + , __pCipherAlgorithm(null) + , __pCastCipherImpl(null) +{ +} + +CastCipher::~CastCipher(void) +{ + delete __pSymmetricCipher; +} + +result +CastCipher::Construct(const Tizen::Base::String& transformation, CipherOperation opMode) +{ + result r = E_SUCCESS; + bool padVal = false; + String cipherMode = null; + String padding = null; + + SysAssertf(__pSymmetricCipher == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pSymmetricCipher = new (std::nothrow) _SymmetricCipher(); + SysTryReturn(NID_SEC_CRYPTO, __pSymmetricCipher != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + SysTryCatch(NID_SEC_CRYPTO, transformation.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The transformation string should be valid."); + + // Setting the key size, cipher mode and padding for the Cast Construct + r = transformation.SubString(0, _TRANSFORMATION_STRING_PART_1_LENGTH, cipherMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (cipherMode.CompareTo(L"128") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_cast5_cbc(); + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested key length is not supported."); + goto CATCH; + } + + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_A, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"NOPADDING") == E_SUCCESS) + { + padVal = false; + } + else + { + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_B, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"PKCS7PADDING") == E_SUCCESS) + { + padVal = true; + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested padding is not supported."); + goto CATCH; + } + } + + // sets the transformation + r = __pSymmetricCipher->SetTransformation(__pCipherAlgorithm, padVal); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set transformation operation.", GetErrorMessage(r)); + + SysTryCatch(NID_SEC_CRYPTO, opMode == CIPHER_ENCRYPT || opMode == CIPHER_DECRYPT, + r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The opMode should be valid."); + + // sets the SetCipherOpearation + r = __pSymmetricCipher->SetCipherOperation(opMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] The cipher operation request should be valid.", GetErrorMessage(r)); + +CATCH: + if (IsFailed(r)) + { + delete __pSymmetricCipher; + __pSymmetricCipher = null; + } + return r; +} + +result +CastCipher::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int keyLen = 0; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + std::unique_ptr pKey(key.GetEncodedN()); + SysTryReturnResult(NID_SEC_CRYPTO, pKey != null, E_INVALID_ARG, "Input key data should be valid."); + + keyLen = static_cast< int >(pKey->GetRemaining()); + SysTryReturnResult(NID_SEC_CRYPTO, keyLen == __pCipherAlgorithm->key_len, E_INVALID_ARG, "Input key length should be equal to algorithm key length."); + + r = __pSymmetricCipher->SetKey(key); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + + return r; +} + +result +CastCipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->SetInitialVector(initialVector); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set initial vector operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +CastCipher::EncryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do encrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +CastCipher::DecryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do decrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +result +CastCipher::Initialize(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->Initialize(); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do initialize operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +CastCipher::UpdateN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->UpdateN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do update operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +CastCipher::FinalizeN(void) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->FinalizeN(); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do finalize operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +CastCipher::WrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +ByteBuffer* +CastCipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoDesCipher.cpp b/src/security/crypto/FSecCryptoDesCipher.cpp new file mode 100644 index 0000000..6514771 --- /dev/null +++ b/src/security/crypto/FSecCryptoDesCipher.cpp @@ -0,0 +1,261 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoDesCipher.cpp + * @brief This file contains the declaration of Tizen::Security::Crypto::DesCipher. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_SymmetricCipher.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _TRANSFORMATION_STRING_PART_1_LENGTH = 3; +static const int _TRANSFORMATION_STRING_PART_2_BEGIN = 4; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_A = 9; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_B = 12; + +DesCipher::DesCipher(void) + : __pSymmetricCipher(null) // Default is DES/CBC/128 + , __pCipherAlgorithm(null) + , __pDesCipherImpl(null) +{ +} + +DesCipher::~DesCipher(void) +{ + delete __pSymmetricCipher; +} + +result +DesCipher::Construct(const Tizen::Base::String& transformation, CipherOperation opMode) +{ + result r = E_SUCCESS; + bool padVal = false; + String cipherMode = null; + String padding = null; + + SysAssertf(__pSymmetricCipher == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pSymmetricCipher = new (std::nothrow) _SymmetricCipher(); + SysTryReturn(NID_SEC_CRYPTO, __pSymmetricCipher != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + SysTryCatch(NID_SEC_CRYPTO, transformation.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The transformation string should be valid."); + + // Setting the key size, cipher mode and padding for the Des Construct + r = transformation.SubString(0, _TRANSFORMATION_STRING_PART_1_LENGTH, cipherMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (cipherMode.CompareTo(L"CBC") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_des_cbc(); + } + else if (cipherMode.CompareTo(L"ECB") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_des_ecb(); + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested mode is not supported."); + goto CATCH; + } + + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_A, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"NOPADDING") == E_SUCCESS) + { + padVal = false; + } + else + { + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_B, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"PKCS7PADDING") == E_SUCCESS) + { + padVal = true; + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested padding is not supported."); + goto CATCH; + } + } + + // sets the transformation + r = __pSymmetricCipher->SetTransformation(__pCipherAlgorithm, padVal); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set transformation operation.", GetErrorMessage(r)); + + SysTryCatch(NID_SEC_CRYPTO, opMode == CIPHER_ENCRYPT || opMode == CIPHER_DECRYPT, + r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The opMode should be valid."); + + // sets the SetCipherOpearation + r = __pSymmetricCipher->SetCipherOperation(opMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] The cipher operation request should be valid.", GetErrorMessage(r)); + +CATCH: + if (IsFailed(r)) + { + delete __pSymmetricCipher; + __pSymmetricCipher = null; + } + return r; +} + +result +DesCipher::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int keyLen = 0; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + std::unique_ptr pKey(key.GetEncodedN()); + SysTryReturnResult(NID_SEC_CRYPTO, pKey != null, E_INVALID_ARG, "Input key data should be valid."); + + keyLen = static_cast< int >(pKey->GetRemaining()); + SysTryReturnResult(NID_SEC_CRYPTO, keyLen == __pCipherAlgorithm->key_len, E_INVALID_ARG, "Input key length value should be equal to algorithm key length."); + + r = __pSymmetricCipher->SetKey(key); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + + return r; +} + +result +DesCipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->SetInitialVector(initialVector); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set initial vector operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +DesCipher::EncryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do encrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +DesCipher::DecryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do decrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +result +DesCipher::Initialize(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->Initialize(); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do initialize operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +DesCipher::UpdateN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->UpdateN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do update operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +DesCipher::FinalizeN(void) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->FinalizeN(); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do finalize operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +DesCipher::WrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +ByteBuffer* +DesCipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoDesEdeCipher.cpp b/src/security/crypto/FSecCryptoDesEdeCipher.cpp new file mode 100644 index 0000000..ecd229c --- /dev/null +++ b/src/security/crypto/FSecCryptoDesEdeCipher.cpp @@ -0,0 +1,259 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoDesEdeCipher.cpp + * @brief This file contains the declaration of Tizen::Security::Crypto::DesEdeCipher. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_SymmetricCipher.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _TRANSFORMATION_STRING_PART_1_LENGTH = 3; +static const int _TRANSFORMATION_STRING_PART_2_BEGIN = 4; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_A = 9; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_B = 12; + +DesEdeCipher::DesEdeCipher(void) + : __pSymmetricCipher(null) // Default is 3DES/CBC/128 + , __pCipherAlgorithm(null) + , __pDesEdeCipherImpl(null) +{ +} + +DesEdeCipher::~DesEdeCipher(void) +{ + delete __pSymmetricCipher; +} + +result +DesEdeCipher::Construct(const Tizen::Base::String& transformation, CipherOperation opMode) +{ + result r = E_SUCCESS; + bool padVal = false; + String cipherMode = null; + String padding = null; + + SysAssertf(__pSymmetricCipher == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pSymmetricCipher = new (std::nothrow) _SymmetricCipher(); + SysTryReturn(NID_SEC_CRYPTO, __pSymmetricCipher != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + SysTryCatch(NID_SEC_CRYPTO, transformation.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The transformation string should be valid."); + + // Setting the key size, cipher mode and padding for the DesEde Construct + r = transformation.SubString(0, _TRANSFORMATION_STRING_PART_1_LENGTH, cipherMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (cipherMode.CompareTo(L"CBC") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_des_ede3_cbc(); + } + else if (cipherMode.CompareTo(L"ECB") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_des_ede3(); + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested mode is not supported."); + goto CATCH; + } + + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_A, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"NOPADDING") == E_SUCCESS) + { + padVal = false; + } + else + { + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_B, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"PKCS7PADDING") == E_SUCCESS) + { + padVal = true; + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested padding is not supported."); + goto CATCH; + } + } + + // sets the transformation + r = __pSymmetricCipher->SetTransformation(__pCipherAlgorithm, padVal); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set transformation operation.", GetErrorMessage(r)); + + SysTryCatch(NID_SEC_CRYPTO, opMode == CIPHER_ENCRYPT || opMode == CIPHER_DECRYPT, + r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The opMode should be valid."); + + // sets the SetCipherOpearation + r = __pSymmetricCipher->SetCipherOperation(opMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] The cipher operation request should be valid.", GetErrorMessage(r)); + +CATCH: + if (IsFailed(r)) + { + delete __pSymmetricCipher; + __pSymmetricCipher = null; + } + return r; +} + +result +DesEdeCipher::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int keyLen = 0; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + std::unique_ptr pKey(key.GetEncodedN()); + SysTryReturnResult(NID_SEC_CRYPTO, pKey != null, E_INVALID_ARG, "Input key data should be valid."); + + keyLen = static_cast< int >(pKey->GetRemaining()); + SysTryReturnResult(NID_SEC_CRYPTO, keyLen == __pCipherAlgorithm->key_len, E_INVALID_ARG, "Input key length should be equal to algorithm key length."); + + r = __pSymmetricCipher->SetKey(key); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + + return r; +} + +result +DesEdeCipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->SetInitialVector(initialVector); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set initial vector operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +DesEdeCipher::EncryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do encrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +DesEdeCipher::DecryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do decrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +result +DesEdeCipher::Initialize(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->Initialize(); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do initialize operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +DesEdeCipher::UpdateN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->UpdateN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do update operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +DesEdeCipher::FinalizeN(void) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->FinalizeN(); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do finalize operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +DesEdeCipher::WrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +ByteBuffer* +DesEdeCipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoDhKeyExchange.cpp b/src/security/crypto/FSecCryptoDhKeyExchange.cpp new file mode 100644 index 0000000..5a73854 --- /dev/null +++ b/src/security/crypto/FSecCryptoDhKeyExchange.cpp @@ -0,0 +1,155 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/** + * @file FSecCryptoDhKeyExchange.cpp + * @brief This file contains the implementation of Tizen::Security::Crypto::DhKeyExchange. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Security; + + +namespace Tizen { namespace Security { namespace Crypto +{ +static const int _BITS_IN_BYTE = 8; + +DhKeyExchange::DhKeyExchange(void) + : __pParamsP(null) + , __pParamsG(null) + , __pDhKeyExchangeImpl(null) +{ + +} + +DhKeyExchange::~DhKeyExchange(void) +{ + delete __pParamsP; + delete __pParamsG; +} + +result +DhKeyExchange::Construct(const Tizen::Security::IKeyParameters& keyParameters) +{ + result r = E_SUCCESS; + DhKeyParameters* pDhParams = null; + + SysAssertf(__pParamsP == null && __pParamsG == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + pDhParams = const_cast< DhKeyParameters* >(dynamic_cast< const DhKeyParameters* >(&keyParameters)); + SysTryReturn(NID_SEC_CRYPTO, pDhParams != null, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The dh key parameters value should be valid."); + + //Retreive the value of the parameter 'p' from the instance + __pParamsP = pDhParams->GetParameterValueN(KEY_PARAMETER_DH_P); + SysTryReturn(NID_SEC_CRYPTO, __pParamsP != null, GetLastResult(), GetLastResult(), "[%s] Failed to get prime number", GetErrorMessage(GetLastResult())); + + //Retreive the value of the parameter 'g' from the instance + __pParamsG = pDhParams->GetParameterValueN(KEY_PARAMETER_DH_G); + SysTryCatch(NID_SEC_CRYPTO, __pParamsG != null, r = GetLastResult(), GetLastResult(), "[%s] Failed to get generator number", GetErrorMessage(GetLastResult())); + +CATCH: + if (IsFailed(r)) + { + delete __pParamsP; + __pParamsP = null; + } + return r; +} + +ByteBuffer* +DhKeyExchange::GenerateSecretN(Tizen::Security::IPrivateKey& privateKey, Tizen::Security::IPublicKey& publicKey) +{ + result r = E_SUCCESS; + int outLen = 0; + int sizeParams = 0; + int sizePreMaster = 0; + DH* pDhStx = NULL; + BIGNUM* pDhPuKey = null; + std::unique_ptr pOutput(null); + + ClearLastResult(); + + SysAssertf(__pParamsP != null && __pParamsG != null, "Not yet constructed. Construct() should be called before use."); + + std::unique_ptr pPrivateComponent(privateKey.GetEncodedN()); + SysTryReturn(NID_SEC_CRYPTO, pPrivateComponent != null, null, GetLastResult(), "[%s] Failed to fill private key buffer.", GetErrorMessage(GetLastResult())); + + std::unique_ptr pPublicComponent(publicKey.GetEncodedN()); + SysTryReturn(NID_SEC_CRYPTO, pPublicComponent != null, null, GetLastResult(), "[%s] Failed to fill public key buffer.", GetErrorMessage(GetLastResult())); + + sizeParams = pPrivateComponent->GetRemaining(); + sizePreMaster = __pParamsP->GetRemaining(); + + std::unique_ptr pDhPreMasterSecret(new (std::nothrow) byte[sizePreMaster]); + SysTryReturn(NID_SEC_CRYPTO, pDhPreMasterSecret != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pDhStx = DH_new(); + SysTryCatch(NID_SEC_CRYPTO, pDhStx != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pDhStx->p = BN_bin2bn(__pParamsP->GetPointer(), __pParamsP->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pDhStx->p != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pDhStx->g = BN_bin2bn(__pParamsG->GetPointer(), __pParamsG->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pDhStx->g != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pDhStx->length = sizeParams * _BITS_IN_BYTE; + + pDhStx->priv_key = BN_bin2bn(pPrivateComponent->GetPointer(), pPrivateComponent->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pDhStx->priv_key != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pDhPuKey = BN_bin2bn(pPublicComponent->GetPointer(), pPublicComponent->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pDhPuKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + outLen = DH_compute_key(pDhPreMasterSecret.get(), pDhPuKey, pDhStx); + SysTryCatch(NID_SEC_CRYPTO, pDhPreMasterSecret != null && outLen != -1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput = std::unique_ptr(new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pDhPreMasterSecret.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + if (IsFailed(r)) + { + pOutput.reset(null); + } + + if (pDhStx != null) + { + DH_free(pDhStx); + } + + return pOutput.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoKeaKeyExchange.cpp b/src/security/crypto/FSecCryptoKeaKeyExchange.cpp new file mode 100644 index 0000000..5c9f362 --- /dev/null +++ b/src/security/crypto/FSecCryptoKeaKeyExchange.cpp @@ -0,0 +1,196 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoKeaKeyExchange.cpp + * @brief This file contains the implementation of Tizen::Security::Crypto::KeaKeyExchange. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_KeaCore.h" +#include "FSecCrypto_SkipJackCore.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + + +namespace Tizen { namespace Security { namespace Crypto +{ +static const int _BITS_IN_BYTE = 8; + +KeaKeyExchange::KeaKeyExchange(void) + : __pParamsP(null) + , __pParamsG(null) + , __pPrivateComponent(null) + , __pPublicComponent(null) + , __pKeaKeyExchangeImpl(null) +{ + +} + +KeaKeyExchange::~KeaKeyExchange(void) +{ + delete __pParamsP; + delete __pParamsG; + delete __pPrivateComponent; + delete __pPublicComponent; +} + +/** + * DoPhase computes the phase wise shared secret, It requires 1st party private key and 2nd Party public key to generate shared secret. + * Do phase is used in KEA like algorithm and for multiparty key exchange.*/ +result +KeaKeyExchange::DoPhase(Tizen::Security::IPrivateKey& privateKey, Tizen::Security::IPublicKey& publicKey) +{ + result r = E_SUCCESS; + + SysTryReturn(NID_SEC_CRYPTO, &privateKey != null && &publicKey != null, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input privatekey and publickey values should be valid."); + + delete __pPublicComponent; + + __pPublicComponent = publicKey.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, __pPublicComponent != null, GetLastResult(), GetLastResult(), "[%s] Failed to get public key", GetErrorMessage(GetLastResult())); + + delete __pPrivateComponent; + + __pPrivateComponent = privateKey.GetEncodedN(); + SysTryCatch(NID_SEC_CRYPTO, __pPrivateComponent != null, r = GetLastResult(), GetLastResult(), "[%s] Failed to get private key", GetErrorMessage(GetLastResult())); + +CATCH: + if (IsFailed(r)) + { + delete __pPublicComponent; + __pPublicComponent = null; + } + return r; +} + +result +KeaKeyExchange::Construct(const Tizen::Security::IKeyParameters& keyParameters) +{ + result r = E_SUCCESS; + KeaKeyParameters* pKeaParams = null; + + SysAssertf(__pParamsP == null && __pParamsG == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + pKeaParams = const_cast< KeaKeyParameters* >(dynamic_cast< const KeaKeyParameters* >(&keyParameters)); + SysTryReturn(NID_SEC_CRYPTO, pKeaParams != null, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The kea key parameters value should be valid."); + + __pParamsP = pKeaParams->GetParameterValueN(KEY_PARAMETER_KEA_P); + SysTryReturn(NID_SEC_CRYPTO, __pParamsP != null, GetLastResult(), GetLastResult(), "[%s] Failed to get prime number", GetErrorMessage(GetLastResult())); + + __pParamsG = pKeaParams->GetParameterValueN(KEY_PARAMETER_KEA_G); + SysTryCatch(NID_SEC_CRYPTO, __pParamsG != null, r = GetLastResult(), GetLastResult(), "[%s] Failed to get generator number", GetErrorMessage(GetLastResult())); + +CATCH: + if (IsFailed(r)) + { + delete __pParamsP; + __pParamsP = null; + } + return r; +} + +ByteBuffer* +KeaKeyExchange::GenerateSecretN(Tizen::Security::IPrivateKey& privateKey, Tizen::Security::IPublicKey& publicKey) +{ + result r = E_SUCCESS; + int outLen = _SKIPJACK_KEY_LENGTH; + int sizeParams = 0; + byte* pKeaPreMasterSecretValue = null; + std::unique_ptr pKeaPreMasterSecret(null); + std::unique_ptr pOutput(null); + Kea* pKea = null; + BIGNUM* pKeaPuKey1 = null; + BIGNUM* pKeaPuKey2 = null; + + ClearLastResult(); + + SysAssertf(__pParamsP != null && __pParamsG != null && __pPrivateComponent != null && __pPublicComponent != null, + "Not yet constructed. Construct() and DoPhase() should be called before use."); + + std::unique_ptr pPrivateComponent(privateKey.GetEncodedN()); + SysTryReturn(NID_SEC_CRYPTO, pPrivateComponent != null, null, GetLastResult(), "[%s] Failed to fill private key buffer.", GetErrorMessage(GetLastResult())); + + std::unique_ptr pPublicComponent(publicKey.GetEncodedN()); + SysTryReturn(NID_SEC_CRYPTO, pPublicComponent != null, null, GetLastResult(), "[%s] Failed to fill public key buffer.", GetErrorMessage(GetLastResult())); + + sizeParams = pPrivateComponent->GetRemaining(); + + pKea = _KeaCore::CreateKeaN(); + SysTryCatch(NID_SEC_CRYPTO, pKea != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pKea->pP = BN_bin2bn(__pParamsP->GetPointer(), __pParamsP->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pKea->pP != null, r = E_SYSTEM, E_SYSTEM, "E_SYSTEM] An unexpected system error occurred."); + + pKea->pG = BN_bin2bn(__pParamsG->GetPointer(), __pParamsG->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pKea->pG != null, r = E_SYSTEM, E_SYSTEM, "E_SYSTEM] An unexpected system error occurred."); + + pKea->length = sizeParams * _BITS_IN_BYTE; + + pKea->pPrivKey1 = BN_bin2bn(pPrivateComponent->GetPointer(), pPrivateComponent->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pKea->pPrivKey1 != null, r = E_SYSTEM, E_SYSTEM, "E_SYSTEM] An unexpected system error occurred."); + + pKea->pPrivKey2 = BN_bin2bn(__pPrivateComponent->GetPointer(), __pPrivateComponent->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pKea->pPrivKey2 != null, r = E_SYSTEM, E_SYSTEM, "E_SYSTEM] An unexpected system error occurred."); + + pKeaPuKey1 = BN_bin2bn(pPublicComponent->GetPointer(), pPublicComponent->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pKeaPuKey1 != null, r = E_SYSTEM, E_SYSTEM, "E_SYSTEM] An unexpected system error occurred."); + + pKeaPuKey2 = BN_bin2bn(__pPublicComponent->GetPointer(), __pPublicComponent->GetRemaining(), NULL); + SysTryCatch(NID_SEC_CRYPTO, pKeaPuKey2 != null, r = E_SYSTEM, E_SYSTEM, "E_SYSTEM] An unexpected system error occurred."); + + r = _KeaCore::ComputeKeaKey(&pKeaPreMasterSecretValue, pKeaPuKey1, pKeaPuKey2, *pKea); + pKeaPreMasterSecret = std::unique_ptr (pKeaPreMasterSecretValue); + + SysTryCatch(NID_SEC_CRYPTO, pKeaPreMasterSecret != null && !IsFailed(r), , r, "[%s] Failed to call kea compute key.", GetErrorMessage(r)); + + pOutput = std::unique_ptr (new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pKeaPreMasterSecret.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + if (IsFailed(r)) + { + pOutput.reset(null);; + } + + if (pKea) + { + _KeaCore::DeleteKea(pKea); + } + + return pOutput.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoMd5Hash.cpp b/src/security/crypto/FSecCryptoMd5Hash.cpp new file mode 100644 index 0000000..a06938f --- /dev/null +++ b/src/security/crypto/FSecCryptoMd5Hash.cpp @@ -0,0 +1,185 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoMd5Hash.cpp + * @brief This file contains the implementation of Md5Hash class. + * + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +Md5Hash::Md5Hash(void) + : __pEvpMdCtx(null) + , __pMd5HashImpl(null) +{ +} + +Md5Hash::~Md5Hash(void) +{ + delete __pEvpMdCtx; +} + +result +Md5Hash::SetAlgorithm(const Tizen::Base::String& algorithm) +{ + // Unsupported in Md5Hash + return E_UNSUPPORTED_ALGORITHM; +} + +ByteBuffer* +Md5Hash::GetHashN(const ByteBuffer& input) const +{ + result r = E_SUCCESS; + int dataLen = 0; + unsigned int outLen = 0; + byte* pData = null; + byte hashOut[MD5_DIGEST_LENGTH] = {'\0'}; + + ClearLastResult(); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be positive."); + + //this function returns the MD5 hash hashOut + EVP_Digest(pData, dataLen, hashOut, &outLen, EVP_md5(), null); + SysTryReturn(NID_SEC_CRYPTO, outLen > 0, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //stores the hash in bytebuffer + std::unique_ptr pOutput(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(hashOut, 0, outLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + + return pOutput.release(); +} + +result +Md5Hash::Initialize(void) +{ + result r = E_SUCCESS; + int ret = 0; + + SysAssertf(__pEvpMdCtx == null, "Already constructed. Calling Initialize() twice or more on a same instance is not allowed for this class."); + + //MD5 init is called + __pEvpMdCtx = new (std::nothrow) EVP_MD_CTX(); + SysTryReturn(NID_SEC_CRYPTO, __pEvpMdCtx != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + ret = EVP_DigestInit(__pEvpMdCtx, EVP_md5()); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + +CATCH: + + if (IsFailed(r)) + { + delete __pEvpMdCtx; + __pEvpMdCtx = null; + } + return r; +} + +result +Md5Hash::Update(const ByteBuffer& input) +{ + result r = E_SUCCESS; + int ret = 0; + int dataLen = 0; + byte* pData = null; + + SysAssertf(__pEvpMdCtx != null, "Not yet constructed. Initialize() should be called before use."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be positive."); + + //MD5_update is called + ret = EVP_DigestUpdate(__pEvpMdCtx, pData, dataLen); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return r; +} + +ByteBuffer* +Md5Hash::FinalizeN(void) +{ + result r = E_SUCCESS; + int ret = 0; + int outLen = MD5_DIGEST_LENGTH; + std::unique_ptr pOutput(null); + + ClearLastResult(); + + SysAssertf(__pEvpMdCtx != null, "Not yet constructed. Initialize() should be called before use."); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[outLen]); + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + //MD5_final is called and is stored in pTempBuf + ret = EVP_DigestFinal(__pEvpMdCtx, pTempBuf.get(), null); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //hash is stored in bytebuffer + pOutput = std::unique_ptr(new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory"); + + r = pOutput->SetArray(pTempBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + EVP_MD_CTX_cleanup(__pEvpMdCtx); + + if (IsFailed(r)) + { + pOutput.reset(null); + } + + delete __pEvpMdCtx; + __pEvpMdCtx = null; + + return pOutput.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoMd5Hmac.cpp b/src/security/crypto/FSecCryptoMd5Hmac.cpp new file mode 100644 index 0000000..4db7991 --- /dev/null +++ b/src/security/crypto/FSecCryptoMd5Hmac.cpp @@ -0,0 +1,228 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoMd5Hmac.cpp + * @brief This file contains the implementation of Md5Hmac class. + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ +static const int _MD5_DIGEST_LENGTH = 16; + +Md5Hmac::Md5Hmac(void) + : __pMd5HmacCtx(null) + , __pMd5HmacImpl(null) +{ +} + +Md5Hmac::~Md5Hmac(void) +{ + delete __pMd5HmacCtx; +} + +result +Md5Hmac::SetAlgorithm(const Tizen::Base::String& algorithm) +{ + // Unsupported in Md5Hmac + return E_UNSUPPORTED_ALGORITHM; +} + +result +Md5Hmac::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int dataLen = 0; + ByteBuffer* pBuffer = null; + + // convert the ISecretKey to ByteBuffer + pBuffer = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Failed to fill key buffer.", GetErrorMessage(GetLastResult())); + + //converts into bytebuffer + dataLen = static_cast< int >(pBuffer->GetRemaining()); + SysTryCatch(NID_SEC_CRYPTO, dataLen > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Key length should be positive."); + + r = __keyBytes.Construct(*pBuffer); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Input key buffer should be valid.", GetErrorMessage(r)); + +CATCH: + delete pBuffer; + return r; +} + +ByteBuffer* +Md5Hmac::GetHmacN(const ByteBuffer& input) const +{ + result r = E_SUCCESS; + int dataLen = 0; + int keyLen = 0; + unsigned int mdLen = 0; + byte* pData = null; + byte* pKey = null; + + ClearLastResult(); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + std::unique_ptr pMd(new (std::nothrow) byte[_MD5_DIGEST_LENGTH]); + SysTryReturn(NID_SEC_CRYPTO, pMd != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pMd.get(), 0, _MD5_DIGEST_LENGTH); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key value should be valid."); + + keyLen = __keyBytes.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + //gets HMAC of the input data + HMAC(EVP_md5(), pKey, keyLen, pData, dataLen, pMd.get(), &mdLen); + SysTryReturn(NID_SEC_CRYPTO, mdLen != 0, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //stores the HMAC output in bytebuffer + std::unique_ptr pOutput(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to create memory."); + + r = pOutput->Construct(mdLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_OUT_OF_MEMORY, "[E_OUT_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pMd.get(), 0, mdLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + + return pOutput.release(); +} + +result +Md5Hmac::Initialize(void) +{ + result r = E_SUCCESS; + int ret = 0; + int keyLen = 0; + byte* pKey = null; + + SysAssertf(__pMd5HmacCtx == null, "Already constructed. Calling Initialize() twice or more on a same instance is not allowed for this class."); + + __pMd5HmacCtx = new (std::nothrow) HMAC_CTX(); + SysTryReturn(NID_SEC_CRYPTO, __pMd5HmacCtx != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryCatch(NID_SEC_CRYPTO, pKey != null, r = E_KEY_NOT_FOUND, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] The key value should be valid."); + + keyLen = __keyBytes.GetRemaining(); + SysTryCatch(NID_SEC_CRYPTO, keyLen, r = E_KEY_NOT_FOUND, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] The key length should be positive."); + + //calls the HMAC_init function + ret = HMAC_Init(__pMd5HmacCtx, static_cast< byte* >(pKey), keyLen, EVP_md5()); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + +CATCH: + + if (IsFailed(r)) + { + delete __pMd5HmacCtx; + __pMd5HmacCtx = null; + } + return r; +} + +result +Md5Hmac::Update(const Tizen::Base::ByteBuffer& input) +{ + result r = E_SUCCESS; + int ret = 0; + int dataLen = 0; + byte* pData = null; + + SysAssertf(__pMd5HmacCtx != null, "Not yet constructed. Initialize() should be called before use."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be valid."); + + //calls the HMAC_update function + ret = HMAC_Update(__pMd5HmacCtx, const_cast< byte* >(pData), static_cast< unsigned long >(dataLen)); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return r; +} + +Tizen::Base::ByteBuffer* +Md5Hmac::FinalizeN(void) +{ + result r = E_SUCCESS; + int ret = 0; + unsigned int outLen = _MD5_DIGEST_LENGTH; + std::unique_ptr pOutput(null); + + ClearLastResult(); + + SysAssertf(__pMd5HmacCtx != null, "Not yet constructed. Initialize() should be called before use."); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[outLen]); + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + //call the HMAC_final function and stores output in pTempBuf + ret = HMAC_Final(__pMd5HmacCtx, pTempBuf.get(), &outLen); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //write HMAC output in bytebuffer + pOutput = std::unique_ptr(new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to create memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pTempBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + HMAC_CTX_cleanup(__pMd5HmacCtx); + + if (IsFailed(r)) + { + pOutput.reset(null); + } + + delete __pMd5HmacCtx; + __pMd5HmacCtx = null; + + return pOutput.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoRc2Cipher.cpp b/src/security/crypto/FSecCryptoRc2Cipher.cpp new file mode 100644 index 0000000..43d140e --- /dev/null +++ b/src/security/crypto/FSecCryptoRc2Cipher.cpp @@ -0,0 +1,261 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoRc2Cipher.cpp + * @brief This file contains the implementation of Tizen::Security::Crypto::Rc2Cipher. + */ +#include +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_SymmetricCipher.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _TRANSFORMATION_STRING_PART_1_LENGTH = 3; +static const int _TRANSFORMATION_STRING_PART_2_BEGIN = 4; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_A = 9; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_B = 12; + +Rc2Cipher::Rc2Cipher(void) + : __pSymmetricCipher(null) // Default is RC2/CBC/128 + , __pCipherAlgorithm(null) + , __pRc2CipherImpl(null) +{ +} + +Rc2Cipher::~Rc2Cipher(void) +{ + delete __pSymmetricCipher; +} + +result +Rc2Cipher::Construct(const Tizen::Base::String& transformation, CipherOperation opMode) +{ + result r = E_SUCCESS; + bool padVal = false; + String cipherMode = null; + String padding = null; + + SysAssertf(__pSymmetricCipher == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pSymmetricCipher = new (std::nothrow) _SymmetricCipher(); + SysTryReturn(NID_SEC_CRYPTO, __pSymmetricCipher != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + SysTryCatch(NID_SEC_CRYPTO, transformation.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The transformation string should be valid."); + + // Setting the key size, cipher mode and padding for the Rc2 Construct + r = transformation.SubString(0, _TRANSFORMATION_STRING_PART_1_LENGTH, cipherMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (cipherMode.CompareTo(L"CBC") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_rc2_cbc(); + } + else if (cipherMode.CompareTo(L"ECB") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_rc2_ecb(); + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested mode is not supported."); + goto CATCH; + } + + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_A, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"NOPADDING") == E_SUCCESS) + { + padVal = false; + } + else + { + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_B, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"PKCS7PADDING") == E_SUCCESS) + { + padVal = true; + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested padding is not supported."); + goto CATCH; + } + } + + // sets the transformation + r = __pSymmetricCipher->SetTransformation(__pCipherAlgorithm, padVal); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set transformation operation.", GetErrorMessage(r)); + + SysTryCatch(NID_SEC_CRYPTO, opMode == CIPHER_ENCRYPT || opMode == CIPHER_DECRYPT, + r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The opMode should be valid."); + + // sets the SetCipherOpearation + r = __pSymmetricCipher->SetCipherOperation(opMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] The cipher operation request should be valid.", GetErrorMessage(r)); + +CATCH: + if (IsFailed(r)) + { + delete __pSymmetricCipher; + __pSymmetricCipher = null; + } + return r; +} + +result +Rc2Cipher::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int keyLen = 0; + ByteBuffer* pKey = null; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pKey = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Input key data should be valid."); + + keyLen = static_cast< int >(pKey->GetRemaining()); + SysTryCatch(NID_SEC_CRYPTO, keyLen >= 5, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Input key length should be >= algorithm key length."); + + r = __pSymmetricCipher->SetKey(key); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + +CATCH: + delete pKey; + return r; +} + +result +Rc2Cipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->SetInitialVector(initialVector); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set initial vector operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +Rc2Cipher::EncryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input, true); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do encrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +Rc2Cipher::DecryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input, true); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do decrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +result +Rc2Cipher::Initialize(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->Initialize(true); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do initialize operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +Rc2Cipher::UpdateN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->UpdateN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do update operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +Rc2Cipher::FinalizeN(void) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->FinalizeN(); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do finalize operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +Rc2Cipher::WrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +ByteBuffer* +Rc2Cipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoRc4Cipher.cpp b/src/security/crypto/FSecCryptoRc4Cipher.cpp new file mode 100644 index 0000000..928da49 --- /dev/null +++ b/src/security/crypto/FSecCryptoRc4Cipher.cpp @@ -0,0 +1,223 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoRc4Cipher.cpp + * @brief This file contains the implementation of Tizen::Security::Crypto::Rc4Cipher. + */ +#include +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_SymmetricCipher.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +Rc4Cipher::Rc4Cipher(void) + : __pSymmetricCipher(null) // Default is None + , __pCipherAlgorithm(null) + , __pRc4CipherImpl(null) +{ +} + +Rc4Cipher::~Rc4Cipher(void) +{ + delete __pSymmetricCipher; +} + +result +Rc4Cipher::Construct(const Tizen::Base::String& transformation, CipherOperation opMode) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pSymmetricCipher = new (std::nothrow) _SymmetricCipher(); + SysTryReturn(NID_SEC_CRYPTO, __pSymmetricCipher != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + SysTryCatch(NID_SEC_CRYPTO, transformation.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The transformation string should be valid."); + + // Setting the key size, cipher mode and padding for the Rc4 Construct + if (transformation.CompareTo(L"NONE") == E_SUCCESS) + { + __pCipherAlgorithm = EVP_rc4(); + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The requested cipher algorithm is not supported."); + goto CATCH; + } + + // sets the transformation + r = __pSymmetricCipher->SetTransformation(__pCipherAlgorithm, false); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set transformation operation.", GetErrorMessage(r)); + + SysTryCatch(NID_SEC_CRYPTO, opMode == CIPHER_ENCRYPT || opMode == CIPHER_DECRYPT, + r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The opMode should be valid."); + + // sets the SetCipherOpearation + r = __pSymmetricCipher->SetCipherOperation(opMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] The cipher operation request should be valid.", GetErrorMessage(r)); + +CATCH: + if (IsFailed(r)) + { + delete __pSymmetricCipher; + __pSymmetricCipher = null; + } + + return r; +} + +result +Rc4Cipher::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int keyLen = 0; + ByteBuffer* pKey = null; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pKey = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input key data should be valid."); + + keyLen = static_cast< int >(pKey->GetRemaining()); + SysTryCatch(NID_SEC_CRYPTO, keyLen > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Input key length should be >= algorithm key length."); + + r = __pSymmetricCipher->SetKey(key); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + +CATCH: + delete pKey; + return r; +} + +result +Rc4Cipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->SetInitialVector(initialVector); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set initial vector operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +Rc4Cipher::EncryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input, true); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do encrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +Rc4Cipher::DecryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input, true); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do decrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +result +Rc4Cipher::Initialize(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->Initialize(true); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do initialize operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +Rc4Cipher::UpdateN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->UpdateN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do update operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +Rc4Cipher::FinalizeN(void) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->FinalizeN(); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do finalize operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +Rc4Cipher::WrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +ByteBuffer* +Rc4Cipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoRsaCipher.cpp b/src/security/crypto/FSecCryptoRsaCipher.cpp new file mode 100644 index 0000000..ad8e158 --- /dev/null +++ b/src/security/crypto/FSecCryptoRsaCipher.cpp @@ -0,0 +1,235 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoRsaCipher.cpp + * @brief This file contains the implementation of Tizen::Security::Crypto::RsaCipher class. + * + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ +static const int _MAX_ARRAY_LENGTH = 4096; + +RsaCipher::RsaCipher(void) + : __pRsaCipherImpl(null) +{ +} + +RsaCipher::~RsaCipher(void) +{ +} + +result +RsaCipher::SetPrivateKey(const Tizen::Security::IKey& key) +{ + result r = E_SUCCESS; + ByteBuffer* pBuffer = null; + + pBuffer = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Failed to fill the key buffer.", GetErrorMessage(GetLastResult())); + + r = __privateKey.Construct(*pBuffer); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Input key buffer should be valid.", GetErrorMessage(r)); + +CATCH: + delete pBuffer; + return r; +} + +result +RsaCipher::SetPublicKey(const Tizen::Security::IKey& key) +{ + result r = E_SUCCESS; + ByteBuffer* pBuffer = null; + + pBuffer = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Failed to fill the key buffer.", GetErrorMessage(GetLastResult())); + + r = __publicKey.Construct(*pBuffer); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Input key buffer should be valid.", GetErrorMessage(r)); + +CATCH: + delete pBuffer; + return r; +} + +ByteBuffer* +RsaCipher::EncryptN(const Tizen::Base::ByteBuffer& input) +{ + result r = E_SUCCESS; + int dataLen = 0; + int keyLen = 0; + int outLen = 0; + int tempLen = 0; + byte* pData = null; + byte* pTempBuf = null; + byte buffer[_MAX_ARRAY_LENGTH]; + const byte* pKey = null; + ByteBuffer* pOutput = null; + EVP_PKEY* pEvpKey = null; + RSA* pRsa = null; + + ClearLastResult(); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + pKey = __publicKey.GetPointer(); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key value should be valid."); + + keyLen = __publicKey.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen > 0, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + pEvpKey = d2i_PublicKey(EVP_PKEY_RSA, null, &pKey, keyLen); + SysTryReturn(NID_SEC_CRYPTO, pEvpKey != null, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pRsa = EVP_PKEY_get1_RSA(pEvpKey); + SysTryCatch(NID_SEC_CRYPTO, pRsa != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + tempLen = BN_bn2bin(pRsa->n, buffer); + SysTryCatch(NID_SEC_CRYPTO, tempLen > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pTempBuf = new (std::nothrow) byte[tempLen]; + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pTempBuf, 0, tempLen); + + outLen = RSA_public_encrypt(dataLen, pData, pTempBuf, pRsa, RSA_PKCS1_PADDING); + SysTryCatch(NID_SEC_CRYPTO, outLen > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + SysTryCatch(NID_SEC_CRYPTO, outLen <= tempLen, r = E_OVERFLOW, E_OVERFLOW, "[E_OVERFLOW] Overflow as output data length > input data length."); + + pOutput = new (std::nothrow) ByteBuffer(); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pTempBuf, 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + if (IsFailed(r)) + { + delete pOutput; + pOutput = null; + } + if (pRsa) + { + RSA_free(pRsa); + } + EVP_PKEY_free(pEvpKey); + + delete[] pTempBuf; + return pOutput; +} + +ByteBuffer* +RsaCipher::DecryptN(const Tizen::Base::ByteBuffer& input) +{ + result r = E_SUCCESS; + int dataLen = 0; + int keyLen = 0; + int outLen = 0; + int tempLen = 0; + byte* pData = null; + byte* pTempBuf = null; + byte buffer[_MAX_ARRAY_LENGTH]; + const byte* pKey = null; + ByteBuffer* pOutput = null; + EVP_PKEY* pEvpKey = null; + RSA* pRsa = null; + + ClearLastResult(); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + pKey = __privateKey.GetPointer(); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key data should be valid."); + + keyLen = __privateKey.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen > 0, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + //res = __SecCrDecodeRSAPrivateKey(&pPriKey, (CrUINT8 *)pKey, (CrUINT32)keyLen); + pEvpKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKey, keyLen); + SysTryReturn(NID_SEC_CRYPTO, pEvpKey != null, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pRsa = EVP_PKEY_get1_RSA(pEvpKey); + SysTryCatch(NID_SEC_CRYPTO, pRsa != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + tempLen = BN_bn2bin(pRsa->n, buffer); + SysTryCatch(NID_SEC_CRYPTO, tempLen > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pTempBuf = new (std::nothrow) byte[tempLen]; + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_SYSTEM] An unexpected system error occurred."); + + memset(pTempBuf, 0, tempLen); + + outLen = RSA_private_decrypt(dataLen, pData, pTempBuf, pRsa, RSA_PKCS1_PADDING); + SysTryCatch(NID_SEC_CRYPTO, outLen > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_SYSTEM] An unexpected system error occurred."); + SysTryCatch(NID_SEC_CRYPTO, outLen <= tempLen, r = E_OVERFLOW, E_OVERFLOW, "[E_OVERFLOW] Overflow as output data length > input data length."); + + pOutput = new (std::nothrow) ByteBuffer(); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pTempBuf, 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + if (IsFailed(r)) + { + delete pOutput; + pOutput = null; + } + if (pRsa) + { + RSA_free(pRsa); + } + EVP_PKEY_free(pEvpKey); + + delete[] pTempBuf; + return pOutput; +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoRsaSignature.cpp b/src/security/crypto/FSecCryptoRsaSignature.cpp new file mode 100644 index 0000000..d0da511 --- /dev/null +++ b/src/security/crypto/FSecCryptoRsaSignature.cpp @@ -0,0 +1,217 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoRsaSignature.cpp + * @brief This file contains the implementation for Tizen::Security::Crypto::RsaSignature class. + * + */ +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ +static const int _MAX_ARRAY_LENGTH = 4096; + +RsaSignature::RsaSignature(void) + : __pRsaSignatureImpl(null) +{ +} + +RsaSignature::~RsaSignature(void) +{ +} + +result +RsaSignature::SetPrivateKey(const Tizen::Security::IKey& key) +{ + result r = E_SUCCESS; + ByteBuffer* pBuffer = null; + + pBuffer = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Failed to fill the key buffer.", GetErrorMessage(GetLastResult())); + + r = __privateKey.Construct(*pBuffer); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Input key buffer should be valid.", GetErrorMessage(r)); + +CATCH: + delete pBuffer; + return r; +} + +result +RsaSignature::SetPublicKey(const Tizen::Security::IKey& key) +{ + result r = E_SUCCESS; + ByteBuffer* pBuffer = null; + + pBuffer = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Failed to fill the key buffer.", GetErrorMessage(GetLastResult())); + + r = __publicKey.Construct(*pBuffer); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Input key buffer should be valid.", GetErrorMessage(r)); + +CATCH: + delete pBuffer; + return r; +} + +ByteBuffer* +RsaSignature::SignN(const ByteBuffer& input) +{ + result r = E_SUCCESS; + int ret = 0; + int keyLen = 0; + unsigned int dataLen = 0; + unsigned int outLen = 0; + byte buffer[_MAX_ARRAY_LENGTH]; + byte* pTempBuf = null; + const byte* pData = null; + const byte* pKey = null; + ByteBuffer* pOutput = null; + EVP_PKEY* pEvpKey = null; + RSA* pRsa = null; + + ClearLastResult(); + + pData = input.GetPointer(); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + pKey = __privateKey.GetPointer(); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key value should be valid."); + + keyLen = __privateKey.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen > 0, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + pEvpKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKey, keyLen); + SysTryReturn(NID_SEC_CRYPTO, pEvpKey != null, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pRsa = EVP_PKEY_get1_RSA(pEvpKey); + SysTryCatch(NID_SEC_CRYPTO, pRsa != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + outLen = BN_bn2bin(pRsa->n, buffer); + SysTryCatch(NID_SEC_CRYPTO, outLen > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pTempBuf = new (std::nothrow) byte[outLen]; + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pTempBuf, 0, outLen); + + ret = RSA_sign(NID_sha1, pData, dataLen, pTempBuf, &outLen, pRsa); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + SysTryCatch(NID_SEC_CRYPTO, outLen > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Output length should be positive."); + + pOutput = new (std::nothrow) ByteBuffer(); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allovate memory."); + + r = pOutput->SetArray(pTempBuf, 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + if (IsFailed(r)) + { + delete pOutput; + pOutput = null; + } + if (pRsa) + { + RSA_free(pRsa); + } + EVP_PKEY_free(pEvpKey); + + delete[] pTempBuf; + return pOutput; +} + +bool +RsaSignature::Verify(const Tizen::Base::ByteBuffer& data, const Tizen::Base::ByteBuffer& signedData) +{ + result r = E_SUCCESS; + int ret = 0; + int keyLen = 0; + unsigned int dataLen = 0; + unsigned int signedDataLen = 0; + byte* pSignedData = null; + const byte* pData = null; + const byte* pKey = null; + EVP_PKEY* pEvpKey = null; + RSA* pRsa = null; + + ClearLastResult(); + + pData = data.GetPointer(); + SysTryReturn(NID_SEC_CRYPTO, pData != null, false, E_INVALID_ARG, "[E_INVALID_ARG] Input data value should be valid."); + + dataLen = data.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, false, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + pSignedData = const_cast< byte* >(signedData.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pSignedData != null, false, E_INVALID_ARG, "[E_INVALID_ARG] Signed data value should be valid."); + + signedDataLen = static_cast< unsigned int >(signedData.GetRemaining()); + SysTryReturn(NID_SEC_CRYPTO, signedDataLen > 0, false, E_INVALID_ARG, "[E_INVALID_ARG] Signed data length should be positive."); + + pKey = __publicKey.GetPointer(); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, false, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key value should be valid."); + + keyLen = __publicKey.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen > 0, false, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + pEvpKey = d2i_PublicKey(EVP_PKEY_RSA, null, &pKey, keyLen); + SysTryReturn(NID_SEC_CRYPTO, pEvpKey != null, false, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pRsa = EVP_PKEY_get1_RSA(pEvpKey); + SysTryCatch(NID_SEC_CRYPTO, pRsa != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = RSA_verify(NID_sha1, pData, dataLen, pSignedData, signedDataLen, pRsa); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + +CATCH: + + if (pRsa) + { + RSA_free(pRsa); + } + EVP_PKEY_free(pEvpKey); + + if (IsFailed(r)) + { + return false; + } + else + { + return true; + } +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoSha1Hash.cpp b/src/security/crypto/FSecCryptoSha1Hash.cpp new file mode 100644 index 0000000..47ea3ae --- /dev/null +++ b/src/security/crypto/FSecCryptoSha1Hash.cpp @@ -0,0 +1,184 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSha1Hash.cpp + * @brief This file contains the implementation of Sha1Hash class. + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +Sha1Hash::Sha1Hash(void) + : __pEvpMdCtx(null) + , __pSha1HashImpl(null) +{ +} + +Sha1Hash::~Sha1Hash(void) +{ + delete __pEvpMdCtx; +} + +result +Sha1Hash::SetAlgorithm(const Tizen::Base::String& algorithm) +{ + // Unsupported in Sha1Hash + return E_UNSUPPORTED_ALGORITHM; +} + +ByteBuffer* +Sha1Hash::GetHashN(const ByteBuffer& input) const +{ + result r = E_SUCCESS; + int dataLen = 0; + unsigned int outLen = 0; + byte* pData = null; + byte hashOut[SHA_DIGEST_LENGTH] = {'\0'}; + + ClearLastResult(); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be positive."); + + //this function returns the SHA1 hash hashOut + EVP_Digest(pData, dataLen, hashOut, &outLen, EVP_sha1(), null); + SysTryReturn(NID_SEC_CRYPTO, outLen > 0, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //stores the hash in bytebuffer + std::unique_ptr pOutput(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(hashOut, 0, outLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + + return pOutput.release(); +} + +result +Sha1Hash::Initialize(void) +{ + result r = E_SUCCESS; + int ret = 0; + + SysAssertf(__pEvpMdCtx == null, "Already constructed. Calling Initialize() twice or more on a same instance is not allowed for this class."); + + __pEvpMdCtx = new (std::nothrow) EVP_MD_CTX(); + SysTryReturn(NID_SEC_CRYPTO, __pEvpMdCtx != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + //SHA1 init is called + ret = EVP_DigestInit(__pEvpMdCtx, EVP_sha1()); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + +CATCH: + + if (IsFailed(r)) + { + delete __pEvpMdCtx; + __pEvpMdCtx = null; + } + return r; +} + +result +Sha1Hash::Update(const ByteBuffer& input) +{ + result r = E_SUCCESS; + int ret = 0; + int dataLen = 0; + byte* pData = null; + + SysAssertf(__pEvpMdCtx != null, "Not yet constructed. Initialize() should be called before use."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be positive."); + + //SHA1_update is called + ret = EVP_DigestUpdate(__pEvpMdCtx, pData, dataLen); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return r; +} + +ByteBuffer* +Sha1Hash::FinalizeN(void) +{ + result r = E_SUCCESS; + int ret = 0; + int outLen = SHA_DIGEST_LENGTH; + std::unique_ptr pOutput(null); + + ClearLastResult(); + + SysAssertf(__pEvpMdCtx != null, "Not yet constructed. Initialize() should be called before use."); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[outLen]); + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + //SHA1_final is called and is stored in pTempBuf + ret = EVP_DigestFinal(__pEvpMdCtx, pTempBuf.get(), null); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //hash is stored in bytebuffer + pOutput = std::unique_ptr(new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory"); + + r = pOutput->SetArray(pTempBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + EVP_MD_CTX_cleanup(__pEvpMdCtx); + + if (IsFailed(r)) + { + pOutput.reset(null); + } + + delete __pEvpMdCtx; + __pEvpMdCtx = null; + + return pOutput.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoSha1Hmac.cpp b/src/security/crypto/FSecCryptoSha1Hmac.cpp new file mode 100644 index 0000000..7d33c94 --- /dev/null +++ b/src/security/crypto/FSecCryptoSha1Hmac.cpp @@ -0,0 +1,229 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSha1Hmac.cpp + * @brief This file contains the implementation of Sha1Hmac class. + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _SHA1_DIGEST_LENGTH = 20; + +Sha1Hmac::Sha1Hmac(void) + : __pSha1HmacCtx(null) + , __pSha1HmacImpl(null) +{ +} + +Sha1Hmac::~Sha1Hmac(void) +{ + delete __pSha1HmacCtx; +} + +result +Sha1Hmac::SetAlgorithm(const Tizen::Base::String& algorithm) +{ + // Unsupported in Sha1Hmac + return E_UNSUPPORTED_ALGORITHM; +} + +result +Sha1Hmac::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int dataLen = 0; + ByteBuffer* pBuffer = null; + + // convert the ISecretKey to ByteBuffer + pBuffer = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Failed to fill key buffer.", GetErrorMessage(GetLastResult())); + + //converts into bytebuffer + dataLen = static_cast< int >(pBuffer->GetRemaining()); + SysTryCatch(NID_SEC_CRYPTO, dataLen > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Key length should be positive."); + + r = __keyBytes.Construct(*pBuffer); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Input key buffer should be valid.", GetErrorMessage(r)); + +CATCH: + delete pBuffer; + return r; +} + +ByteBuffer* +Sha1Hmac::GetHmacN(const ByteBuffer& input) const +{ + result r = E_SUCCESS; + int dataLen = 0; + int keyLen = 0; + unsigned int mdLen = 0; + byte* pData = null; + byte* pKey = null; + + ClearLastResult(); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + std::unique_ptr pMd(new (std::nothrow) byte[_SHA1_DIGEST_LENGTH]); + SysTryReturn(NID_SEC_CRYPTO, pMd != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pMd.get(), 0, _SHA1_DIGEST_LENGTH); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key value should be valid."); + + keyLen = __keyBytes.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + //gets HMAC of the input data + HMAC(EVP_sha1(), pKey, keyLen, pData, dataLen, pMd.get(), &mdLen); + SysTryReturn(NID_SEC_CRYPTO, mdLen != 0, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //stores the HMAC output in bytebuffer + std::unique_ptr pOutput(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to create memory."); + + r = pOutput->Construct(mdLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_OUT_OF_MEMORY, "[E_OUT_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pMd.get(), 0, mdLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + + return pOutput.release(); +} + +result +Sha1Hmac::Initialize(void) +{ + result r = E_SUCCESS; + int ret = 0; + int keyLen = 0; + byte* pKey = null; + + SysAssertf(__pSha1HmacCtx == null, "Already constructed. Calling Initialize() twice or more on a same instance is not allowed for this class."); + + __pSha1HmacCtx = new (std::nothrow) HMAC_CTX(); + SysTryReturn(NID_SEC_CRYPTO, __pSha1HmacCtx != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryCatch(NID_SEC_CRYPTO, pKey != null, r = E_KEY_NOT_FOUND, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] The key value should be valid."); + + keyLen = __keyBytes.GetRemaining(); + SysTryCatch(NID_SEC_CRYPTO, keyLen > 0, r = E_KEY_NOT_FOUND, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] The key length should be positive."); + + //calls the HMAC_init function + ret = HMAC_Init(__pSha1HmacCtx, pKey, keyLen, EVP_sha1()); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + +CATCH: + + if (IsFailed(r)) + { + delete __pSha1HmacCtx; + __pSha1HmacCtx = null; + } + return r; +} + +result +Sha1Hmac::Update(const Tizen::Base::ByteBuffer& input) +{ + result r = E_SUCCESS; + int ret = 0; + int dataLen = 0; + byte* pData = null; + + SysAssertf(__pSha1HmacCtx != null, "Not yet constructed. Initialize() should be called before use."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be valid."); + + //calls the HMAC_update function + ret = HMAC_Update(__pSha1HmacCtx, const_cast< byte* >(pData), static_cast< unsigned long >(dataLen)); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return r; +} + +Tizen::Base::ByteBuffer* +Sha1Hmac::FinalizeN(void) +{ + result r = E_SUCCESS; + int ret = 0; + unsigned int outLen = _SHA1_DIGEST_LENGTH; + std::unique_ptr pOutput(null); + + ClearLastResult(); + + SysAssertf(__pSha1HmacCtx != null, "Not yet constructed. Initialize() should be called before use."); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[outLen]); + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + //call the HMAC_final function and stores output in pTempBuf + ret = HMAC_Final(__pSha1HmacCtx, pTempBuf.get(), &outLen); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //write HMAC output in bytebuffer + pOutput = std::unique_ptr(new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to create memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pTempBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + HMAC_CTX_cleanup(__pSha1HmacCtx); + + if (IsFailed(r)) + { + pOutput.reset(null); + } + + delete __pSha1HmacCtx; + __pSha1HmacCtx = null; + + return pOutput.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoSha2Hash.cpp b/src/security/crypto/FSecCryptoSha2Hash.cpp new file mode 100644 index 0000000..a11c10a --- /dev/null +++ b/src/security/crypto/FSecCryptoSha2Hash.cpp @@ -0,0 +1,210 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSha2Hash.cpp + * @brief This file contains the implementation of Sha2Hash class. + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace Security { namespace Crypto +{ +static const int _SHA2_DIGEST_LENGTH = 64; + +Sha2Hash::Sha2Hash(void) + : __pAlgorithm(EVP_sha256()) + , __pEvpMdCtx(null) + , __pSha2HashImpl(null) +{ +} + +Sha2Hash::~Sha2Hash(void) +{ + delete __pEvpMdCtx; +} + +result +Sha2Hash::SetAlgorithm(const Tizen::Base::String& algorithm) +{ + result r = E_SUCCESS; + + if (algorithm.CompareTo(L"SHA2/224") == 0) + { + __pAlgorithm = EVP_sha224(); + } + else if (algorithm.CompareTo(L"SHA2/256") == 0) + { + __pAlgorithm = EVP_sha256(); + } + else if (algorithm.CompareTo(L"SHA2/384") == 0) + { + __pAlgorithm = EVP_sha384(); + } + else if (algorithm.CompareTo(L"SHA2/512") == 0) + { + __pAlgorithm = EVP_sha512(); + } + else + { + r = E_UNSUPPORTED_ALGORITHM; + } + + return r; +} + +ByteBuffer* +Sha2Hash::GetHashN(const ByteBuffer& input) const +{ + result r = E_SUCCESS; + int dataLen = 0; + unsigned int outLen = 0; + byte* pData = null; + byte hashOut[_SHA2_DIGEST_LENGTH] = {'\0'}; + + ClearLastResult(); + + SysTryReturn(NID_SEC_CRYPTO, __pAlgorithm != null, null, E_INVALID_ARG, "[E_INVALID_ARG] The algorithm value should be valid."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be positive."); + + outLen = EVP_MD_size(__pAlgorithm); + + EVP_Digest(pData, dataLen, hashOut, &outLen, __pAlgorithm, null); + SysTryReturn(NID_SEC_CRYPTO, outLen > 0, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //stores the hash in bytebuffer + std::unique_ptr pOutput(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(hashOut, 0, outLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + + return pOutput.release(); +} + +result +Sha2Hash::Initialize(void) +{ + result r = E_SUCCESS; + int ret = 0; + + SysAssertf(__pEvpMdCtx == null, "Already constructed. Calling Initialize() twice or more on a same instance is not allowed for this class."); + + __pEvpMdCtx = new (std::nothrow) EVP_MD_CTX(); + SysTryReturn(NID_SEC_CRYPTO, __pEvpMdCtx != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + ret = EVP_DigestInit(__pEvpMdCtx, __pAlgorithm); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + +CATCH: + + if (IsFailed(r)) + { + delete __pEvpMdCtx; + __pEvpMdCtx = null; + } + return r; +} + +result +Sha2Hash::Update(const Tizen::Base::ByteBuffer& input) +{ + result r = E_SUCCESS; + int ret = 0; + int dataLen = 0; + byte* pData = null; + + SysAssertf(__pEvpMdCtx != null, "Not yet constructed. Initialize() should be called before use."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be positive."); + + //SHA2_update is called + ret = EVP_DigestUpdate(__pEvpMdCtx, pData, dataLen); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return r; +} + +Tizen::Base::ByteBuffer* +Sha2Hash::FinalizeN(void) +{ + result r = E_SUCCESS; + int ret = 0; + int outLen = 0; + std::unique_ptr pOutput(null); + + ClearLastResult(); + + SysAssertf(__pEvpMdCtx != null && __pAlgorithm != null, "Not yet constructed. Initialize() and SetAlgorithm() should be called before use."); + + outLen = EVP_MD_size(__pAlgorithm); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[outLen]); + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + ret = EVP_DigestFinal(__pEvpMdCtx, pTempBuf.get(), null); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //hash is stored in bytebuffer + pOutput = std::unique_ptr(new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory"); + + r = pOutput->SetArray(pTempBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + EVP_MD_CTX_cleanup(__pEvpMdCtx); + + if (IsFailed(r)) + { + pOutput.reset(null); + } + + delete __pEvpMdCtx; + __pEvpMdCtx = null; + + return pOutput.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoSha2Hmac.cpp b/src/security/crypto/FSecCryptoSha2Hmac.cpp new file mode 100644 index 0000000..d6dc4de --- /dev/null +++ b/src/security/crypto/FSecCryptoSha2Hmac.cpp @@ -0,0 +1,253 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSha2Hmac.cpp + * @brief This file contains the implementation of Sha2Hmac class. + */ +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +Sha2Hmac::Sha2Hmac(void) + : __pSha2HmacCtx(null) + , __pAlgorithm(EVP_sha256()) + , __pSha2HmacImpl(null) +{ +} + +Sha2Hmac::~Sha2Hmac(void) +{ + delete __pSha2HmacCtx; +} + +result +Sha2Hmac::SetAlgorithm(const Tizen::Base::String& algorithm) +{ + result r = E_SUCCESS; + + if (algorithm.CompareTo(L"HMACSHA2/224") == 0) + { + __pAlgorithm = EVP_sha224(); + } + else if (algorithm.CompareTo(L"HMACSHA2/256") == 0) + { + __pAlgorithm = EVP_sha256(); + } + else if (algorithm.CompareTo(L"HMACSHA2/384") == 0) + { + __pAlgorithm = EVP_sha384(); + } + else if (algorithm.CompareTo(L"HMACSHA2/512") == 0) + { + __pAlgorithm = EVP_sha512(); + } + else + { + r = E_UNSUPPORTED_ALGORITHM; + } + + return r; +} + +result +Sha2Hmac::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int dataLen = 0; + ByteBuffer* pBuffer = null; + + //convert the ISecretKey to ByteBuffer + pBuffer = key.GetEncodedN(); + SysTryReturn(NID_SEC_CRYPTO, pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Failed to fill key buffer.", GetErrorMessage(GetLastResult())); + + //converts into bytebuffer + dataLen = static_cast< int >(pBuffer->GetRemaining()); + SysTryCatch(NID_SEC_CRYPTO, dataLen > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Key length should be positive."); + + r = __keyBytes.Construct(*pBuffer); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Input key buffer should be valid.", GetErrorMessage(r)); + +CATCH: + delete pBuffer; + return r; +} + +ByteBuffer* +Sha2Hmac::GetHmacN(const ByteBuffer& input) const +{ + result r = E_SUCCESS; + int dataLen = 0; + int keyLen = 0; + unsigned int mdLen = 0; + byte* pData = null; + byte* pKey = null; + + ClearLastResult(); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key value should be valid."); + + keyLen = __keyBytes.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen > 0, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + mdLen = EVP_MD_size(__pAlgorithm); + + std::unique_ptr pMd(new (std::nothrow) byte[mdLen]); + SysTryReturn(NID_SEC_CRYPTO, pMd != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(pMd.get(), 0, mdLen); + + //gets HMAC of the input data for SEC_MAC_SHA224 + HMAC(__pAlgorithm, pKey, keyLen, pData, dataLen, pMd.get(), &mdLen); + SysTryReturn(NID_SEC_CRYPTO, mdLen != 0, null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //stores the HMAC output in bytebuffer + std::unique_ptr pOutput(new (std::nothrow) ByteBuffer()); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to create memory."); + + r = pOutput->Construct(mdLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_OUT_OF_MEMORY, "[E_OUT_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pMd.get(), 0, mdLen); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), null, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + + return pOutput.release(); +} + +result +Sha2Hmac::Initialize(void) +{ + result r = E_SUCCESS; + int ret = 0; + int keyLen = 0; + byte* pKey = null; + + SysAssertf(__pSha2HmacCtx == null, "Already constructed. Calling Initialize() twice or more on a same instance is not allowed for this class."); + + __pSha2HmacCtx = new (std::nothrow) HMAC_CTX(); + SysTryReturn(NID_SEC_CRYPTO, __pSha2HmacCtx != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryCatch(NID_SEC_CRYPTO, pKey != null, r = E_KEY_NOT_FOUND, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] The key value should be valid."); + + keyLen = __keyBytes.GetRemaining(); + SysTryCatch(NID_SEC_CRYPTO, keyLen > 0, r = E_KEY_NOT_FOUND, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] The key length should be positive."); + + ret = HMAC_Init(__pSha2HmacCtx, pKey, keyLen, __pAlgorithm); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + +CATCH: + + if (IsFailed(r)) + { + delete __pSha2HmacCtx; + __pSha2HmacCtx = null; + } + return r; +} + +result +Sha2Hmac::Update(const Tizen::Base::ByteBuffer& input) +{ + result r = E_SUCCESS; + int ret = 0; + int dataLen = 0; + byte* pData = null; + + SysAssertf(__pSha2HmacCtx != null, "Not yet constructed. Initialize() should be called before use."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data value should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input data length should be valid."); + + //calls the HMAC_update function + ret = HMAC_Update(__pSha2HmacCtx, const_cast< byte* >(pData), static_cast< unsigned long >(dataLen)); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return r; +} + +Tizen::Base::ByteBuffer* +Sha2Hmac::FinalizeN(void) +{ + result r = E_SUCCESS; + int ret = 0; + unsigned int outLen = 0; + std::unique_ptr pOutput(null); + + ClearLastResult(); + + SysAssertf(__pSha2HmacCtx != null && __pAlgorithm != null, "Not yet constructed. Initialize() and SetAlgorithm() should be called before use."); + + outLen = EVP_MD_size(__pAlgorithm); + + std::unique_ptr pTempBuf(new (std::nothrow) byte[outLen]); + SysTryCatch(NID_SEC_CRYPTO, pTempBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + //call the HMAC_final function based on the SHA2 algorithm and stores output in pTempBuf + ret = HMAC_Final(__pSha2HmacCtx, pTempBuf.get(), &outLen); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //write HMAC output in bytebuffer + pOutput = std::unique_ptr(new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to create memory."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pTempBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + HMAC_CTX_cleanup(__pSha2HmacCtx); + + if (IsFailed(r)) + { + pOutput.reset(null); + } + + delete __pSha2HmacCtx; + __pSha2HmacCtx = null; + + return pOutput.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCryptoSkipJackCipher.cpp b/src/security/crypto/FSecCryptoSkipJackCipher.cpp new file mode 100644 index 0000000..f3b3dd7 --- /dev/null +++ b/src/security/crypto/FSecCryptoSkipJackCipher.cpp @@ -0,0 +1,262 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCryptoSkipJackCipher.cpp + * @brief This header file contains the declaration of Tizen::Security::Crypto::SkipJackCipher. + * + */ +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_SkipJackModes.h" +#include "FSecCrypto_SymmetricCipher.h" + +using namespace Tizen::Base; + +const EVP_CIPHER* EvpSkipJackCbc80(); +const EVP_CIPHER* EvpSkipJackEcb80(); + + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _TRANSFORMATION_STRING_PART_1_LENGTH = 3; +static const int _TRANSFORMATION_STRING_PART_2_BEGIN = 4; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_A = 9; +static const int _TRANSFORMATION_STRING_PART_2_LENGTH_B = 12; + +SkipJackCipher::SkipJackCipher(void) + : __pSymmetricCipher(null) // Default is SKIPJACK/CBC/80 + , __pCipherAlgorithm(null) + , __pSkipJackCipherImpl(null) +{ +} + +SkipJackCipher::~SkipJackCipher(void) +{ + delete __pSymmetricCipher; +} + +result +SkipJackCipher::Construct(const Tizen::Base::String& transformation, CipherOperation opMode) +{ + result r = E_SUCCESS; + bool padVal = false; + String cipherMode = null; + String padding = null; + + SysAssertf(__pSymmetricCipher == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + __pSymmetricCipher = new (std::nothrow) _SymmetricCipher(); + SysTryReturn(NID_SEC_CRYPTO, __pSymmetricCipher != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + SysTryCatch(NID_SEC_CRYPTO, transformation.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The transformation string should be valid."); + + // Setting the key size, cipher mode and padding for the SkipJack Construct + r = transformation.SubString(0, _TRANSFORMATION_STRING_PART_1_LENGTH, cipherMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (cipherMode.CompareTo(L"CBC") == E_SUCCESS) + { + __pCipherAlgorithm = EvpSkipJackCbc80(); + } + else if (cipherMode.CompareTo(L"ECB") == E_SUCCESS) + { + __pCipherAlgorithm = EvpSkipJackEcb80(); + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested mode is not supported."); + goto CATCH; + } + + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_A, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"NOPADDING") == E_SUCCESS) + { + padVal = false; + } + else + { + r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH_B, padding); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid."); + + if (padding.CompareTo(L"PKCS7PADDING") == E_SUCCESS) + { + padVal = true; + } + else + { + r = E_INVALID_ARG; + SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested padding is not supported."); + goto CATCH; + } + } + + // sets the transformation + r = __pSymmetricCipher->SetTransformation(__pCipherAlgorithm, padVal); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set transformation operation.", GetErrorMessage(r)); + + SysTryCatch(NID_SEC_CRYPTO, opMode == CIPHER_ENCRYPT || opMode == CIPHER_DECRYPT, + r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The opMode should be valid."); + + // sets the SetCipherOpearation + r = __pSymmetricCipher->SetCipherOperation(opMode); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] The cipher operation request should be valid.", GetErrorMessage(r)); + +CATCH: + if (IsFailed(r)) + { + delete __pSymmetricCipher; + __pSymmetricCipher = null; + } + return r; +} + +result +SkipJackCipher::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + int keyLen = 0; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + std::unique_ptr pKey(key.GetEncodedN()); + SysTryReturnResult(NID_SEC_CRYPTO, pKey != null, E_INVALID_ARG, "Key data should be valid."); + + keyLen = static_cast< int >(pKey->GetRemaining()); + SysTryReturnResult(NID_SEC_CRYPTO, keyLen == __pCipherAlgorithm->key_len, E_INVALID_ARG, "Input key length should be equal to algorithm key length."); + + r = __pSymmetricCipher->SetKey(key); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set key operation.", GetErrorMessage(r)); + + return r; +} + +result +SkipJackCipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->SetInitialVector(initialVector); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set initial vector operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +SkipJackCipher::EncryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do encrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +SkipJackCipher::DecryptN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->DoCipherN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do decrypt operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +result +SkipJackCipher::Initialize(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + r = __pSymmetricCipher->Initialize(); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do initialize operation.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +SkipJackCipher::UpdateN(const Tizen::Base::ByteBuffer& input) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->UpdateN(input); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do update operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +SkipJackCipher::FinalizeN(void) +{ + ByteBuffer* pOutput = null; + + ClearLastResult(); + + SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use."); + + pOutput = __pSymmetricCipher->FinalizeN(); + SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do finalize operation", GetErrorMessage(GetLastResult())); + + return pOutput; +} + +ByteBuffer* +SkipJackCipher::WrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +ByteBuffer* +SkipJackCipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + ClearLastResult(); + + SetLastResult(E_UNSUPPORTED_ALGORITHM); + + return null; +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCrypto_KeaCore.cpp b/src/security/crypto/FSecCrypto_KeaCore.cpp new file mode 100644 index 0000000..d2d4dda --- /dev/null +++ b/src/security/crypto/FSecCrypto_KeaCore.cpp @@ -0,0 +1,297 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto_KeaCore.cpp + * @brief This file contains implementation of Kea Key Exchange algorithms and Shared Secret Generation. + */ +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_KeaCore.h" +#include "FSecCrypto_SkipJackCore.h" + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _DATA_ARRAY_SIZE = 2; +static const int _KEA_KEY_LOOP_VAR_1 = 5; +static const int _KEA_KEY_LOOP_VAR_2 = 7; +static const int _ONE_BIT_RESET_VAL = 0x00; +static const int _KEA_LSB_VAL_1 = 2; +static const int _KEA_LSB_VAL_2 = 3; +static const int _KEA_MSB_VAL_1 = 9; +static const int _KEA_MSB_VAL_2 = 8; +static const int _TWO_BYTE_VAL = 16; +static const int _CRYPTO_VARIABLE_SIGNIFICANT_BITS_ = 20; +static const int _PUBLIC_KEY_LENGTH = 1024; + +Kea* +_KeaCore::CreateKeaN(void) +{ + ClearLastResult(); + + std::unique_ptr pRet (new (std::nothrow) Kea()); + SysTryReturn(NID_SEC_CRYPTO, pRet != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new Kea object failed."); + + pRet->version = 0; + pRet->pP = null; + pRet->pG = null; + pRet->length = 0; + pRet->pPubKey1 = null; + pRet->pPrivKey1 = null; + pRet->pPubKey2 = null; + pRet->pPrivKey2 = null; + + return pRet.release(); +} + +void +_KeaCore::DeleteKea(Kea* pKea) +{ + if (pKea->pP != null) + { + BN_clear_free(pKea->pP); + } + + if (pKea->pG != null) + { + BN_clear_free(pKea->pG); + } + + if (pKea->pPubKey1 != null) + { + BN_clear_free(pKea->pPubKey1); + } + + if (pKea->pPrivKey1 != null) + { + BN_clear_free(pKea->pPrivKey1); + } + + if (pKea->pPubKey2 != null) + { + BN_clear_free(pKea->pPubKey2); + } + + if (pKea->pPrivKey2 != null) + { + BN_clear_free(pKea->pPrivKey2); + } +} + +result +_KeaCore::ComputeKeaKey(byte** ppKey, BIGNUM* pPublicKey1, BIGNUM* pPublicKey2, Kea& keaVar) +{ + result r = E_SUCCESS; + int ret = 0; + byte secret[_PUBLIC_KEY_LENGTH] = {0, }; + BN_CTX* pCtx = null; + BIGNUM* pTmp = null; + BIGNUM* pTmp1 = null; + BIGNUM* pRem = null; + + SysTryReturn(NID_SEC_CRYPTO, ppKey != null && pPublicKey1 != null && pPublicKey2 != null + , E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Input key data and public keys should be valid."); + + pCtx = BN_CTX_new(); + SysTryReturn(NID_SEC_CRYPTO, pCtx != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + // Managing 1st set of public and private key + BN_CTX_start(pCtx); + pTmp = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC_CRYPTO, pTmp != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + SysTryCatch(NID_SEC_CRYPTO, keaVar.pPrivKey1 != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key is not available."); + + ret = BN_mod_exp(pTmp, pPublicKey1, keaVar.pPrivKey1, keaVar.pP, pCtx); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + // Managing 2nd set of public and private key + pTmp1 = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC_CRYPTO, pTmp1 != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + SysTryCatch(NID_SEC_CRYPTO, keaVar.pPrivKey2 != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key is not available."); + + ret = BN_mod_exp(pTmp1, pPublicKey2, keaVar.pPrivKey2, keaVar.pP, pCtx); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + // Performing operation pRem = (pTmp + pTmp1) mod p + pRem = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC_CRYPTO, pRem != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = BN_add(pRem, pTmp, pTmp1); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = BN_mod(pTmp, pRem, keaVar.pP, pCtx); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + ret = BN_bn2bin(pTmp, secret); + SysTryCatch(NID_SEC_CRYPTO, ret > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + keaVar.length = ret; + + *ppKey = ComputeKeaSecret(secret, ret); + SysTryCatch(NID_SEC_CRYPTO, *ppKey != null, r = GetLastResult(), GetLastResult(), "[%s] Kea key secret should be valid.", GetErrorMessage(GetLastResult())); + +CATCH: + if (pCtx != null) + { + BN_CTX_end(pCtx); + BN_CTX_free(pCtx); + } + + return r; +} + +byte* +_KeaCore::ComputeKeaSecret(byte* pKey, int len) +{ + result r = E_SUCCESS; + int index = 0; + int ret = 0; + byte pad[_SKIPJACK_KEY_LENGTH] = {0x72, 0xf1, 0xa8, 0x7e, 0x92, 0x82, 0x41, 0x98, 0xab, 0x0b}; + byte vector3[_DATA_ARRAY_SIZE] = {0, }; + SkipJackKey sjVar = {{0, }, }; + BIGNUM* pBn1 = null; + BIGNUM* pBn2 = null; + BIGNUM* pBn3 = null; + BN_CTX* pCtx = null; + + ClearLastResult(); + + std::unique_ptr pVector1 (new (std::nothrow) byte[_SKIPJACK_KEY_LENGTH]); + SysTryReturn(NID_SEC_CRYPTO, pVector1 != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + std::unique_ptr pVector2 (new (std::nothrow) byte[_SKIPJACK_KEY_LENGTH]); + SysTryCatch(NID_SEC_CRYPTO, pVector2 != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + pCtx = BN_CTX_new(); + SysTryCatch(NID_SEC_CRYPTO, pCtx != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + memset(&sjVar, 0, sizeof(sjVar)); + + memcpy(pVector1.get(), (pKey + len - _SKIPJACK_KEY_LENGTH), _SKIPJACK_KEY_LENGTH); + + memcpy(pVector2.get(), (pKey + len - _CRYPTO_VARIABLE_SIGNIFICANT_BITS_), _SKIPJACK_KEY_LENGTH); + + for (index = 0; index < _KEA_KEY_LOOP_VAR_1; index++) + { + pVector1.get()[index] = pVector1.get()[index] + pVector1.get()[_KEA_MSB_VAL_1 - index]; + pVector1.get()[_KEA_MSB_VAL_1 - index] = pVector1.get()[index] - pVector1.get()[_KEA_MSB_VAL_1 - index]; + pVector1.get()[index] = pVector1.get()[index] - pVector1.get()[_KEA_MSB_VAL_1 - index]; + + pVector2.get()[index] = pVector2.get()[index] + pVector2.get()[_KEA_MSB_VAL_1 - index]; + pVector2.get()[_KEA_MSB_VAL_1 - index] = pVector2.get()[index] - pVector2.get()[_KEA_MSB_VAL_1 - index]; + pVector2.get()[index] = pVector2.get()[index] - pVector2.get()[_KEA_MSB_VAL_1 - index]; + } + + //for creating key pVector1 ^ pad + for (index = 0; index < _SKIPJACK_KEY_LENGTH; index++) + { + pVector1.get()[index] = pVector1.get()[index] ^ pad[index]; + } + + //for doing (pVector2 / 2^16) mod 2 ^64 + //1st Step: we perform left shift on pVector2 by 2 bytes to perform (pVector2 / 2^16) + for (index = _KEA_KEY_LOOP_VAR_2; index >= 0; index--) + { + pVector2.get()[_DATA_ARRAY_SIZE + index] = pVector2.get()[index]; + } + + //Setting 1st 2 bytes as 0 in continuation from the above operation + // no need for explicitly doing mod 2^64 opeartion since number will be the same + // as 2^64 -1 = 0xFFFFFFFFFFFFFFFF and that is the biggest 64 bit number + // and x is also a 64 bit number + // therefore x mod 2^64 = x + for (index = 0; index < _DATA_ARRAY_SIZE; index++) + { + pVector2.get()[index] = _ONE_BIT_RESET_VAL; + } + + // making modified pVector1 as key for doing skipjack operation + for (index = 0; index < _SKIPJACK_KEY_LENGTH; index++) + { + sjVar.keyVal[index] = pVector1.get()[index]; + } + + BN_CTX_start(pCtx); + + pBn2 = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC_CRYPTO, pBn2 != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pBn3 = BN_CTX_get(pCtx); + SysTryCatch(NID_SEC_CRYPTO, pBn3 != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //Peforming pVector2 mod 2exp16 and storing it in vector3 + //pVector2 in to big number + pBn1 = BN_bin2bn(pVector2.get(), _SKIPJACK_KEY_LENGTH, null); + SysTryCatch(NID_SEC_CRYPTO, pBn1 != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //2^16 into big number + ret = BN_lshift(pBn2, BN_value_one(), _TWO_BYTE_VAL); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + // performing pVector2 mod 2^16 + ret = BN_mod(pBn3, pBn1, pBn2, pCtx); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + // storing it in array + ret = BN_bn2bin(pBn3, vector3); + SysTryCatch(NID_SEC_CRYPTO, ret > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //Performing encryption over (pVector2/2^16) mod 2 ^ 64 + _SkipJackCore::DoCipherEcb(static_cast< const byte* >(pVector2.get() + _DATA_ARRAY_SIZE), pVector1.get(), sjVar, static_cast< bool >(1)); + + //Performing second encryption on the output data from previous encryption + for (index = _KEA_KEY_LOOP_VAR_2; index >= 0; index--) + { + pVector1.get()[_DATA_ARRAY_SIZE + index] = pVector1.get()[index]; + //printf("%c\t",pVector2[index]); + } + + for (index = 0; index < _DATA_ARRAY_SIZE; index++) + { + pVector1.get()[index] = _ONE_BIT_RESET_VAL; + //printf("%c \t",pVector2[index]); + } + + _SkipJackCore::DoCipherEcb(static_cast< const byte* >(pVector1.get() + _DATA_ARRAY_SIZE), pVector2.get(), sjVar, static_cast< bool >(1)); + + // xoring pVector1 msb with vector3 + pVector1.get()[0] = pVector1.get()[0] ^ vector3[0]; + pVector1.get()[1] = pVector1.get()[1] ^ vector3[1]; + + //adding the xored bits as lsb in pVector1 + pVector2.get()[_KEA_MSB_VAL_2] = pVector1.get()[_KEA_LSB_VAL_1]; + pVector2.get()[_KEA_MSB_VAL_1] = pVector1.get()[_KEA_LSB_VAL_2]; + +CATCH: + + if (pCtx != null) + { + BN_CTX_end(pCtx); + BN_CTX_free(pCtx); + } + + return pVector2.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCrypto_KeaCore.h b/src/security/crypto/FSecCrypto_KeaCore.h new file mode 100644 index 0000000..2640d47 --- /dev/null +++ b/src/security/crypto/FSecCrypto_KeaCore.h @@ -0,0 +1,61 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto_KeaCore.h + * @brief This header file contains declarations of KEA Key Exchange algorithms and Shared Secret Generation. + */ +#ifndef _FSEC_CRYPTO_INTERNAL_KEA_CORE_H_ +#define _FSEC_CRYPTO_INTERNAL_KEA_CORE_H_ + +struct bignum_st; + +namespace Tizen { namespace Security { namespace Crypto +{ + +struct Kea +{ + int version; + int length; + bignum_st* pP; + bignum_st* pG; + bignum_st* pPubKey1; // y + bignum_st* pPrivKey1; // x + bignum_st* pPubKey2; // r + bignum_st* pPrivKey2; // t +}; + +class _KeaCore +{ + +public: + static Kea* CreateKeaN(void); + static void DeleteKea(Kea* pKea); + static result ComputeKeaKey(byte** ppKey, bignum_st* pPublicKey1, bignum_st* pPublicKey2, Kea& keaVar); + static byte* ComputeKeaSecret(byte* pKey, int len); + +private: + _KeaCore(void); + _KeaCore(const _KeaCore& rhs); + _KeaCore& operator =(const _KeaCore& rhs); + ~_KeaCore(void); + +}; //_KeaCore + +} } } // Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_INTERNAL_KEA_CORE_H_ diff --git a/src/security/crypto/FSecCrypto_SkipJackCore.cpp b/src/security/crypto/FSecCrypto_SkipJackCore.cpp new file mode 100644 index 0000000..80b421a --- /dev/null +++ b/src/security/crypto/FSecCrypto_SkipJackCore.cpp @@ -0,0 +1,373 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto_SkipJackCore.cpp + * @brief This file contains the implementation of SkipJack Core encryption and decryption algorithms. + */ +#include +#include "FSecCrypto_SkipJackCore.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +static const int _INCREMENT_ONE_BYTE = 1; +static const int _INCREMENT_TWO_BYTE = 2; +static const int _INCREMENT_THREE_BYTE = 3; +static const int _ONE_WORD_VAL = 4; +static const int _ONE_BYTE_VAL = 8; +static const int _TWO_BYTE_VAL = 16; +static const int _FOUR_BYTE_VAL = 32; +static const int _SHIFT_ONE_BYTE = 8; +static const int _SHIFT_TWO_BYTE = 16; +static const int _SHIFT_THREE_BYTE = 24; +static const int _ONE_BYTE_MASK = 0xff; +static const int _TWO_BYTE_MASK = 0xffff; +static const int _FOUR_BYTE_MASK = 0xffffffff; +static const int _DATA_ARRAY_SIZE = 2; + +//This table includes constant values that are part of the G-permutation function +static const byte _FIELD_TABLE[_TWO_BYTE_VAL][_TWO_BYTE_VAL] = +{ + {0xa3, 0xd7, 0x09, 0x83, 0xf8, 0x48, 0xf6, 0xf4, 0xb3, 0x21, 0x15, 0x78, 0x99, 0xb1, 0xaf, 0xf9}, + {0xe7, 0x2d, 0x4d, 0x8a, 0xce, 0x4c, 0xca, 0x2e, 0x52, 0x95, 0xd9, 0x1e, 0x4e, 0x38, 0x44, 0x28}, + {0x0a, 0xdf, 0x02, 0xa0, 0x17, 0xf1, 0x60, 0x68, 0x12, 0xb7, 0x7a, 0xc3, 0xe9, 0xfa, 0x3d, 0x53}, + {0x96, 0x84, 0x6b, 0xba, 0xf2, 0x63, 0x9a, 0x19, 0x7c, 0xae, 0xe5, 0xf5, 0xf7, 0x16, 0x6a, 0xa2}, + {0x39, 0xb6, 0x7b, 0x0f, 0xc1, 0x93, 0x81, 0x1b, 0xee, 0xb4, 0x1a, 0xea, 0xd0, 0x91, 0x2f, 0xb8}, + {0x55, 0xb9, 0xda, 0x85, 0x3f, 0x41, 0xbf, 0xe0, 0x5a, 0x58, 0x80, 0x5f, 0x66, 0x0b, 0xd8, 0x90}, + {0x35, 0xd5, 0xc0, 0xa7, 0x33, 0x06, 0x65, 0x69, 0x45, 0x00, 0x94, 0x56, 0x6d, 0x98, 0x9b, 0x76}, + {0x97, 0xfc, 0xb2, 0xc2, 0xb0, 0xfe, 0xdb, 0x20, 0xe1, 0xeb, 0xd6, 0xe4, 0xdd, 0x47, 0x4a, 0x1d}, + {0x42, 0xed, 0x9e, 0x6e, 0x49, 0x3c, 0xcd, 0x43, 0x27, 0xd2, 0x07, 0xd4, 0xde, 0xc7, 0x67, 0x18}, + {0x89, 0xcb, 0x30, 0x1f, 0x8d, 0xc6, 0x8f, 0xaa, 0xc8, 0x74, 0xdc, 0xc9, 0x5d, 0x5c, 0x31, 0xa4}, + {0x70, 0x88, 0x61, 0x2c, 0x9f, 0x0d, 0x2b, 0x87, 0x50, 0x82, 0x54, 0x64, 0x26, 0x7d, 0x03, 0x40}, + {0x34, 0x4b, 0x1c, 0x73, 0xd1, 0xc4, 0xfd, 0x3b, 0xcc, 0xfb, 0x7f, 0xab, 0xe6, 0x3e, 0x5b, 0xa5}, + {0xad, 0x04, 0x23, 0x9c, 0x14, 0x51, 0x22, 0xf0, 0x29, 0x79, 0x71, 0x7e, 0xff, 0x8c, 0x0e, 0xe2}, + {0x0c, 0xef, 0xbc, 0x72, 0x75, 0x6f, 0x37, 0xa1, 0xec, 0xd3, 0x8e, 0x62, 0x8b, 0x86, 0x10, 0xe8}, + {0x08, 0x77, 0x11, 0xbe, 0x92, 0x4f, 0x24, 0xc5, 0x32, 0x36, 0x9d, 0xcf, 0xf3, 0xa6, 0xbb, 0xac}, + {0x5e, 0x6c, 0xa9, 0x13, 0x57, 0x25, 0xb5, 0xe3, 0xbd, 0xa8, 0x3a, 0x01, 0x05, 0x59, 0x2a, 0x46} +}; + +void +TransformByteToLong(const byte*& pInputVal, unsigned long& inputLongVal) +{ + inputLongVal = static_cast< unsigned long >(*(pInputVal++)); + inputLongVal |= (static_cast< unsigned long >(*(pInputVal++))) << _SHIFT_ONE_BYTE; + inputLongVal |= (static_cast< unsigned long >(*(pInputVal++))) << _SHIFT_TWO_BYTE; + inputLongVal |= (static_cast< unsigned long >(*(pInputVal++))) << _SHIFT_THREE_BYTE; +} + +void +TransformLongToByte(unsigned long inputLongVal, byte*& pInputVal) +{ + *(pInputVal++) = static_cast< byte >(inputLongVal & _ONE_BYTE_MASK); + *(pInputVal++) = static_cast< byte >((inputLongVal >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK); + *(pInputVal++) = static_cast< byte >((inputLongVal >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK); + *(pInputVal++) = static_cast< byte >((inputLongVal >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); +} + +// This macro defines the procedure for implemeting G- permutation function +void +GeneratePermutation(byte& generatorVal1, byte& generatorVal2, byte& generatorVal3, byte& generatorVal4, byte& intermediateDataVal, unsigned int cryptoVariable) +{ + intermediateDataVal = static_cast< byte >(cryptoVariable); + intermediateDataVal = generatorVal2 ^ intermediateDataVal; + + generatorVal3 = _FIELD_TABLE[static_cast< unsigned int >(intermediateDataVal) >> _ONE_WORD_VAL][static_cast< unsigned int >(intermediateDataVal) % _TWO_BYTE_VAL] ^ generatorVal1; + + intermediateDataVal = static_cast< byte >(cryptoVariable >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK; + intermediateDataVal = generatorVal3 ^ intermediateDataVal; + + generatorVal4 = _FIELD_TABLE[static_cast< unsigned int >(intermediateDataVal) >> _ONE_WORD_VAL][static_cast< unsigned int >(intermediateDataVal) % _TWO_BYTE_VAL] ^ generatorVal2; + + intermediateDataVal = static_cast< byte >(cryptoVariable >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK; + intermediateDataVal = generatorVal4 ^ intermediateDataVal; + + generatorVal1 = _FIELD_TABLE[static_cast< unsigned int >(intermediateDataVal) >> _ONE_WORD_VAL][static_cast< unsigned int >(intermediateDataVal) % _TWO_BYTE_VAL] ^ generatorVal3; + + intermediateDataVal = static_cast< byte >(cryptoVariable >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK; + intermediateDataVal = generatorVal1 ^ intermediateDataVal; + + generatorVal2 = _FIELD_TABLE[static_cast< unsigned int >(intermediateDataVal) >> _ONE_WORD_VAL][static_cast< unsigned int >(intermediateDataVal) % _TWO_BYTE_VAL] ^ generatorVal4; +} + +//This macro defines the procedure for implemeting inverse G - permutation function +void +GenerateInversePermutation(byte& generatorVal4, byte& generatorVal3, byte& generatorVal2, byte& generatorVal1, byte& intermediateDataVal, unsigned int cryptoVariable) +{ + intermediateDataVal = static_cast< byte >(cryptoVariable >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK; + intermediateDataVal = generatorVal3 ^ intermediateDataVal; + + generatorVal2 = _FIELD_TABLE[static_cast< unsigned int >(intermediateDataVal) >> _ONE_WORD_VAL][static_cast< unsigned int >(intermediateDataVal) % _TWO_BYTE_VAL] ^ generatorVal4; + + intermediateDataVal = static_cast< byte >(cryptoVariable >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK; + intermediateDataVal = generatorVal2 ^ intermediateDataVal; + + generatorVal1 = _FIELD_TABLE[static_cast< unsigned int >(intermediateDataVal) >> _ONE_WORD_VAL][static_cast< unsigned int >(intermediateDataVal) % _TWO_BYTE_VAL] ^ generatorVal3; + + intermediateDataVal = static_cast< byte >(cryptoVariable >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK; + intermediateDataVal = generatorVal1 ^ intermediateDataVal; + + generatorVal4 = _FIELD_TABLE[static_cast< unsigned int >(intermediateDataVal) >> _ONE_WORD_VAL][static_cast< unsigned int >(intermediateDataVal) % _TWO_BYTE_VAL] ^ generatorVal2; + + intermediateDataVal = static_cast< byte >(cryptoVariable); + intermediateDataVal = generatorVal4 ^ intermediateDataVal; + + generatorVal3 = _FIELD_TABLE[static_cast< unsigned int >(intermediateDataVal) >> _ONE_WORD_VAL][static_cast< unsigned int >(intermediateDataVal) % _TWO_BYTE_VAL] ^ generatorVal1; +} + +// This function is for encryption and decryption process for cbc mode +// Defining Initialization vector is necessary for this mode +void +_SkipJackCore::DoCipherCbc(const byte* pIn, byte* pOut, long length, SkipJackKey& ks, const byte* pIv, bool encrypt) +{ + unsigned long inputLongVal = 0; + unsigned long inputVal[_DATA_ARRAY_SIZE] = {0, 0}; + unsigned long ivVal[_DATA_ARRAY_SIZE] = {0, 0}; + + //changing iv into 32 bit variable + TransformByteToLong(pIv, inputLongVal); + ivVal[0] = inputLongVal; + + TransformByteToLong(pIv, inputLongVal); + ivVal[1] = inputLongVal; + + //changing input into 32 bits + TransformByteToLong(pIn, inputLongVal); + inputVal[0] = inputLongVal; + + TransformByteToLong(pIn, inputLongVal); + inputVal[1] = inputLongVal; + + if (encrypt) + { + //xoring plaintext and iv + inputVal[0] = (ivVal[0] ^ inputVal[0]) & _FOUR_BYTE_MASK; + inputVal[1] = (ivVal[1] ^ inputVal[1]) & _FOUR_BYTE_MASK; + + // calling encryption function + _SkipJackCore::Encrypt(inputVal, ks); + } + else + { + //calling decrypt function + _SkipJackCore::Decrypt(inputVal, ks); + + //xoring plaintext and iv + inputVal[0] = (ivVal[0] ^ inputVal[0]) & _FOUR_BYTE_MASK; + inputVal[1] = (ivVal[1] ^ inputVal[1]) & _FOUR_BYTE_MASK; + + } + + // changing output into 8 bit streams + inputLongVal = inputVal[0]; + TransformLongToByte(inputLongVal, pOut); + + inputLongVal = inputVal[1]; + TransformLongToByte(inputLongVal, pOut); +} + +//This function is for carrying out encryption and decryption for ecb mode +void +_SkipJackCore::DoCipherEcb(const byte* pIn, byte* pOut, SkipJackKey& ks, bool encrypt) +{ + unsigned long inputLongVal = 0; + unsigned long inputVal[_DATA_ARRAY_SIZE] = {0, 0}; + + TransformByteToLong(pIn, inputLongVal); + inputVal[0] = inputLongVal; + + TransformByteToLong(pIn, inputLongVal); + inputVal[1] = inputLongVal; + + if (encrypt) + { + _SkipJackCore::Encrypt(inputVal, ks); + } + else + { + _SkipJackCore::Decrypt(inputVal, ks); + } + + inputLongVal = inputVal[0]; + TransformLongToByte(inputLongVal, pOut); + + inputLongVal = inputVal[1]; + TransformLongToByte(inputLongVal, pOut); + +} + +//This is the underlining encryption operation that is carried out for both ecb and cbc mode +//Total of 32 steps would be carried out in total out of which 16 steps are of Rule A and rest 16 are of rule B +void +_SkipJackCore::Encrypt(unsigned long* pData, SkipJackKey& key) +{ + int index = 0; + int counter = 0; + unsigned int cryptoVariable = 0; + unsigned int inputDataVal[_DATA_ARRAY_SIZE] = {0, 0}; + //unsigned long* pData = reinterpret_cast< unsigned long* >(pDataLongValue); + byte intermediateDataVal = 0; + byte generatorVal1 = 0; + byte generatorVal2 = 0; + byte generatorVal3 = 0; + byte generatorVal4 = 0; + + while (counter != _FOUR_BYTE_VAL) + { + //index=0; + for (index = 0; index < _ONE_BYTE_VAL; index++) + { + //The 1st 8 steps and 3rd 8 steps are carried out using Rule A for encryption + cryptoVariable = static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter) % _SKIPJACK_KEY_LENGTH]) | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_ONE_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_ONE_BYTE | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_TWO_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_TWO_BYTE | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_THREE_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_THREE_BYTE; + + generatorVal1 = static_cast< byte >(pData[0]); + generatorVal2 = static_cast< byte >(pData[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK; + + GeneratePermutation(generatorVal1, generatorVal2, generatorVal3, generatorVal4, intermediateDataVal, cryptoVariable); //For G(w1) + + inputDataVal[0] = (static_cast< unsigned int >(generatorVal1 << _SHIFT_ONE_BYTE) | static_cast< unsigned int >(generatorVal2)) & _TWO_BYTE_MASK; + + inputDataVal[1] = inputDataVal[0]; + counter = counter + 1; + inputDataVal[0] = inputDataVal[0] ^ ((((pData[1] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | + pData[1] >> _SHIFT_THREE_BYTE) & _TWO_BYTE_MASK) ^ counter; // G(w1) ^ w4 ^ counter + + inputDataVal[0] = ((inputDataVal[0] << _SHIFT_TWO_BYTE) | inputDataVal[1]) & _FOUR_BYTE_MASK; + + inputDataVal[1] = ((pData[0] >> _SHIFT_TWO_BYTE) << _SHIFT_ONE_BYTE | pData[0] >> _SHIFT_THREE_BYTE) << _SHIFT_TWO_BYTE | + (((pData[1] & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE) | (((pData[1] >> _SHIFT_ONE_BYTE)) & _ONE_BYTE_MASK)); // (w2 | w3) + + pData[0] = (inputDataVal[0] & _ONE_BYTE_MASK) << _SHIFT_THREE_BYTE | ((inputDataVal[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK) << _SHIFT_TWO_BYTE | ((inputDataVal[0] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | ((inputDataVal[0] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); + pData[1] = (inputDataVal[1] & _ONE_BYTE_MASK) << _SHIFT_THREE_BYTE | ((inputDataVal[1] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK) << _SHIFT_TWO_BYTE | ((inputDataVal[1] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | ((inputDataVal[1] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); + } + + for (index = _ONE_BYTE_VAL; index < _TWO_BYTE_VAL; index++) + { + //The 2nd 8 steps and 4th 8 Steps are carried out using Rule B for encryption + cryptoVariable = static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter) % _SKIPJACK_KEY_LENGTH]) | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_ONE_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_ONE_BYTE | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_TWO_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_TWO_BYTE | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_THREE_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_THREE_BYTE; + + generatorVal1 = static_cast< byte >(pData[0]); + generatorVal2 = static_cast< byte >(pData[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK; + + GeneratePermutation(generatorVal1, generatorVal2, generatorVal3, generatorVal4, intermediateDataVal, cryptoVariable); //G(w1) + + counter = counter + 1; + inputDataVal[0] = (static_cast< unsigned int >(generatorVal1 << _SHIFT_ONE_BYTE) | static_cast< unsigned int >(generatorVal2)) & _TWO_BYTE_MASK; + + inputDataVal[0] = ((inputDataVal[0]) | ((pData[1] >> _SHIFT_TWO_BYTE) << _SHIFT_ONE_BYTE | + pData[1] >> _SHIFT_THREE_BYTE) << _SHIFT_TWO_BYTE) & _FOUR_BYTE_MASK; // (w4 | G(w1)) + + inputDataVal[1] = ((pData[0] << _SHIFT_ONE_BYTE | ((pData[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK)) & _TWO_BYTE_MASK) ^ + (((pData[0] >> _SHIFT_TWO_BYTE) << _SHIFT_ONE_BYTE | (pData[0] >> _SHIFT_THREE_BYTE)) & _TWO_BYTE_MASK) ^ + counter; // w1 ^ w2 ^ counter + + inputDataVal[1] = inputDataVal[1] << _SHIFT_TWO_BYTE | ((pData[1] & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | + ((pData[1] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK)); + + pData[0] = (inputDataVal[0] & _ONE_BYTE_MASK) << _SHIFT_THREE_BYTE | ((inputDataVal[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK) << _SHIFT_TWO_BYTE | ((inputDataVal[0] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | ((inputDataVal[0] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); + pData[1] = (inputDataVal[1] & _ONE_BYTE_MASK) << _SHIFT_THREE_BYTE | ((inputDataVal[1] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK) << _SHIFT_TWO_BYTE | ((inputDataVal[1] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | ((inputDataVal[1] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); + } + } +} + +//This is the underlining decryption operation that is carried out for both ecb and cbc mode +//Total of 32 steps would be carried out in total out of which 16 steps are of Rule B inverse and rest 16 are of rule A inverse +void +_SkipJackCore::Decrypt(unsigned long* pData, SkipJackKey& key) +{ + int index = 0; + int counter = _FOUR_BYTE_VAL; + unsigned int cryptoVariable = 0; + unsigned int inputDataVal[_DATA_ARRAY_SIZE] = {0, 0}; + //unsigned long* pData = reinterpret_cast< unsigned long* >(pDataLongValue); + byte intermediateDataVal = 0; + byte generatorVal1 = 0; + byte generatorVal2 = 0; + byte generatorVal3 = 0; + byte generatorVal4 = 0; + + while (counter > 0) + { + //index=0; + for (index = 0; index < _ONE_BYTE_VAL; index++) + { + //The 1st 8 steps and 3rd 8 Steps are carried out using Rule B inverse for decryption + counter = counter - 1; + cryptoVariable = static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter) % _SKIPJACK_KEY_LENGTH]) | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_ONE_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_ONE_BYTE | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_TWO_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_TWO_BYTE | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_THREE_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_THREE_BYTE; + + generatorVal1 = static_cast< byte >(pData[0] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK; + generatorVal2 = static_cast< byte >(pData[0] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK; + + GenerateInversePermutation(generatorVal1, generatorVal2, generatorVal3, generatorVal4, intermediateDataVal, cryptoVariable); + + inputDataVal[0] = (static_cast< unsigned int >(generatorVal2 << _SHIFT_ONE_BYTE) | static_cast< unsigned int >(generatorVal1)) & _TWO_BYTE_MASK; //G(w2) + + inputDataVal[1] = inputDataVal[0] ^ ((pData[1] & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | + ((pData[1] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK)) ^ (counter + _INCREMENT_ONE_BYTE); //G(w2) ^ w3 ^ counter + inputDataVal[0] = (inputDataVal[0] << _SHIFT_TWO_BYTE | inputDataVal[1]) & _FOUR_BYTE_MASK; // (G(w2) | inputDataVal[1]) + + inputDataVal[1] = ((pData[1] >> _SHIFT_TWO_BYTE) << _SHIFT_ONE_BYTE | pData[1] >> _SHIFT_THREE_BYTE) << _SHIFT_TWO_BYTE | + ((pData[0] << _SHIFT_ONE_BYTE | ((pData[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK)) & _TWO_BYTE_MASK); // (w4 | w1) + + pData[0] = (inputDataVal[0] & _ONE_BYTE_MASK) << _SHIFT_THREE_BYTE | ((inputDataVal[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK) << _SHIFT_TWO_BYTE | ((inputDataVal[0] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | ((inputDataVal[0] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); + pData[1] = (inputDataVal[1] & _ONE_BYTE_MASK) << _SHIFT_THREE_BYTE | ((inputDataVal[1] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK) << _SHIFT_TWO_BYTE | ((inputDataVal[1] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | ((inputDataVal[1] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); + } + + for (index = _ONE_BYTE_VAL; index < _TWO_BYTE_VAL; index++) + { + //The 2nd 8 steps and 4th 8 Steps are carried out using Rule A inverse for decryption + counter = counter - 1; + cryptoVariable = static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter) % _SKIPJACK_KEY_LENGTH]) | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_ONE_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_ONE_BYTE | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_TWO_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_TWO_BYTE | + static_cast< unsigned int >(key.keyVal[(_ONE_WORD_VAL * counter + _INCREMENT_THREE_BYTE) % _SKIPJACK_KEY_LENGTH]) << _SHIFT_THREE_BYTE; + + generatorVal1 = static_cast< byte >(pData[0] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK; + generatorVal2 = static_cast< byte >(pData[0] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK; + + GenerateInversePermutation(generatorVal1, generatorVal2, generatorVal3, generatorVal4, intermediateDataVal, cryptoVariable); // Ginv(w2) + + inputDataVal[0] = (static_cast< unsigned int >(generatorVal2 << _SHIFT_ONE_BYTE) | static_cast< unsigned int >(generatorVal1)) & _TWO_BYTE_MASK; + + inputDataVal[0] = ((inputDataVal[0] << _SHIFT_TWO_BYTE) | ((pData[1] & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | + ((pData[1] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK))) & _FOUR_BYTE_MASK; // (G(w2) | w3) + + inputDataVal[1] = ((pData[0] << _SHIFT_ONE_BYTE | ((pData[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK)) & _TWO_BYTE_MASK) ^ + (((pData[0] >> _SHIFT_TWO_BYTE) << _SHIFT_ONE_BYTE | (pData[0] >> _SHIFT_THREE_BYTE)) & _TWO_BYTE_MASK) ^ + (counter + _INCREMENT_ONE_BYTE); // w1 ^ w2 ^ counter + + inputDataVal[1] = ((pData[1] >> _SHIFT_TWO_BYTE) << _SHIFT_ONE_BYTE | pData[1] >> _SHIFT_THREE_BYTE) << _SHIFT_TWO_BYTE | inputDataVal[1]; // (w4 | inputDataVal[1]) + + pData[0] = (inputDataVal[0] & _ONE_BYTE_MASK) << _SHIFT_THREE_BYTE | ((inputDataVal[0] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK) << _SHIFT_TWO_BYTE | ((inputDataVal[0] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | ((inputDataVal[0] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); + pData[1] = (inputDataVal[1] & _ONE_BYTE_MASK) << _SHIFT_THREE_BYTE | ((inputDataVal[1] >> _SHIFT_ONE_BYTE) & _ONE_BYTE_MASK) << _SHIFT_TWO_BYTE | ((inputDataVal[1] >> _SHIFT_TWO_BYTE) & _ONE_BYTE_MASK) << _SHIFT_ONE_BYTE | ((inputDataVal[1] >> _SHIFT_THREE_BYTE) & _ONE_BYTE_MASK); + } + } +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCrypto_SkipJackCore.h b/src/security/crypto/FSecCrypto_SkipJackCore.h new file mode 100644 index 0000000..738271e --- /dev/null +++ b/src/security/crypto/FSecCrypto_SkipJackCore.h @@ -0,0 +1,58 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto_SkipJackCore.h + * @brief This header file contains declarations of SkipJack Core encryption and decryption algorithms. + */ +#ifndef _FSEC_CRYPTO_INTERNAL_SKIPJACKCORE_H_ +#define _FSEC_CRYPTO_INTERNAL_SKIPJACKCORE_H_ + +static const int _SKIPJACK_BLOCK_DATA_SIZE = 8; +static const int _SKIPJACK_KEY_LENGTH = 10; // Key length is 10 bytes + + +namespace Tizen { namespace Security { namespace Crypto +{ + +struct SkipJackKey +{ + // Number of rounds + byte iv[_SKIPJACK_BLOCK_DATA_SIZE]; + byte keyVal[_SKIPJACK_KEY_LENGTH]; +}; + +class _SkipJackCore +{ + +public: + static void DoCipherCbc(const byte* pIn, byte* pOut, long length, SkipJackKey& ks, const byte* pIv, bool encFlag); + static void DoCipherEcb(const byte* pIn, byte* pOut, SkipJackKey& key, bool encFlag); + static void Encrypt(unsigned long* pData, SkipJackKey& key); + static void Decrypt(unsigned long* pData, SkipJackKey& key); + +private: + _SkipJackCore(void); + _SkipJackCore(const _SkipJackCore& rhs); + _SkipJackCore& operator =(const _SkipJackCore& rhs); + ~_SkipJackCore(void); + +}; //_SkipJackCore + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_INTERNAL_SKIPJACKCORE_H_ diff --git a/src/security/crypto/FSecCrypto_SkipJackModes.cpp b/src/security/crypto/FSecCrypto_SkipJackModes.cpp new file mode 100644 index 0000000..52c676e --- /dev/null +++ b/src/security/crypto/FSecCrypto_SkipJackModes.cpp @@ -0,0 +1,200 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto_SkipJackModes.cpp + * @brief This file contains implementation of various block cipher modes of SkipJack encryption and decryption operation (like CBC and ECB modes). + */ +#include +#include +#include +#include "FSecCrypto_SkipJackCore.h" +#include "FSecCrypto_SkipJackModes.h" + +static const int _SKIPJACK_NID_ = 101; +static const int _SKIPJACK_IV_DATA_SIZE = 8; + +//These functions are callbacks for openSSL libraries. +//The signatures and their respective return values cannot be altered. +//Therefore, we need to have unsigned int in the Last input parameter for DoSkipJackCipherCbc80 & DoSkipJackCipherEcb80. +static int InitSkipJackCbcKey80(EVP_CIPHER_CTX* pCtx, const byte* pKey, const byte* pIv, int encFlag); +static int DoSkipjackCipherCbc80(EVP_CIPHER_CTX* pCtx, byte* pOut, const byte* pIn, unsigned int inLen); +static int InitSkipJackEcbKey80(EVP_CIPHER_CTX* pCtx, const byte* pKey, const byte* pIv, int encFlag); +static int DoSkipjackCipherEcb80(EVP_CIPHER_CTX* pCtx, byte* pOut, const byte* pIn, unsigned int inLen); + +// SKIPJACK CBC Mode 80 bits +static const EVP_CIPHER skipJackCbcCipher80 = +{ + _SKIPJACK_NID_, _SKIPJACK_BLOCK_DATA_SIZE, _SKIPJACK_KEY_LENGTH, _SKIPJACK_IV_DATA_SIZE, + 0 | EVP_CIPH_CBC_MODE, + InitSkipJackCbcKey80, + DoSkipjackCipherCbc80, + null, + sizeof(Tizen::Security::Crypto::SkipJackKey), + EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, + null, + null +}; + +// SKIPJACK ECB Mode 80 bits +static const EVP_CIPHER skipJackEcbCipher80 = +{ + _SKIPJACK_NID_, _SKIPJACK_BLOCK_DATA_SIZE, _SKIPJACK_KEY_LENGTH, 0, + 0 | EVP_CIPH_ECB_MODE, + InitSkipJackEcbKey80, + DoSkipjackCipherEcb80, + null, + sizeof(Tizen::Security::Crypto::SkipJackKey), + EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, + null, + null +}; + +const EVP_CIPHER* +EvpSkipJackCbc80(void) +{ + ClearLastResult(); + + return(&skipJackCbcCipher80); +} + +int +InitSkipJackCbcKey80(EVP_CIPHER_CTX* pCtx, const byte* pKey, const byte* pIv, int encFlag) +{ + return Tizen::Security::Crypto::_SkipJackModes::InitCbcKey80(pCtx, static_cast< const byte* >(pKey), static_cast< const byte* >(pIv), + static_cast< bool >(encFlag)); +} + +int +DoSkipjackCipherCbc80(EVP_CIPHER_CTX* pCtx, byte* pOut, const byte* pIn, unsigned int inLen) +{ + return Tizen::Security::Crypto::_SkipJackModes::DoCipherCbc80(pCtx, static_cast< byte* >(pOut), static_cast< const byte* >(pIn), static_cast< int >(inLen)); +} + +const EVP_CIPHER* +EvpSkipJackEcb80(void) +{ + ClearLastResult(); + + return(&skipJackEcbCipher80); +} + +int +InitSkipJackEcbKey80(EVP_CIPHER_CTX* pCtx, const byte* pKey, const byte* pIv, int encFlag) +{ + return Tizen::Security::Crypto::_SkipJackModes::InitEcbKey80(pCtx, static_cast< const byte* >(pKey), static_cast< const byte* >(pIv), static_cast< bool >(encFlag)); +} + +int +DoSkipjackCipherEcb80(EVP_CIPHER_CTX* pCtx, byte* pOut, const byte* pIn, unsigned int inLen) +{ + return Tizen::Security::Crypto::_SkipJackModes::DoCipherEcb80(pCtx, static_cast< byte* >(pOut), static_cast< const byte* >(pIn), static_cast< int >(inLen)); +} + + +namespace Tizen { namespace Security { namespace Crypto +{ + +// called by EVP_CipherInit->EVP_EncryptInit->cipherInit +int +_SkipJackModes::InitCbcKey80(EVP_CIPHER_CTX* pCtx, const byte* pKey, const byte* pIv, bool enc) +{ + EVP_CIPHER_CTX* pCtxSsl = pCtx; + SkipJackKey* pSkipJackKey = static_cast< SkipJackKey* >(pCtxSsl->cipher_data); + + memcpy(&(pSkipJackKey->keyVal), pKey, _SKIPJACK_KEY_LENGTH); + memcpy(&(pSkipJackKey->iv), pIv, _SKIPJACK_IV_DATA_SIZE); + + return 1; +} + +int +_SkipJackModes::DoCipherCbc80(EVP_CIPHER_CTX* pCtx, byte* pOut, const byte* pIn, int inl) +{ + int blockCount = 0; + byte* pIv = null; + byte temp[_SKIPJACK_BLOCK_DATA_SIZE] = {0, }; + EVP_CIPHER_CTX* pCtxSsl = pCtx; + SkipJackKey* pSkipJackKey = static_cast< SkipJackKey* >(pCtxSsl->cipher_data); + + pIv = pSkipJackKey->iv; + + inl = inl / _SKIPJACK_BLOCK_DATA_SIZE; + + if (pCtxSsl->encrypt) + { + for (blockCount = 0; blockCount < inl; blockCount++) + { + memset(temp, 0x00, _SKIPJACK_BLOCK_DATA_SIZE); + _SkipJackCore::DoCipherCbc(pIn, temp, _SKIPJACK_BLOCK_DATA_SIZE * _SKIPJACK_BLOCK_DATA_SIZE, *pSkipJackKey, pIv, 1); + memcpy(pOut, temp, _SKIPJACK_BLOCK_DATA_SIZE); + pIv = pOut; + pIn += _SKIPJACK_BLOCK_DATA_SIZE; + pOut += _SKIPJACK_BLOCK_DATA_SIZE; + } + } + else + { + for (blockCount = 0; blockCount < inl; blockCount++) + { + memset(temp, 0x00, _SKIPJACK_BLOCK_DATA_SIZE); + _SkipJackCore::DoCipherCbc(pIn, temp, _SKIPJACK_BLOCK_DATA_SIZE * _SKIPJACK_BLOCK_DATA_SIZE, *pSkipJackKey, pIv, 0); + memcpy(pOut, temp, _SKIPJACK_BLOCK_DATA_SIZE); + pIv = const_cast< byte* >(pIn); + pIn += _SKIPJACK_BLOCK_DATA_SIZE; + pOut += _SKIPJACK_BLOCK_DATA_SIZE; + } + } + + memcpy(pSkipJackKey->iv, pIv, _SKIPJACK_BLOCK_DATA_SIZE); + + return 1; +} + +int +_SkipJackModes::InitEcbKey80(EVP_CIPHER_CTX* pCtx, const byte* pKey, const byte* pIv, bool encFlag) +{ + EVP_CIPHER_CTX* pCtxSsl = pCtx; + SkipJackKey* pSkipJackKey = static_cast< SkipJackKey* >(pCtxSsl->cipher_data); + + memcpy(&(pSkipJackKey->keyVal), pKey, _SKIPJACK_KEY_LENGTH); + + return 1; +} + +int +_SkipJackModes::DoCipherEcb80(EVP_CIPHER_CTX* pCtx, byte* pOut, const byte* pIn, int inl) +{ + int blockCount = 0; + byte temp[_SKIPJACK_BLOCK_DATA_SIZE] = {0, }; + EVP_CIPHER_CTX* pCtxSsl = pCtx; + SkipJackKey* pSkipJackKey = static_cast< SkipJackKey* >(pCtxSsl->cipher_data); + + inl = inl / _SKIPJACK_BLOCK_DATA_SIZE; + + for (blockCount = 0; blockCount < inl; blockCount++) + { + memset(temp, 0x00, _SKIPJACK_BLOCK_DATA_SIZE); + _SkipJackCore::DoCipherEcb(pIn, temp, *pSkipJackKey, pCtxSsl->encrypt); + memcpy(pOut, temp, _SKIPJACK_BLOCK_DATA_SIZE); + pIn += _SKIPJACK_BLOCK_DATA_SIZE; + pOut += _SKIPJACK_BLOCK_DATA_SIZE; + } + + return 1; +} +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCrypto_SkipJackModes.h b/src/security/crypto/FSecCrypto_SkipJackModes.h new file mode 100644 index 0000000..e92b02b --- /dev/null +++ b/src/security/crypto/FSecCrypto_SkipJackModes.h @@ -0,0 +1,49 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto_SkipJackModes.h + * @brief This header file contains declarations of various block cipher modes of SkipJack encryption and decryption operation (like CBC and ECB modes). + */ +#ifndef _FSEC_CRYPTO_INTERNAL_SKIPJACKMODES_H_ +#define _FSEC_CRYPTO_INTERNAL_SKIPJACKMODES_H_ + +struct evp_cipher_ctx_st; + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SkipJackModes +{ + +public: + static int InitCbcKey80(evp_cipher_ctx_st* pCtx, const byte* pKey, const byte* pIv, bool encFlag); + static int DoCipherCbc80(evp_cipher_ctx_st* pCtx, byte* pOut, const byte* pIn, int inl); + static int InitEcbKey80(evp_cipher_ctx_st* pCtx, const byte* pKey, const byte* pIv, bool encFlag); + static int DoCipherEcb80(evp_cipher_ctx_st* pCtx, byte* pOut, const byte* pIn, int inl); + +private: + _SkipJackModes(void); + _SkipJackModes(const _SkipJackModes& rhs); + _SkipJackModes& operator =(const _SkipJackModes& rhs); + ~_SkipJackModes(void); + +}; //_SkipJackModes + +} } } //Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_INTERNAL_SKIPJACKMODES_H_ diff --git a/src/security/crypto/FSecCrypto_SymmetricCipher.cpp b/src/security/crypto/FSecCrypto_SymmetricCipher.cpp new file mode 100644 index 0000000..bfa3e40 --- /dev/null +++ b/src/security/crypto/FSecCrypto_SymmetricCipher.cpp @@ -0,0 +1,742 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto_SymmetricCipher.cpp + * @brief This is implementation file of common operations for Symmetric Ciphers available. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "FSecCrypto_SkipJackModes.h" +#include "FSecCrypto_SymmetricCipher.h" + +using namespace Tizen::Base; + + +namespace Tizen { namespace Security { namespace Crypto +{ +static const int _BITS_IN_BYTE = 8; +static const int _AES_DATA_BLOCK_LENGTH = 16; +static const int _MAX_AES_KEY_DATA_LENGTH = 32; +static const int _MAX_AES_WRAP_DATA_LENGTH = 40; +static const int _MIN_UNWRAP_KEY_LEN_REFACTOR = 2; +static const int _MIN_WRAP_KEY_LEN_REFACTOR = 3; +static const int _MAX_LOOP_LEN_UNWRAP = 5; +static const int _MAX_LOOP_LEN_WRAP = 6; +static const int _MAX_LOOP_VAL = 7; +static const int _AES_128_KEY_LEN = 16; +static const int _AES_192_KEY_LEN = 24; +static const int _AES_256_KEY_LEN = 32; + +static const byte IV[_BITS_IN_BYTE] = +{ + 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6 +}; + +_SymmetricCipher::_SymmetricCipher(void) + : __pCipherAlgorithm(EVP_aes_128_cbc()) // Default is AES/CBC/128 + , __pCipherCtx(null) + , __opMode(CIPHER_ENCRYPT) // Default is encryption. + , __padding(false) +{ +} + +_SymmetricCipher::~_SymmetricCipher(void) +{ +} + +result +_SymmetricCipher::SetTransformation(const EVP_CIPHER* pCipherAlgorithm, bool padding) +{ + __pCipherAlgorithm = pCipherAlgorithm; + + __padding = padding; + + return E_SUCCESS; +} + +result +_SymmetricCipher::SetCipherOperation(CipherOperation opMode) +{ + //Setting the cipher opeartion that needs to be carried out + __opMode = opMode; + + return E_SUCCESS; +} + +result +_SymmetricCipher::SetKey(const Tizen::Security::ISecretKey& key) +{ + result r = E_SUCCESS; + + // convert the ISecretKey to ByteBuffer + std::unique_ptr pBuffer (key.GetEncodedN()); + SysTryReturn(NID_SEC_CRYPTO, pBuffer != null, GetLastResult(), GetLastResult(), "[%s] Allocating new ByteBuffer failed.", GetErrorMessage(GetLastResult())); + + // Sets the key + r = __keyBytes.Construct(*pBuffer); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Key data is not valid.", GetErrorMessage(r)); + + return r; +} + +result +_SymmetricCipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector) +{ + result r = E_SUCCESS; + + SysTryReturn(NID_SEC_CRYPTO, initialVector.GetRemaining() > 0 && initialVector.GetPointer() != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The input iv data should be valid and the iv length should be positive."); + + //Sets the initial vector + r = __initVector.Construct(initialVector); + SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Initialization vector data is not valid.", GetErrorMessage(r)); + + return r; +} + +ByteBuffer* +_SymmetricCipher::DoCipherN(const Tizen::Base::ByteBuffer& input, bool variableKeyFlag) +{ + result r = E_SUCCESS; + int ret = 0; + int dataLen = 0; + int keyLen = 0; + int ivLen = 0; + int outLen = 0; + int tempLen = 0; + int finalLen = 0; + byte* pData = null; + byte* pKey = null; + byte* pIv = null; + std::unique_ptr pOutput; + EVP_CIPHER_CTX cipherCtx; + + ClearLastResult(); + + SysAssertf(__pCipherAlgorithm != null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class"); + + SysTryReturn(NID_SEC_CRYPTO, __opMode == CIPHER_ENCRYPT || __opMode == CIPHER_DECRYPT, null, E_INVALID_OPERATION, "[E_INVALID_OPERATION] This function is for encryption and decryption purpose."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + // If the input length is not a multiple of block size, and the padding is false, then, return error. + if (__padding == false) + { + SysTryReturn(NID_SEC_CRYPTO, dataLen % __pCipherAlgorithm->block_size == 0, null, E_INVALID_OPERATION, "[E_INVALID_OPERATION] The input data length is not a multiple of algorithm data blocksize."); + } + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key value should be valid."); + + keyLen = __keyBytes.GetRemaining(); + + if (__initVector.GetRemaining() > 0) + { + pIv = const_cast< byte* >(__initVector.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pIv != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Initialization vector should be valid."); + + ivLen = __initVector.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, ivLen >= __pCipherAlgorithm->iv_len, null, E_INVALID_ARG, + "[E_INVALID_ARG] Input iv length should be >= algorithm iv length."); + } + + // block size + tempLen = static_cast< int >((dataLen / __pCipherAlgorithm->block_size + 1) * __pCipherAlgorithm->block_size); + + std::unique_ptr pOutBuf (new (std::nothrow) byte[tempLen]); + SysTryReturn(NID_SEC_CRYPTO, pOutBuf != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + memset(pOutBuf.get(), 0, tempLen); + + // Selects the encryption algorithm using EVP class + EVP_CIPHER_CTX_init(&cipherCtx); + + if (__opMode == CIPHER_ENCRYPT) + { + if (variableKeyFlag) + { + ret = EVP_CipherInit(&cipherCtx, __pCipherAlgorithm, null, null, 1); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + EVP_CIPHER_CTX_set_key_length(&cipherCtx, keyLen); + + ret = EVP_CipherInit(&cipherCtx, null, pKey, pIv, 1); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + else + { + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, __pCipherAlgorithm, pKey, pIv, 1); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + } + else if (__opMode == CIPHER_DECRYPT) + { + if (variableKeyFlag) + { + ret = EVP_CipherInit(&cipherCtx, __pCipherAlgorithm, null, null, 0); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + EVP_CIPHER_CTX_set_key_length(&cipherCtx, keyLen); + + ret = EVP_CipherInit(&cipherCtx, null, pKey, pIv, 0); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + else + { + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, __pCipherAlgorithm, pKey, pIv, 0); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + } + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, static_cast< int >(__padding)); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, pOutBuf.get(), static_cast< int* >(&outLen), pData, dataLen); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher final operation + ret = EVP_CipherFinal(&cipherCtx, pOutBuf.get() + outLen, &finalLen); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + outLen = outLen + finalLen; + + SysTryCatch(NID_SEC_CRYPTO, outLen <= tempLen, r = E_OVERFLOW, E_OVERFLOW, "[E_OVERFLOW] Length mismatch resulting in overflow."); + + //creating bytebuffer and storing output data from cipher final operation in it + pOutput = std::unique_ptr (new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new ByteBuffer failed."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pOutBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + EVP_CIPHER_CTX_cleanup(&cipherCtx); + + return pOutput.release(); +} + +result +_SymmetricCipher::Initialize(bool variableKeyFlag) +{ + result r = E_SUCCESS; + int ret = 0; + int keyLen = 0; + int ivLen = 0; + byte* pKey = null; + byte* pIv = null; + + SysAssertf(__pCipherAlgorithm != null && __pCipherCtx == null, "Not yet constructed. Construct() should be called before use."); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, E_KEY_NOT_FOUND, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key value should be valid."); + + keyLen = __keyBytes.GetRemaining(); + + if (__initVector.GetRemaining() > 0) + { + pIv = const_cast< byte* >(__initVector.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pIv != null, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Initialization vector should be valid."); + + ivLen = __initVector.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, ivLen >= __pCipherAlgorithm->iv_len, E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] Input iv length should be >= algorithm iv length."); + } + + __pCipherCtx = std::unique_ptr (new (std::nothrow) EVP_CIPHER_CTX()); + SysTryReturn(NID_SEC_CRYPTO, __pCipherCtx != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new cipher context object failed."); + + EVP_CIPHER_CTX_init(__pCipherCtx.get()); + + if (__opMode == CIPHER_ENCRYPT) + { + if (variableKeyFlag) + { + ret = EVP_CipherInit(__pCipherCtx.get(), __pCipherAlgorithm, null, null, 1); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + EVP_CIPHER_CTX_set_key_length(__pCipherCtx.get(), keyLen); + + ret = EVP_CipherInit(__pCipherCtx.get(), null, pKey, pIv, 1); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + else + { + ret = EVP_CipherInit(__pCipherCtx.get(), __pCipherAlgorithm, pKey, pIv, 1); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + } + else if (__opMode == CIPHER_DECRYPT) + { + if (variableKeyFlag) + { + ret = EVP_CipherInit(__pCipherCtx.get(), __pCipherAlgorithm, null, null, 0); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + EVP_CIPHER_CTX_set_key_length(__pCipherCtx.get(), keyLen); + + ret = EVP_CipherInit(__pCipherCtx.get(), null, pKey, pIv, 0); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + else + { + ret = EVP_CipherInit(__pCipherCtx.get(), __pCipherAlgorithm, pKey, pIv, 0); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + } + } + else + { + return E_INVALID_OPERATION; + } + + ret = EVP_CIPHER_CTX_set_padding(__pCipherCtx.get(), static_cast< int >(__padding)); + SysTryReturn(NID_SEC_CRYPTO, ret == 1, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + return r; +} + +ByteBuffer* +_SymmetricCipher::UpdateN(const Tizen::Base::ByteBuffer& input) +{ + result r = E_SUCCESS; + int ret = 0; + int dataLen = 0; + int outLen = 0; + int tempLen = 0; + byte* pData = null; + std::unique_ptr pOutput; + + ClearLastResult(); + + SysAssertf(__pCipherAlgorithm != null && __pCipherCtx != null, "Not yet constructed. Construct() should be called before use."); + + pData = const_cast< byte* >(input.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data should be valid."); + + dataLen = input.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Input data length should be positive."); + + tempLen = static_cast< int >((dataLen / __pCipherAlgorithm->block_size + 1) * __pCipherAlgorithm->block_size); + + std::unique_ptr pOutBuf (new (std::nothrow) byte[tempLen]); + SysTryReturn(NID_SEC_CRYPTO, pOutBuf != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + memset(pOutBuf.get(), 0, tempLen); + + ret = EVP_CipherUpdate(__pCipherCtx.get(), pOutBuf.get(), static_cast< int* >(&outLen), pData, dataLen); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + SysTryCatch(NID_SEC_CRYPTO, outLen <= tempLen, r = E_OVERFLOW, E_OVERFLOW, "[E_OVERFLOW] Overflow since output data length > input data length."); + + pOutput = std::unique_ptr (new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new ByteBuffer failed."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pOutBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + return pOutput.release(); +} + +ByteBuffer* +_SymmetricCipher::FinalizeN(void) +{ + result r = E_SUCCESS; + int ret = 0; + int outLen = 0; + int tempLen = 0; + std::unique_ptr pOutput; + + ClearLastResult(); + + SysAssertf(__pCipherCtx != null, "Not yet constructed. Construct() should be called before use."); + + SysTryReturn(NID_SEC_CRYPTO, __pCipherCtx->cipher != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Cipher context algorithm should be valid."); + + tempLen = __pCipherCtx->cipher->block_size; + SysTryReturn(NID_SEC_CRYPTO, tempLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Cipher context algorithm blocksize should be positive."); + + std::unique_ptr pOutBuf (new (std::nothrow) byte[tempLen]); + SysTryReturn(NID_SEC_CRYPTO, pOutBuf != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed."); + + memset(pOutBuf.get(), 0, tempLen); + + ret = EVP_CipherFinal(__pCipherCtx.get(), pOutBuf.get(), static_cast< int* >(&outLen)); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + SysTryCatch(NID_SEC_CRYPTO, outLen <= tempLen, r = E_OVERFLOW, E_OVERFLOW, "[E_OVERFLOW] Overflow since output data length > input data length."); + + pOutput = std::unique_ptr (new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutput != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new ByteBuffer failed."); + + r = pOutput->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutput->SetArray(pOutBuf.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutput->Flip(); + +CATCH: + + EVP_CIPHER_CTX_cleanup(__pCipherCtx.get()); + + __pCipherCtx.reset(null); + + return pOutput.release(); +} + +ByteBuffer* +_SymmetricCipher::WrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + ClearLastResult(); + + if (__opMode != CIPHER_WRAP) + { + SetLastResult(E_INVALID_OPERATION); + return null; + } + + return DoWrapN(secretKey); +} + +ByteBuffer* +_SymmetricCipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + ClearLastResult(); + + if (__opMode != CIPHER_UNWRAP) + { + SetLastResult(E_INVALID_OPERATION); + return null; + } + + return DoUnwrapN(wrappedKey); +} + +ByteBuffer* +_SymmetricCipher::DoWrapN(const Tizen::Base::ByteBuffer& secretKey) +{ + result r = E_SUCCESS; + int ret = 0; + int numVal = 0; + int tempVal = 0; + int finalLen = 0; + int keyLen = 0; + int outLen = 0; + int dataLen = 0; + char index = null; + char count = null; + byte tempB[_AES_DATA_BLOCK_LENGTH] = {'\0'}; // Temp buffer for Receiving AES o/p + byte tempBuf[_AES_DATA_BLOCK_LENGTH] = {'\0'}; + byte* pData = null; + byte* pKey = null; + byte* pTemp = null; // For In place calculation + std::unique_ptr pOut; + std::unique_ptr pOutBuf; + EVP_CIPHER_CTX cipherCtx; + const EVP_CIPHER* pEncryptionAlgorithm = null; + + ClearLastResult(); + + pData = const_cast< byte* >(secretKey.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Secret key data should be valid."); + + dataLen = secretKey.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Secret key length should be positive."); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key data should be valid."); + + keyLen = __keyBytes.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen > 0, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + // The data to be wrapped should be atleast 128-bit + numVal = dataLen / _BITS_IN_BYTE; +// SysTryReturn(NID_SEC_CRYPTO, numVal > _MIN_UNWRAP_KEY_LEN_REFACTOR && dataLen < _MAX_AES_KEY_DATA_LENGTH, null, E_SYSTEM, "[E_SYSTEM] An Unexpected system error occurred."); + + + if (numVal < _MIN_UNWRAP_KEY_LEN_REFACTOR || dataLen > _MAX_AES_KEY_DATA_LENGTH) + { + r = E_SYSTEM; + SysLogException(NID_SEC_CRYPTO, r, "An Unexpected system error occurred."); + goto CATCH; + } + + + switch (keyLen) + { + case _AES_128_KEY_LEN: + pEncryptionAlgorithm = EVP_aes_128_ecb(); + break; + + case _AES_192_KEY_LEN: + pEncryptionAlgorithm = EVP_aes_192_ecb(); + break; + + case _AES_256_KEY_LEN: + pEncryptionAlgorithm = EVP_aes_256_ecb(); + break; + + default: + r = E_UNSUPPORTED_ALGORITHM; + SysLogException(NID_SEC_CRYPTO, r, " The algorithm for input key length is not supported"); + goto CATCH; + } + + pOut = std::unique_ptr (new (std::nothrow) byte[dataLen + 8]); + SysTryReturn(NID_SEC_CRYPTO, pOut != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new byte array failed"); + + // Intialize variables + memcpy(pOut.get(), IV, _BITS_IN_BYTE); + pTemp = pOut.get() + _BITS_IN_BYTE; + + // Fill 64-bit register array + for (index = 0; index < numVal; index++) + { + memcpy(pTemp + index * _BITS_IN_BYTE, (pData + index * _BITS_IN_BYTE), _BITS_IN_BYTE); + } + + // Start Main loop + for (count = 0; count < _MAX_LOOP_LEN_WRAP; count++) + { + for (index = 1; index <= numVal; index++) + { + // Form A|Ri + memcpy(tempBuf, pOut.get(), _BITS_IN_BYTE); + memcpy(tempBuf + _BITS_IN_BYTE, pTemp + (index - 1) * _BITS_IN_BYTE, _BITS_IN_BYTE); + + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, pEncryptionAlgorithm, pKey, IV, 1); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, 0); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, tempB, &outLen, tempBuf, sizeof(tempBuf)); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher final operation + ret = EVP_CipherFinal(&cipherCtx, &tempB[outLen], &finalLen); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + outLen = outLen + finalLen; + + tempVal = (numVal * count) + index; + + memcpy(pOut.get(), tempB, _BITS_IN_BYTE); + pOut.get()[_MAX_LOOP_VAL] = pOut.get()[_MAX_LOOP_VAL] ^ tempVal; + + // Ri = LSB64(B) + memcpy(pTemp + (index - 1) * _BITS_IN_BYTE, &tempB[_BITS_IN_BYTE], _BITS_IN_BYTE); + + } + } + outLen = (numVal + 1) * _BITS_IN_BYTE; + + pOutBuf = std::unique_ptr (new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new ByteBuffer failed."); + + r = pOutBuf->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutBuf->SetArray(pOut.get(), 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutBuf->Flip(); + +CATCH: + + EVP_CIPHER_CTX_cleanup(&cipherCtx); + + SetLastResult(r); + return pOutBuf.release(); +} + +ByteBuffer* +_SymmetricCipher::DoUnwrapN(const Tizen::Base::ByteBuffer& wrappedKey) +{ + result r = E_SUCCESS; + int numVal = 0; + int ret = 0; + int count = 0; + int finalLen = 0; + int keyLen = 0; + int outLen = 0; + int dataLen = 0; + byte tempVal = null; + byte index = null; + byte num = null; + byte tempB[_AES_DATA_BLOCK_LENGTH] = {'\0'}; // Temp buffer for Receiveing AES o/p + byte tempBuf[_AES_DATA_BLOCK_LENGTH] = {'\0'}; + byte* pWrapData = null; + byte* pKey = null; + byte* pTemp = null; // For In place calculation + std::unique_ptr pOut; + std::unique_ptr pOutBuf; + EVP_CIPHER_CTX cipherCtx; + const EVP_CIPHER* pEncryptionAlgorithm = null; + + ClearLastResult(); + + pWrapData = const_cast< byte* >(wrappedKey.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pWrapData != null, null, E_INVALID_ARG, "[E_INVALID_ARG] Wrapped key data should be valid."); + + dataLen = wrappedKey.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, dataLen > 0, null, E_INVALID_ARG, "[E_INVALID_ARG] Wrapped key length should be positive."); + + pKey = const_cast< byte* >(__keyBytes.GetPointer()); + SysTryReturn(NID_SEC_CRYPTO, pKey != null, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key data should be valid."); + + keyLen = __keyBytes.GetRemaining(); + SysTryReturn(NID_SEC_CRYPTO, keyLen > 0, null, E_KEY_NOT_FOUND, "[E_KEY_NOT_FOUND] Key length should be positive."); + + numVal = dataLen / _BITS_IN_BYTE; +// SysTryReturn(NID_SEC_CRYPTO, numVal > _MIN_WRAP_KEY_LEN_REFACTOR && dataLen < _MAX_AES_WRAP_DATA_LENGTH, null, E_SYSTEM, "[E_SYSTEM] An Unexpected system error occurred."); + + if (numVal < _MIN_WRAP_KEY_LEN_REFACTOR || dataLen > _MAX_AES_WRAP_DATA_LENGTH) + { + ret = E_SYSTEM; + SysLogException(NID_SEC_CRYPTO, r, "An Unexpected system error occurred."); + goto CATCH; + } + + + switch (keyLen) + { + case _AES_128_KEY_LEN: + pEncryptionAlgorithm = EVP_aes_128_ecb(); + break; + + case _AES_192_KEY_LEN: + pEncryptionAlgorithm = EVP_aes_192_ecb(); + break; + + case _AES_256_KEY_LEN: + pEncryptionAlgorithm = EVP_aes_256_ecb(); + break; + + default: + r = E_UNSUPPORTED_ALGORITHM; + SysLogException(NID_SEC_CRYPTO, r, " The algorithm for input key length is not supported"); + goto CATCH; + } + + pOut = std::unique_ptr (new (std::nothrow) byte[dataLen]); + SysTryReturn(NID_SEC_CRYPTO, pOut != null, null, E_OUT_OF_MEMORY, "Allocating new byte array failed"); + + // Intialize variables + num = numVal - 1; + pTemp = pOut.get() + _BITS_IN_BYTE; + + // A = C0 + memcpy(pOut.get(), pWrapData, _BITS_IN_BYTE); + + for (index = 1; index <= num; index++) + { + memcpy(pTemp + (index - 1) * _BITS_IN_BYTE, pWrapData + index * _BITS_IN_BYTE, _BITS_IN_BYTE); + } + + // Start main loop + for (count = _MAX_LOOP_LEN_UNWRAP; count >= 0; count--) + { + for (index = num; index >= 1; index--) + { + + tempVal = (num * count) + index; + pOut.get()[_MAX_LOOP_VAL] = pOut.get()[_MAX_LOOP_VAL] ^ tempVal; + + memcpy(tempBuf, pOut.get(), _BITS_IN_BYTE); + memcpy(tempBuf + _BITS_IN_BYTE, pTemp + (index - 1) * _BITS_IN_BYTE, _BITS_IN_BYTE); + + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, pEncryptionAlgorithm, pKey, IV, 0); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, 0); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, tempB, &outLen, tempBuf, _AES_DATA_BLOCK_LENGTH); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + //cipher final operation + ret = EVP_CipherFinal(&cipherCtx, &tempB[outLen], &finalLen); + SysTryCatch(NID_SEC_CRYPTO, ret == 1, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + outLen = outLen + finalLen; + + memcpy(pOut.get(), tempB, _BITS_IN_BYTE); + + memcpy(pTemp + (index - 1) * _BITS_IN_BYTE, &tempB[_BITS_IN_BYTE], _BITS_IN_BYTE); + } + } + + ret = memcmp(pOut.get(), IV, _BITS_IN_BYTE); + SysTryCatch(NID_SEC_CRYPTO, ret == 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + outLen = (numVal - 1) * _BITS_IN_BYTE; + + pOutBuf = std::unique_ptr (new (std::nothrow) ByteBuffer()); + SysTryCatch(NID_SEC_CRYPTO, pOutBuf != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Allocating new ByteBuffer failed."); + + r = pOutBuf->Construct(outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory."); + + r = pOutBuf->SetArray(pTemp, 0, outLen); + SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] An unexpected system error occurred."); + + pOutBuf->Flip(); + +CATCH: + + EVP_CIPHER_CTX_cleanup(&cipherCtx); + + SetLastResult(r); + return pOutBuf.release(); +} + +} } } //Tizen::Security::Crypto diff --git a/src/security/crypto/FSecCrypto_SymmetricCipher.h b/src/security/crypto/FSecCrypto_SymmetricCipher.h new file mode 100644 index 0000000..3589747 --- /dev/null +++ b/src/security/crypto/FSecCrypto_SymmetricCipher.h @@ -0,0 +1,73 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCrypto_SymmetricCipher.h + * @brief This header file contains declarations of common operations for Symmetric Ciphers available. + */ +#ifndef _FSEC_CRYPTO_INTERNAL_SYMMETRIC_CIPHER_H_ +#define _FSEC_CRYPTO_INTERNAL_SYMMETRIC_CIPHER_H_ + +#include +#include +#include + +struct evp_cipher_st; +struct evp_cipher_ctx_st; + + +namespace Tizen { namespace Security { namespace Crypto +{ + +class _SymmetricCipher +{ + +public: + _SymmetricCipher(void); + virtual ~_SymmetricCipher(void); + result SetCipherAlgorithm(const Tizen::Base::String& cipherAlgorithm); + result SetKey(const Tizen::Security::ISecretKey& key); + result SetInitialVector(const Tizen::Base::ByteBuffer& initialVector); + result SetTransformation(const evp_cipher_st* pCipherAlgorithm, bool padding); + result SetCipherOperation(CipherOperation opMode); + Tizen::Base::ByteBuffer* DoCipherN(const Tizen::Base::ByteBuffer& input, bool variableKeyFlag = false); + result Initialize(bool variableKeyFlag = false); + Tizen::Base::ByteBuffer* UpdateN(const Tizen::Base::ByteBuffer& input); + Tizen::Base::ByteBuffer* FinalizeN(void); + Tizen::Base::ByteBuffer* WrapN(const Tizen::Base::ByteBuffer& secretKey); + Tizen::Base::ByteBuffer* UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + _SymmetricCipher(const _SymmetricCipher& rhs); + _SymmetricCipher& operator =(const _SymmetricCipher& rhs); + Tizen::Base::ByteBuffer* DoWrapN(const Tizen::Base::ByteBuffer& secretKey); + Tizen::Base::ByteBuffer* DoUnwrapN(const Tizen::Base::ByteBuffer& wrappedKey); + +private: + const evp_cipher_st* __pCipherAlgorithm; + Tizen::Base::String __cipherAlgorithm; + std::unique_ptr __pCipherCtx; + CipherOperation __opMode; + bool __padding; + Tizen::Base::ByteBuffer __initVector; + Tizen::Base::ByteBuffer __keyBytes; + +}; //_SymmetricCipher + +} } } // Tizen::Security::Crypto + +#endif //_FSEC_CRYPTO_INTERNAL_SYMMETRIC_CIPHER_H_ diff --git a/src/security/inc/FSecCert_CertService.h b/src/security/inc/FSecCert_CertService.h new file mode 100644 index 0000000..b2a69d0 --- /dev/null +++ b/src/security/inc/FSecCert_CertService.h @@ -0,0 +1,1002 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertService.h + * @brief This header file contains the declarations of CertService APIs. + * + * This header file contains the declarations of CertService APIs. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_SERVICE_H_ +#define _FSEC_CERT_INTERNAL_CERT_SERVICE_H_ + +#include + +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Security { namespace Cert +{ + +/** + * @class _CertService + * @brief This class is provide Services API for Certificate Management. + * @since 2.1 + * + * The %_CertService class is used for to provide Certificate Management's Services API. + * + * For more information on the class features, see Certificates. + * + */ +class _OSP_EXPORT_ _CertService +{ +public: + /** + * This function initializes the Db tables and removes and installs certificates . + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + */ + static result InitializeDb(void); + + /** + * This function initializes the Db tables. If tables are not created already, this function creates the Db tables. + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + */ + static result Initialize(void); + + /** + * This function drops the tables and removes all certificate files from the storage. + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + */ + static result DropTables(void); + + /** + * This function resets (deletes and creates) db tables. + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation failed. + */ + static result ResetTables(void); + + /** + * This function removes all certificates. + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation failed. + */ + static result MasterReset(void); + + /** + * This function reinstall Db. + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation failed. + */ + static result ReInitializeDb(void); + + /** + * This function installs the certificates into the Db table identified by input type. + * + * @since 2.1 + * @return If success this function returns number of certificates installed in Db tables, + * -1 in case of failure, 0 in case of no certificates present in directory. + * @param[in] type Type of certificates to install in Db table. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation failed. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static int InsertCert(_CaCertType type); + + /** + * This function installs all certificates identified by a given certificate type. + * + * @since 2.1 + * @return An error code. + * @param[in] certTrustTypes Certificate type. + * @param[out] pCertCount Number of installed certificates by this function. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation failed. + */ + static result InsertCerts(int certTrustTypes, int* pCertCount); + + /** + * This function installs the Default root certificate from pBuffer into Db table identified by type and format of the certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] type Type of the certificate to install in Db table. + * @param[in] format Format of input certificate pBuffer (X.509). + * @param[in] pCertBuf Input certificate pBuffer. + * @param[in] certLen Input certificate pBuffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation failed. + */ + static result InsertDefaultCaCertificate(_CaCertType type, _CertFormat format, byte* pCertBuf, int certLen); + + /** + * This function installs the root certificate from pBuffer into Db table identified by type and format of the certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] type Type of the certificate to install in Db table. + * @param[in] format Format of input certificate pBuffer (X.509). + * @param[in] pCertBuf Input certificate pBuffer. + * @param[in] certLen Input certificate pBuffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation failed. + */ + static result InsertCaCertificate(_CaCertType type, _CertFormat format, byte* pCertBuf, int certLen); + + /** + * This function installs the user root certificate from buffer into Db table identified by format of the certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] format Format of input certificate buffer (X.509). + * @param[in] pCert Input certificate buffer. + * @param[in] certLen Length of input certificate buffer. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + static result InsertUserCaCertificate(_CertFormat format, char* pCert, int certLen); + + /** + * This function installs User Root Certificate given by a certificate file path. + * + * @since 2.1 + * @return An error code. + * @param[in] pFilePath Certificate file path where the certificate file is located. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation failed. + */ + static result InsertUserCaCertificate(byte* pFilePath); + + /** + * This function installs the Default user CA certificates from storage identified. + * + * @since 2.1 + * @return This function returns count of installed Device certificates. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static int InsertUserCaCertificatesToRootDb(void); + + /** + * This function inserts user certificate chain into DB and store certificate and private key(encrypted) in file system. + * The certificate chain should contain chain of certificate, be in order "DeviceCertificate||CA(n)Certificate||.....". Excluding/including Root CA. + * If CA is not present in chain then it should be previously installed. Format of Certificate chain/key should be DER encoded. + * Only one private key must be supplied in private key parameter. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertChainBuffer User certificate chain buffer. + * @param[in] certChainLength Certificate chain buffer length. + * @param[in] pUserPrivateKey User private Key buffer. + * @param[in] userPrivateKeyLength User private key length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation failed. + */ + static result InsertUserCertChainPrivateKey(char* pCertChainBuffer, int certChainLength, char* pUserPrivateKey, int userPrivateKeyLength); + + /** + * This function inserts user certificate chain including private key into DB and store certificate and private key(encrypted) in file system. + * The certificate chain should contain chain of certificate, be in order "user key || DeviceCertificate||CA(n)Certificate||.....". Excluding/including Root CA. + * If CA is not present in chain then it should be previously installed. Format of Certificate chain/key buffer should be DER encoded. + * Only one private key must be supplied in private key parameter. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertChainPrivateKeyBuffer User private key and certificate chain buffer. + * @param[in] certChainPrivateKeyLength Private key and certificate chain buffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation failed. + */ + static result InsertCertificateChainWithPrivateKey(char* pCertChainPrivateKeyBuffer, int certChainPrivateKeyLength); + + /** + * This function verify certificate chain using DB. + * Note : It is a certificate chain which contains User certificate without private key. + * Chain can contain multiple certificate including Device, Intermediate and CA Certificate. + * If Root CA/Intermediate CA is not present in DB then it should be provided with chain, to be able to verify the certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertCtx Certificate chain context. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation failed. + */ + static result InsertCertificateChainContext(CertChainCtx pCertCtx); + + /** + * This function installs PKCS#12 contents into certificate DB and store certificate and private key(encrypted) in file system. + * Identified by filename and password provided by user. + * + * @since 2.1 + * @return An error code. + * @param[in] pPkcs12FilePath Filename of PKCS#12 content. + * @param[in] pPkcs12ImportPassword Password of the PKCS#12 content. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation failed. + * - DB operation error. + * - OpenSSL operation error. + */ + static result InsertPkcs12Content(char* pPkcs12FilePath, char* pPkcs12ImportPassword); + + /** + * This function removes the certificates from storage identified by input certificate type. + * + * @since 2.1 + * @return An error code. + * @param[in] type Type of certificates to remove. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation error. + */ + static result RemoveCert(_CaCertType type); + + /** + * This function removes all certificates identified by a given certificate type. + * + * @since 2.1 + * @return An error code. + * @param[in] certTrustTypes Certificate types. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation error. + */ + static result RemoveCerts(int certTrustTypes); + + /** + * This function deletes the root certificate + * + * @since 2.1 + * @return An error code. + * @param[in] type Ca Cert Type. + * @param[in] pBuffer Input Buffer. + * @param[in] bufLen Buffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation error. + */ + static result RemoveCaCertificate(_CaCertType type, char* pBuffer, int bufLen); // if same certificate is in Db, remove the certificate. + + /** + * This function un-installs User Root Certificate given by a certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Certificate Id. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation error. + */ + static result RemoveUserCaCertificateByCertId(int certId); + + /** + * This function un-installs User Certificate given by a certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Certificate Id. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation error. + */ + static result RemoveUserCertificateByCertId(int certId); + + + /** + * This function removes the Default user CA certificates from the storage identified. + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation error. + */ + static result RemoveUserCaCertificatesFromRootDb(void); + + /** + * This function deletes user certificate chain on the basis of Certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Id of certificate as in DB. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - File operation error. + * - DB operation error. + */ + static result RemoveUserCertChainByCertId(int certId); + + /** + * This function opens the context identified by calling application. + * + * @since 2.1 + * @return An error code. + * @param[in] type Calling application type. + * @param[out] pCertCtx Pointer to context as out parameter. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + */ + static result OpenContext(_CertContextType type, CertChainCtx* pCertCtx); + + /** + * This function adds the input certificate in the opened certificate context. + * + * @since 2.1 + * @return An error code. + * @param[in] certCtx Handle to the certificate context. + * @param[in] pCertBuf Certificate pBuffer. + * @param[in] certLen Certificate pBuffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - Certificate Link list operation error. + */ + static result AddCertificate(CertChainCtx certCtx, byte* pCertBuf, int certLen); + + /** + * This function verifies the certificate chain in certificate context with respect to installed root certificates in the device. + * + * @since 2.1 + * @return An error code. + * @param[in] certCtx Handle to certificate chain context. + * @param[out] pDomain Root certificate domain type. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - Certificate Link list operation error. + */ + static result VerifyChain(CertChainCtx certCtx, _CertDomainType* pDomain); + + /** + * This function verifies a certificate using given Public key. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to certificate. + * @param[in] pPublickey Certificate Public Key. + * @param[in] keyLen Certificate Public Key length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - Certificate Link list operation error. + */ + static result VerifyCert(CertificateHandle certHandle, byte* pPublickey, int keyLen); + + /** + * This function gets number of certificates in certificate chain represented by context. + * + * @since 2.1 + * @return An error code. + * @param[in] certCtx Handle to certificate context. + * @param[out] pDepth Chain depth information. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + static result GetChainDepth(CertChainCtx certCtx, int* pDepth); + + /** + * This function gets nth certificate handle of the chain represented by input context + * + * @since 2.1 + * @return An error code. + * @param[in] certCtx Handle to certificate context. + * @param[in] nth Position of certificate. + * @param[out] phCerticate Pointer to handle of certificate. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetNthCert(CertChainCtx certCtx, int nth, CertificateHandle* phCerticate); + + /** + * This function gets certificate pBuffer using the certificate handle. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to certificate. + * @param[out] pBuffer Pointer to certificate pBuffer. + * @param[out] certLen Output pBuffer length of certificate. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetCertBufferN(CertificateHandle certHandle, char*& pBuffer, int* certLen); + + /** + * This function returns the handle of certificate of input binary or base64 certificate pBuffer. + * + * @since 2.1 + * @return An error code. + * @param[in] pBuffer Buffer of certificate. + * @param[in] bufLen Length of input pBuffer. + * @param[out] pCertHandle Handle to the certificate out. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result OpenCertificate(char* pBuffer, int bufLen, CertificateHandle* pCertHandle); + + /** + * This function closes the opened context. + * + * @since 2.1 + * @return An error code. + * @param[in] certCtx Handle to certificate context. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + static result CloseContext(CertChainCtx certCtx); + + /** + * This function returns database Id of Ca certificate for given certificate handle. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to the certificate. + * @param[in] certType Type of certificate store. + * @param[out] certId Reference to integer to get certificate data Id. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetCaCertificateId(CertificateHandle certHandle, _CaCertType certType, int& certId); + + /** + * This function returns database Id of User certificate for given certificate handle. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to the certificate. + * @param[out] certId Reference to integer to get certificate data Id. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetUserCertificateId(CertificateHandle certHandle, int& certId); + + /** + * This function returns information of certificate requested by _CertFieldType parameter. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to the certificate. + * @param[in] field Type of combination of information required. + * @param[out] pCertInfo Pointer to certificate information structure. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetCertInfo(CertificateHandle certHandle, _CertFieldType field, _CertFieldInfos* pCertInfo); + + /** + * This function closes the handle of certificate . + * + * @since 2.1 + * @return An error code. + * @param[in] pCertHandle Handle to the certificate to close. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + * @remarks This function is not applicable to handle which is received by context APIs. + */ + static result CloseCertificate(CertificateHandle* pCertHandle); + + /** + * This function gets the certificate list information by requested format. + * + * @since 2.1 + * @return An error code. + * @param[in] certFormat Format of requested certificates. + * @param[in,out] pCertList Pointer to pointer of Certificate list structure. + * @param[out] count Number of certificates in the list. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetCertListByFormatN(_CertFormat certFormat, _CertificateListInfo*& pCertList, int* count); + + /** + * This function gets the root certificate list information by requested certificate ID + * + * @since 2.1 + * @return An error code. + * @param[in] certId Format of requested device certificates. + * @param[out] pCertList Pointer to pointer of Certificate list structure. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetCaCertListByCertIdN(int certId, _CertificateListInfo*& pCertList); + + /** + * This function frees the certificate list given by a certificate list. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertList Pointer to certificate link list. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + static result FreeCertList(_CertificateListInfo* pCertList); + + /** + * This function frees the certificate info given by a struct _CertInfo. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertInfo Pointer to certificate info. + * @exception E_SUCCESS The method is successful. + */ + static result FreeCertificateInfo(_CertInfo* pCertInfo); + + /** + * This function provides list of installed certificate by type. + * + * @since 2.1 + * @return If success give handle of root cert, null in case of failure. + * @param[in] type _CaCertType, Type of certificate. + * @param[out] count Number of installed certificate. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static CertificateStoreCtx OpenCertificateStoreByType(_CaCertType type, int* pCount); + + /** + * This function counts Root CA. + * + * @since 2.1 + * @return Count of Root CA, -1 in case of failure. + * @param[in] certificateStoreCtx Certificate store context, can be get using OpenCertificateStoreByType function. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static int GetCertificateCount(CertificateStoreCtx certificateStoreCtx); + + /** + * This function returns the next root CA pBuffer. + * + * @since 2.1 + * @return An error code. + * @param[in] certificateStoreCtx Certificate store context, can be get using OpenCertificateStoreByType function.. + * @param[out] pBuffer Output Buffer. + * @param[in,out] pBufferLen Buffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + static result GetNextCertificate(CertificateStoreCtx certificateStoreCtx, char* pBuffer, int* pBufferLen); + + /** + * This function updates Root CA certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] type CA Cert Type. + * @param[in] pOldCert Old Certificate Buffer. + * @param[in] oldCertLen Old Certificate length. + * @param[in] pNewCert New Certificate Buffer. + * @param[in] newCertLen New Certificate length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result UpdateCaCertificate(_CaCertType type, char* pOldCert, int oldCertLen, char* pNewCert, int newCertLen); // if same certificate is in Db, replace the certificate using buffer2 and bufferLen2. + + /** + * This function closes root Certificate Handle. + * + * @since 2.1 + * @return An error code. + * @param[in] certificateStoreCtx Certificate store context, can be get using OpenCertificateStoreByType function.. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + static result CloseCertificateStore(CertificateStoreCtx certificateStoreCtx); + + /** + * This function returns Public key of certificate in DER format. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to the certificate. + * @param[out] pBuffer Buffer to contain public key. + * @param[in,out] pBufLen Length of Public Key. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetCertPublicKey(CertificateHandle certHandle, char* pBuffer, int* pBufLen); + + /** + * This function returns Signature of certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to the certificate. + * @param[out] pBuffer Buffer to contain Signature. + * @param[in,out] bufLen Length of Signature. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetCertSignature(CertificateHandle certHandle, char* pBuffer, int* pBufLen); + + /** + * This function returns Version of X509 certificate. + * + * @since 2.1 + * @return certificate version number as integer, -1 in case of failure. + * @param[in] certHandle Handle to the certificate. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static int GetCertVersion(CertificateHandle certHandle); + + /** + * This function checks certificates validity. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to the certificate. + * @param[out] pValidity Validity of certificate; Valid, Expired or Validity Yet to start. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result CheckCertValidity(CertificateHandle certHandle, _CertValidityType* pValidity); + + /** + * This function checks certificate type. + * + * @since 2.1 + * @return An error code. + * @param[in] certHandle Handle to the certificate. + * @param[out] pCertType Type of certificate. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result CheckCertType(CertificateHandle certHandle, _CaCertType* pCertType); + + /** + * This function retrieves domain certificate information. + * + * @since 2.1 + * @return If success this function returns certId installed certificates, -1 in case of failure. + * @param[out] ppDcInfo information about domain certificate. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static int GetDomainCertInfoN(_CertFieldInfos*& prDcInfo); + + /** + * This function retrieves certificate information given by a certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Certificate ID. + * @param[out] pDcInfo Pointer to certificate information structure. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetCaCertInfoByCertId(int certId, _CertFieldInfos* pDcInfo); + + /** + * This function breaks certificate chain buffer into individual certificate. + * It is assumed here that there is no Private Key in the Chain. + * Chain can contain multiple certificate including Device, Intermediate and CA Certificate. + * This will return a Structure HCertChainCtx containing all the certificates. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertChainBuffer Certificate chain buffer. + * @param[in] certChainLength Certificate chain buffer length. + * @param[out] pCertCtx Certificate chain list containing individual certificate. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetParsedCertificateChainN(char* pCertChainBuffer, int certChainLength, CertChainCtx* pCertCtx); + + /** + * This function verifies the certificate chain in certificate context with respect to installed root certificates in the DB. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertCtx Handle to certificate chain context. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result VerifyCertificateChain(CertChainCtx pCertCtx); + + /** + * This function breaks certificate chain buffer into individual certificate. + * It is assumed here that there is no Private Key in the Chain. + * Chain can contain multiple certificate including Device, Intermediate and CA Certificate. + * This will return a Structure ppCertChainList containing all the certificates. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertChainBuffer Certificate chain buffer. + * @param[in] certChainLength Certificate chain buffer length. + * @param[out] ppCertChainListRef Certificate chain list containing individual certificate. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result MakeCertChainFromBufferN(char* pCertChainBuffer, int certChainLength, _CertRootList*& ppCertChainListRef); + + /** + * This function retrieves the user certificate chain on the basis of Subject name of any Intermediate CA and + * subject name of user Certificate. Subject name of Device certificate is optional parameter. + * Subject name of any intermediate Certificate is compulsory parameter. + * This function will retrieve the certificate chain on the basis of Subject name of any intermediate CA taken as + * issuer name in function parameters. It can also extract Certificate chain on the basis of Subject name of device + * certificate including chain containing the Intermediate Certificate Subject name. + * If there are multiple cert chain from the same issuer, it will get all the cert chain and check with subject name + * to decide which chain is need to be returned. For input parameter it takes subject name of any intermediate CA as + * issuer name, and subject name of user certificate as optional parameter. Format of Subject and Issuer name will + * be DER encoded. + * + * @since 2.1 + * @return An error code. + * @param[in] pIssuerName Pointer to Issuer name. + * @param[in] issuerNameLength Length of Issuer name. + * @param[in] pSubjectName pointer to Subject name. + * @param[in] subjectNameLength Length of Subject name. + * @param[out] pUserCertListInfoTypesRef Pointer to certificate list. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetUserCertChainByIssuerAndSubjectNameN(char* pIssuerName, int issuerNameLength, char* pSubjectName, int subjectNameLength, _CertificateListInfo*& pUserCertListInfoTypesRef); + + /** + * This function retrieves the device certificate chain on the basis of Subject name of Device Certificate. + * This function retrieves the certificate chain on the basis of Subject name of Device Certificate as function + * parameters. If there are multiple cert chain from the same issuer, it will get all the cert chain and check + * with subject name to decide which chain is need to be returned. + * + * @since 2.1 + * @return An error code. + * @param[in] pSubjectName Pointer to Subject name. + * @param[in] subjectNameLength Length of Subject name. + * @param[out] pCertChainCtx Pointer to certificate chain. + * @param[out] pPrivateKeyCtx Pointer to private key info. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetUserCertChainBySubjectName(char* pSubjectName, int subjectNameLength, CertChainCtx* pCertChainCtx, PrivateKeyCtx* pPrivateKeyCtx); + + /** + * This function gets the user certificate list information by requested format. + * + * @since 2.1 + * @return An error code. + * @param[in] certFormat Format of requested user certificates. + * @param[out] pUserCertListInfoTypesRef Pointer to pointer of Certificate list structure. + * @param[out] pCount Number of certificates in the list. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetUserCertListInfoTypesByFormatN(_CertFormat certFormat, _CertificateListInfo*& pUserCertListInfoTypesRef, int* pCount); + + /** + * This function gets the user certificate list information by requested certificate ID. It give info of certificate only. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Certificate Id as in Db. + * @param[in] encodingType Required encoding type of output buffer (PEM, Base64 or DER). + * @param[out] ppUserCertificateListInfoTypes Pointer to pointer of Certificate list structure. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetUserCertificateByCertIdN(int certId, _CertEncodingType encodingType, _CertInfo*& pUserCertificateInfoRef); + + /** + * This function retrieves all user certificate information. + * + * @since 2.1 + * @return This function returns certId of installed user certificates. + * @param[out] pCertFieldInfosRef User certificate information. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static int GetUserCertFieldInfoN(_CertFieldInfos*& pCertFieldInfosRef); + + /** + * This function retrieves user certificate information by requested certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Certificate id of requested user certificates as in DB. + * @param[out] pCertFieldInfos Pointer to pointer of Certificate infos structure. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetUserCertFieldInfoByCertId(int certId, _CertFieldInfos* pCertFieldInfos); + + /** + * This function provides certificate subject name given by a certificate handlder. It is complete certificate subject name buffer. + * + * @since 2.1 + * @return An error code. + * @param[in] certificateHandle Handle to certificate. + * @param[out] ppSubjectNameRef Subject name buffer. + * @param[out] pSubjectNameLength Subject name length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetSubjectNameN(CertificateHandle certificateHandle, byte*& ppSubjectNameRef, int* pSubjectNameLength); + + /** + * This function provides certificate issuer name given by a certificate handlder. It is complete certificate issuer name buffer. + * + * @since 2.1 + * @return An error code. + * @param[in] certificateHandle Handle to certificate. + * @param[out] pIssuerNameRef Issuer name buffer. + * @param[out] pIssuerNameLength Subject name length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM An unexpected system error has occurred. + */ + static result GetIssuerNameN(CertificateHandle certificateHandle, byte*& pIssuerNameRef, int* pIssuerNameLength); + + + /** + * This function provides the path of CRT file, which contains all the installed certificate in PEM format. + * + * @since 2.1 + * @return Path of CRT file containing all certificates in PEM format. + */ + static Tizen::Base::String GetCertificateCrtFilePath(void); + + /** + * This function frees the root certificate list. + * + * @since 2.1 + * @return An error code. + * @param[in] pRootCertList Pointer to root certificate link list. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + static result FreeRootCertList(_CertRootList* pRootCertList); + + /** + * This function closes the opened private key context. + * + * @since 2.1 + * @return An error code. + * @param[in] certCtx Handle to private key context. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + */ + static result ClosePrivateKeyContext(PrivateKeyCtx privateKeyCtx); + +private: + _CertService(void); + + _CertService(const _CertService& rhs); + + ~_CertService(void); + + _CertService& operator =(const _CertService& rhs); + +}; //_CertService + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_SERVICE_H_ diff --git a/src/security/inc/FSecCert_CertServiceProxy.h b/src/security/inc/FSecCert_CertServiceProxy.h new file mode 100644 index 0000000..54230a6 --- /dev/null +++ b/src/security/inc/FSecCert_CertServiceProxy.h @@ -0,0 +1,429 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertServiceProxy.h + * @brief This is the header file for the _CertServiceProxy class. + * + * This file contains the declarations of _CertServiceProxy. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_SERVICE_PROXY_H_ +#define _FSEC_CERT_INTERNAL_CERT_SERVICE_PROXY_H_ + +#include +#include +#include +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Io +{ +class _IpcClient; +} } + +namespace Tizen { namespace Base { namespace Runtime +{ +class Mutex; +} } } + +namespace Tizen { namespace Security { namespace Cert +{ + +/** + * @class _CertServiceProxy + * @brief This class is provide IPC API for Certificate Management. + * @since 2.1 + * + * The %_CertServiceProxy class is used for to provide Certificate Management's IPC API. + * + * For more information on the class features, see Certificates. + * + */ +class _OSP_EXPORT_ _CertServiceProxy +{ + +public: + /** + * Creates and intialize the instance of _CertServiceProxy class. + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + */ + static _CertServiceProxy* GetInstance(void); + + /** + * This function returns name of root Certificate store. + * + * @since 2.1 + * @return An error code. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + */ + result GetName(void); + + /** + * This function closes root Certificate Handle. + * + * @since 2.1 + * @return An error code. + * @param[in] certificateStoreCtx Certificate store context, can be get using OpenCertificateStoreByType function. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + */ + result CloseCertificateStore(int certificateStoreCtx); + + /** + * This function provides handle of the required Certificate type. + * + * @since 2.1 + * @return An error code. + * @param[in] type _CaCertType Type info. + * @param[out] count Number of certificates in store. + * @param[out] certificateStoreCtx Certificate store context, can be get using OpenCertificateStoreByType function. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + */ + result OpenCertificateStoreByType(int type, int& count, int& certificateStoreCtx); + + /** + * This function counts Root CA. + * + * @since 2.1 + * @return An error code. + * @param[in] certificateStoreCtx Certificate store context, can be get using OpenCertificateStoreByType function. + * @param[out] count Count of certificates in store. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + */ + result GetCertificateCount(int certificateStoreCtx, int& count); + + /** + * This function returns the next root CA pBuffer. + * + * @since 2.1 + * @return An error code. + * @param[in] certificateStoreCtx Certificate store context, can be get using OpenCertificateStoreByType function. + * @param[out] pBuffer Output buffer. + * @param[out] bufferLen Buffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + */ + result GetNextCertificate(int certificateStoreCtx, byte* pBuffer, int& bufferLen); + + /** + * This function updates Root CA certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] type CA Cert Type. + * @param[in] pOldCert Old Certificate Buffer. + * @param[in] oldCertLen Old Certificate length. + * @param[in] pNewCert New Certificate Buffer. + * @param[in] newCertLen New Certificate length. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + */ + result UpdateCaCertificate(int type, byte* pOldCert, int oldCertLen, byte* pNewCert, int newCertLen); + + /** + * This function deletes the root certificate + * + * @since 2.1 + * @return An error code. + * @param[in] type CA Cert Type. + * @param[in] pBuffer Input Buffer. + * @param[in] bufLen Buffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result RemoveCaCertificate(int type, byte* pBuffer, int bufLen); + + /** + * This function uninstalls User Root Certificate given by a certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Certificate Id. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result RemoveUserCaCertificateByCertId(int certId); + + /** + * This function uninstalls User Certificate given by a certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Certificate Id. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result RemoveUserCertificateByCertId(int certId); + + /** + * This function installs the root certificate from pBuffer into Db table identified by type and format of the certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] type Type of the certificate to install in Db table. + * @param[in] format Format of input certificate pBuffer (X.509) + * @param[in] pCert Input certificate pBuffer. + * @param[in] certLen Input certificate pBuffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result InsertCaCertificate(int type, int format, byte* pCert, long certLen); + + /** + * This function installs the user root certificate from buffer into Db table identified by format of the certificate. + * + * @since 2.1 + * @return An error code. + * @param[in] format Format of input certificate buffer (X.509). + * @param[in] pCert Input certificate buffer. + * @param[in] certLen Length of input certificate buffer. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result InsertUserCaCertificate(int format, char* pCert, int certLen); + + /** + * This function installs User Root Certificate given by a certificate file path. + * + * @since 2.1 + * @return An error code. + * @param[in] pFilePath Certificate file path where the certificate file is located. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result InsertUserCaCertificate(byte* pFilePath); + + /** + * This function inserts user certificate chain into DB and store certificate and private key(encrypted) in file system. + * The certificate chain should contain chain of certificate, be in order "DeviceCertificate||CA(n)Certificate||.....". Excluding/including Root CA. + * If CA is not present in chain then it should be previously installed. Format of Certificate chain/key should be DER encoded. + * Only one private key must be supplied in private key parameter. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertchainBuffer User certificate chain buffer. + * @param[in] certChainLen Certificate chain buffer lenth. + * @param[in] pUserPrivateKey User private Key buffer. + * @param[in] userPrivateKeyLen User private key length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result InsertUserCertChainPrivateKey(char* pCertchainBuffer, int certChainLen, char* pUserPrivateKey, int userPrivateKeyLen); + + /** + * This function inserts user certificate chain including private key into DB and store certificate and private key(encrypted) in file system. + * The certificate chain should contain chain of certificate, be in order "user key || DeviceCertificate||CA(n)Certificate||.....". Excluding/including Root CA. + * If CA is not present in chain then it should be previously installed. Format of Certificate chain/key buffer should be DER encoded. + * Only one private key must be supplied in private key parameter. + * + * @since 2.1 + * @return An error code. + * @param[in] pCertchainPrivateKeyBuffer User private key and certificate chain buffer. + * @param[in] certChainPrivateKeyLength Private key and certificate chain buffer length. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result InsertCertificateChainWithPrivateKey(char* pCertchainPrivateKeyBuffer, int certChainPrivateKeyLength); + + /** + * This function installs PKCS#12 contents into certificate DB and store certificate and private key(encrypted) in file system. + * Identified by filename and password provided by user. + * + * @since 2.1 + * @return An error code. + * @param[in] pPkcs12FilePath Filename of PKCS#12 content. + * @param[in] pPkcs12ImportPassword Password of the PKCS#12 content. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + * - OpenSSL operation failed. + */ + result InsertPkcs12Content(char* pPkcs12FilePath, char* pPkcs12ImportPassword); + + /** + * This function deletes user certificate chain on the basis of Certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId ID of certificate as in DB. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result RemoveUserCertChainByCertId(int certId); + + /** + * This function retrieves the user certificate chain on the basis of Subject name of any Intermediate CA and + * subject name of user Certificate. Subject name of Device certificate is optional parameter. + * Subject name of any intermediate Certificate is compulsory parameter. + * This function will retrieve the certificate chain on the basis of Subject name of any intermediate CA taken as + * issuer name in function parameters. It can also extract Certificate chain on the basis of Subject name of device + * certificate including chain containing the Intermediate Certificate Subject name. + * If there are multiple cert chain from the same issuer, it will get all the cert chain and check with subject name + * to decide which chain is need to be returned. For input parameter it takes subject name of any intermediate CA as + * issuer name, and subject name of user certificate as optional parameter. Format of Subject and Issuer name will + * be DER encoded. + * + * @since 2.1 + * @return An error code. + * @param[in] pIssuerName Pointer to Issuer name. + * @param[in] issuerNameLength Length of Issuer name. + * @param[in] pSubjectName pointer to Subject name. + * @param[in] subjectNameLength Length of Subject name. + * @param[out] pUserCertListInfoTypesRef Pointer to certificate list. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result GetUserCertChainByIssuerAndSubjectNameN(char* pIssuerName, int issuerNameLength, char* pSubjectName, int subjectNameLength, _CertificateListInfo*& pUserCertListInfoTypesRef); + + /** + * This function gets the user certificate list information by requested certificate ID. It give info of certificate only. + * + * @since 2.1 + * @return User certificate information containing certificate buffer, private key buffer etc. + * @param[in] certId Certificate ID as in DB. + * @param[in] encodingType Required encoding type of output buffer (PEM, Base64 or DER). + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation error. + * - File operation error. + * - DB operation error. + */ + _CertInfo* GetUserCertificateByCertIdN(int certId, int encodingType); + + /** + * This function retrieves user certificate information by requested certificate ID. + * + * @since 2.1 + * @return An error code. + * @param[in] certId Certificate id of requested user certificates as in DB. + * @param[out] pCertFieldInfos Pointer to ponter of Certificate infos structure. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_INVALID_ARG The specified input parameter is invalid. + * @exception E_SYSTEM A system error has occurred. + * - IPC operation failed. + * - File operation failed. + * - DB operation failed. + */ + result GetUserCertFieldInfoByCertId(int certId, _CertFieldInfos* pCertFieldInfos); + +private: + // This default constructor is intentionally declared as private to + // implement the Singleton semantic. + _CertServiceProxy(void); + + // This destructor is intentionally declared as private to + // implement the Singleton semantic. + ~_CertServiceProxy(void); + + _CertServiceProxy(const _CertServiceProxy& rhs); + + _CertServiceProxy& operator =(const _CertServiceProxy& rhs); + + //This construct function initialises the _CertServiceProxt instance + static void Construct(void); + +private: + static Tizen::Io::_IpcClient* __pIpcClient; //singleton + static _CertServiceProxy* __pCertServiceProxy; //singleton +}; // _CertServiceProxy + + +} } } //Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_SERVICE_PROXY_H_ diff --git a/src/security/inc/FSecCert_CertServiceStub.h b/src/security/inc/FSecCert_CertServiceStub.h new file mode 100644 index 0000000..32b5f67 --- /dev/null +++ b/src/security/inc/FSecCert_CertServiceStub.h @@ -0,0 +1,119 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertServiceStub.h + * @brief This is the header file for the _CertServiceStub class. + * + * This file contains the declarations of _CertServiceStub. + */ + +#ifndef _FSEC_CERT_INTERNAL_CERT_SERVICE_STUB_H_ +#define _FSEC_CERT_INTERNAL_CERT_SERVICE_STUB_H_ + +#include +#include +#include +#include + +#include "FIo_IIpcServerEventListener.h" +#include "FIo_IpcCommonParamTraits.h" +#include "FSecCert_CertTypes.h" + +namespace Tizen { namespace Io +{ +class _IpcServer; +} } + +namespace Tizen { namespace Security { namespace Cert +{ + +class _OSP_EXPORT_ _CertServiceStub + : public Tizen::Io::_IIpcServerEventListener + , public Tizen::Base::Object +{ +public: + _CertServiceStub(void); + + virtual ~_CertServiceStub(void); + +public: + // __IIPcServerEventListener interfaces + virtual result Construct(void); + + virtual void OnIpcServerStarted(const Tizen::Io::_IpcServer& server); + + virtual void OnIpcServerStopped(const Tizen::Io::_IpcServer& server); + + virtual void OnIpcClientConnected(const Tizen::Io::_IpcServer& server, int clientId); + + virtual void OnIpcClientDisconnected(const Tizen::Io::_IpcServer& server, int clientId); + + virtual void OnIpcRequestReceived(Tizen::Io::_IpcServer& server, const IPC::Message& message); + + //CertService handler method + + bool OnGetName(result* pRet); + + bool OnCloseCertificateStore(int certificateStoreCtx, result* pRet); + + bool OnOpenCertificateStoreByType(int type, int* pCount, int* pRootHandle, result* pRet); + + bool OnGetCertificateCount(int certificateStoreCtx, int* pRootHandle, result* pRet); + + bool OnGetNextCertificate(int certificateStoreCtx, int length, Tizen::Io::_IpcBuffer* pCertBufferIpc, result* pRet); + + bool OnUpdateRootCa(int type, Tizen::Io::_IpcBuffer certOldBufferIpc, Tizen::Io::_IpcBuffer certNewBufferIpc, result* pRet); + + bool OnRemoveRootCa(int type, Tizen::Io::_IpcBuffer certBufferIpc, int bufLen, result* pRet); + + bool OnUninstallUserRootCertificateByCertId(int certId, result* pRet); + + bool OnInsertCaCertificate(int type, int format, Tizen::Io::_IpcBuffer certBuffer, long certLen, result* pRet); + + bool OnInsertUserCaCertificate(int format, Tizen::Io::_IpcBuffer certBuffer, int certLen, result* pRet); + + bool OnInstallUserRootCertificate(Tizen::Io::_IpcBuffer filePath, result* pRet); + + bool OnInsertUserCertChainPrivateKey(Tizen::Io::_IpcBuffer certChainBufferIpc, int certSize, Tizen::Io::_IpcBuffer privateKeyBufferIpc, int userPriKeyLen, result* pRet); + + bool OnInsertCertificateChainWithPrivateKey(Tizen::Io::_IpcBuffer certChainPrivateKeyBufferIpc, int certChainPrivateKeyLength, result* pRet); + + bool OnInstallPkcs12Content(Tizen::Io::_IpcBuffer pkcs12FilePath, Tizen::Io::_IpcBuffer pkcs12ImportPassword, result* pRet); + + bool OnDeleteUserCertChainByCertId(int certID, result* pRet); + + bool OnDeleteUserCertificateByCertId(int certID, result* pRet); + + bool OnGetUserCertChainByIssuerAndSubjectNameN(Tizen::Io::_IpcBuffer issuerBufferIpc, int issuerNameLen, Tizen::Io::_IpcBuffer subjectBufferIpc, int subNameLen, _CertificateListInfo* pCertList, result* pRet); + + bool OnGetUserCertificateByCertIdN(int certId, int encodingType, _CertInfo* pUserCertificateList, result* pRet); + + bool OnGetUserCertFieldInfoByCertId(int certId, _CertFieldInfos* pCertFieldInfos, result* pRet); + +private: + _CertServiceStub(const _CertServiceStub& rhs); + + _CertServiceStub& operator =(const _CertServiceStub& rhs); + +private: + Tizen::Io::_IpcServer* __pIpcServer; +}; // _CertServiceStub + +} } } // Tizen::Security::Cert + +#endif // _FSEC_CERT_INTERNAL_CERT_SERVICE_STUB_H_ diff --git a/src/security/inc/FSecCert_CertTypes.h b/src/security/inc/FSecCert_CertTypes.h new file mode 100755 index 0000000..27212a9 --- /dev/null +++ b/src/security/inc/FSecCert_CertTypes.h @@ -0,0 +1,361 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSecCert_CertTypes.h + * @brief This header file contains the declarations of X509 Certificate defines. + * + * This file contains the declarations of X509 Certificate defines. + */ + + +#ifndef _FSEC_INTERNAL_CERT_TYPES_H_ +#define _FSEC_INTERNAL_CERT_TYPES_H_ + + +#include + +namespace Tizen { namespace Security { namespace Cert +{ + +const int _MAX_CERTIFICATE_SIZE = 8192; +const int _MAX_CERT_PRIVATE_KEY_SIZE = 3072; +const int _MAX_CERT_PUBLIC_KEY_SIZE = 2048; +const int _MAX_CERTIFICATE_PATH_SIZE = 128; +const int _MAX_PRV_KEY_PATH_SIZE_SIZE = 128; +const int _MAX_ISSUER_SUBJECT_NAME_SIZE = 512; +const int _MAX_SERIAL_NUMBER_SIZE = 40; +const int _MAX_FILENAME_SIZE = 256; +const int _MAX_CERT_SHA1_DIGEST_SIZE = 20; +const int _MAX_BASE64_CERT_SIZE = 2000 * (4 / 3); +const int _MAX_TYPE_CONST_SIZE = 100; +const int _MAX_TYPE_RECORD_SIZE = 3; +const int _MAX_CERT_PUB_KEY_HASH_SIZE = 256; +const int _MAX_QUERY_LEN = 2000; +const int _MAX_CERT_TYPE = 32; +const int _MIN_CERT_TYPE = 0; +const int _MAX_HASH_SIZE = 256; +const int _MAX_CERT_VALIDITY_SIZE = 32; +const int _MAX_CERT_ALGORITHM_SIZE = 64; +const int _MAX_CERT_FINGERPRINT_SIZE = 40; +const int _MAX_CERT_TYPE_SIZE = 32; +const int _MAX_CERT_TIME_LEN = 15; +const int _MAX_CERT_OSP_CRITICAL1_COUNT = 1; +const int _MAX_CERT_OSP_CRITICAL2_COUNT = 2; +const int _MAX_CERT_OSP_CRITICAL3_COUNT = 0; +const int _MAX_CERT_OSP_CRITICAL4_COUNT = 1; +const int _MAX_CERT_OSP_CRITICAL5_COUNT = 0; +const int _MAX_CERT_OSP_PRELOAD_APP_COUNT = 1; +const int _MAX_OID_SIZE = 250; +const int _MAX_GAP = 1; +const int _MAX_EXT_TABLESIZE = 31; +const int _MAX_SUBJECT_OFFSET_SIZE = 50; +const int _MAX_ISSUER_OFFSET_SIZE = 30; +const int _MAX_OFFSET_CONST_SIZE = 90; +const int _MAX_CA_CONDITION_SIZE = 610; +const int _MAX_ISSUER_CONDITION_SIZE = 150; +const int _MAX_ISSUER_NAME_OFFSET = 70; +const int _MAX_CONDITION_CONST_SIZE = 700; +const int _MAX_PEM_HEADER = 54; + +extern const Tizen::Base::String _CERT_MGR_SYSTEM_DIRECTORY; +extern const Tizen::Base::String _CERT_MGR_BASE_DIRECTORY; +extern const Tizen::Base::String _CERT_MGR_CERTMGR_DIRECTORY; +extern const Tizen::Base::String _CERT_MGR_CERT_DIRECTORY; +extern const Tizen::Base::String _CERT_ROOT_CA_CERT_FILE_DIRECTORY; +extern const Tizen::Base::String _CERT_USER_CERT_FILE_DIRECTORY; +extern const Tizen::Base::String _CERT_USER_PRIVKEY_FILE_DIRECTORY; + +extern const Tizen::Base::String _CERT_ROOT_CA_CERT_TABLE; +extern const Tizen::Base::String _CERT_USER_CERT_TABLE; + +extern const Tizen::Base::String _CERT_DOMAIN1_CERT_FILE_PATH; +extern const Tizen::Base::String _CERT_DOMAIN2_CERT_FILE_PATH; +extern const Tizen::Base::String _CERT_SVC_DEFAULT_CERT_DIRECTORY; +extern const Tizen::Base::String _CERT_MGR_CRT_FILE_PATH; +extern const Tizen::Base::String _TEMP_CERT_MGR_CRT_FILE_PATH; + +//Prefix definition for NAME Prefix +extern const char* _CERT_COMMON_NAME; +extern const char* _CERT_ORG_UNIT_NAME; +extern const char* _CERT_ORG_NAME; +extern const char* _CERT_LOCALITY_NAME; +extern const char* _CERT_STATE_OR_PROVINCE_NAME; +extern const char* _CERT_COUNTRY_NAME; +extern const char* _CERT_EMAIL_ADDRESS; +extern const char* _CERT_SERIAL_NUM; +extern const char* _CERT_GIVEN_NAME; +extern const char* _CERT_SUR_NAME; +extern const char* _CERT_STATE_OF_PROVINCE; +extern const char* _CERT_DC; +extern const char* _CERT_TK_ISSUER_NAME; + +//Typedef for readeablitiy of code and ditinguish between different types of handles and context +typedef void* CertificateHandle; +typedef void* CertChainCtx; +typedef void* PrivateKeyCtx; +typedef void* CertificateStoreCtx; +typedef int CertIdNo; + +enum _CaCertType +{ + _CERT_TYPE_NOT_BOUNDED = 0, + _CERT_TYPE_PRIVATE = 1, + _CERT_TYPE_UNTRUSTED = 2, + _CERT_TYPE_TRUSTED_CA = 3, + _CERT_TYPE_ROOT_CA = 4, + _CERT_TYPE_ROOT_DOMAIN1 = 5, + _CERT_TYPE_ROOT_DOMAIN2 = 6, + _CERT_TYPE_ROOT_DOMAIN3 = 7, + _CERT_TYPE_SIM_ROOT_DOMAIN1 = 8, + _CERT_TYPE_SIM_ROOT_DOMAIN3 = 9, + _CERT_TYPE_DEV_ROOT_CA = 10, + _CERT_TYPE_DEV_ROOT_DOMAIN1 = 11, + _CERT_TYPE_DEV_ROOT_DOMAIN2 = 12, + _CERT_TYPE_DEV_ROOT_DOMAIN3 = 13, + _CERT_TYPE_ROOT_CA_BY_USER = 14, + _CERT_TYPE_INTERMIDIATE_CA = 15, + _CERT_TYPE_USER_CERT = 16, + _CERT_TYPE_OSP_CRITICAL1 = 17, + _CERT_TYPE_OSP_CRITICAL2 = 18, + _CERT_TYPE_OSP_CRITICAL3 = 19, + _CERT_TYPE_OSP_PRELOAD_APP = 20, + _CERT_TYPE_CSC_ROOT_CA = 21, + _CERT_TYPE_CSC_ROOT_DOMAIN1 = 22, + _CERT_TYPE_CSC_ROOT_DOMAIN2 = 23, + _CERT_TYPE_CSC_ROOT_DOMAIN3 = 24, + _CERT_TYPE_OSP_CRITICAL4 = 25, + _CERT_TYPE_OSP_CRITICAL5 = 26, + _CERT_TYPE_WRT = 27, + _CERT_TYPE_MAX = 9999, +}; //_CaCertType + +enum _CertFormat +{ + _CERT_X509 = 1, + _CERT_UNKNOWN = 9999 +}; //_CertFormat + +enum _CertDomainType +{ + _CERT_DOMAIN1_TRUSTED = 0, + _CERT_DOMAIN2_TRUSTED = 1, + _CERT_DOMAIN3_TRUSTED = 2, + _CERT_WRT_TRUSTED = 3, + _CERT_INVALID_DOMAIN = 9999, + +}; //_CertDomainType + +enum _CertContextType +{ + _CERT_CONTEXT_DOMAIN = 0, + _CERT_CONTEXT_DOMAIN_NO_VALIDITY = 1, + _CERT_CONTEXT_CERT = 2, + _CERT_CONTEXT_CERT_NO_VALIDITY = 3, + _CERT_CONTEXT_OSP_USER = 4, + _CERT_CONTEXT_OSP_USER_NO_VALIDITY = 5, + _CERT_CONTEXT_OSP_CRITICAL1 = 6, + _CERT_CONTEXT_OSP_CRITICAL1_NO_VALIDITY = 7, + _CERT_CONTEXT_OSP_CRITICAL2 = 8, + _CERT_CONTEXT_OSP_CRITICAL2_NO_VALIDITY = 9, + _CERT_CONTEXT_OSP_CRITICAL3 = 10, + _CERT_CONTEXT_OSP_CRITICAL3_NO_VALIDITY = 11, + _CERT_CONTEXT_OSP_CRITICAL4 = 12, + _CERT_CONTEXT_OSP_CRITICAL4_NO_VALIDITY = 13, + _CERT_CONTEXT_OSP_CRITICAL5 = 14, + _CERT_CONTEXT_OSP_CRITICAL5_NO_VALIDITY = 15, + _CERT_CONTEXT_OSP_PRELOAD_APP = 16, + _CERT_CONTEXT_OSP_PRELOAD_APP_NO_VALIDITY = 17, + _CERT_CONTEXT_SSL = 29, + _CERT_CONTEXT_MIDP = 30, + _CERT_CONTEXT_WRT = 31, + _CERT_CONTEXT_TK = 32, +}; //_CertContextType + +enum _CertFieldType +{ + _CERT_FIELD_SERIAL = 1, + _CERT_FIELD_SIGALGORITHM = 2, + _CERT_FIELD_VALIDITY = 4, + _CERT_FIELD_SUBJECT = 8, + _CERT_FIELD_ISSUER = 16, + _CERT_FIELD_FINGERPRINT = 32, + _CERT_FIELD_PUBLICKEY = 64, + _CERT_FIELD_VERSION = 128, + _CERT_FIELD_TYPE = 256, + _CERT_FIELD_ALL = 0xFFF, +}; //_CertFieldType + +enum _CertValidityType +{ + _CERT_VALIDITY_VALID = 0, // valid + _CERT_VALIDITY_EXPIRED = 1, // expired + _CERT_VALIDITY_NOT_YET_VALID = 2, // not yet valid + _CERT_VALIDITY_UNKNOWN = 9999, +}; //_CertValidityType + +/** + * @enum _CertEncodingType + * Defines the type of encoding. + * + * @since 2.1 + */ +enum _CertEncodingType +{ + _CERT_ENC_TYPE_BINARY = 0, /**< %Binary or DER Encoding */ + _CERT_ENC_TYPE_BASE64 = 1, /**< %Base64 Encoding */ + _CERT_ENC_TYPE_PEM = 2, /**< %PEM Encoding */ + _CERT_ENC_TYPE_UNKNOWN = 9999, +}; //_CertEncodingType + +enum _CertTrustType +{ + _CERT_TRUST_NONE = 0, + _CERT_TRUST_PHONE_ROOT_CA = 1, + _CERT_TRUST_PHONE_DOMAIN = 2, + _CERT_TRUST_SIM_ROOT_CA = 4, + _CERT_TRUST_SIM_DOMAIN = 8, + _CERT_TRUST_DEV_ROOT_CA = 16, + _CERT_TRUST_DEV_DOMAIN = 32, + _CERT_TRUST_OSP_ROOT_CA = 64, + _CERT_TRUST_WRT_CA = 128, + _CERT_TRUST_CSC_CA = 256, +}; //_CertTrustType + +enum _CertExt +{ + _CERT_EXT_BASIC_CONTRAINTS = 0, // critical + _CERT_EXT_CRL_DISTRIBUTION_POINTS = 1, // non-critical + _CERT_EXT_KEY_USAGE = 2, // critical + _CERT_EXT_AUTHORITY_KEY_IDENTIFIER = 3, // non-critical + _CERT_EXT_SUBJECT_KEY_IDENTIFIER = 4, // non-critical + _CERT_EXT_CERTIFICATE_POLICIES = 5, // not used + _CERT_EXT_EXT_KEY_USAGE = 6, // critical + _CERT_EXT_OCSP_NONCE = 7, // non-critical + _CERT_EXT_OCSP_NO_CHECK = 8, // non-critical + _CERT_EXT_OCSP = 9, + _CERT_EXT_OCSP_SIGNING = 10, + _CERT_EXT_AUTHORITY_INFO_ACCESS = 11, //OCSP Responder url + _CERT_EXT_OMA_DRM_AGENT = 12, + _CERT_EXT_OMA_RIGHTS_ISSUER = 13, + _CERT_EXT_REVOKED_CERTIFICATE_RANGE = 14, + _CERT_EXT_ISSUING_DISTRIBUTION_POINT = 15, + _CERT_EXT_CRL_NUMBER = 16, + _CERT_EXT_CA_ISSUERS = 17, + _CERT_EXT_SUB_ALT_NAME = 18, + _CERT_EXT_SUB_DIR_ATTR = 19, + _CERT_EXT_PRI_KEY_USAGE_PER = 20, + _CERT_EXT_ISSUER_ALT_NAME = 21, + _CERT_EXT_REASON_CODE = 22, + _CERT_EXT_INSTRUCTION_CODE = 23, + _CERT_EXT_INVALID_DATE = 24, + _CERT_EXT_DELTA_CRL_INDI = 25, + _CERT_EXT_CERTIFICATE_ISSUER = 26, + _CERT_EXT_NAME_CONSTRAINT = 27, + _CERT_EXT_POLICY_MAPPING = 28, + _CERT_EXT_POLICY_CONSTRAINTS = 29, + _CERT_EXT_UNKNOWN = 9999, // non-critical +}; //_CertExt + +enum _CertPathType +{ + _CERT_PATH_CA_CERT = 0, + _CERT_PATH_USER_CERT = 1, + _CERT_PATH_PRIVATE_KEY = 2, + _CERT_PATH_UNKNOWN = 9999 +}; //_CertPathType + +struct _CertExtensionInfo +{ + _CertExt CertExtType; + bool CertExtCritical; + byte* CertExtValue; + int CertExtLength; + _CertExtensionInfo* pCertExtNext; +}; //_CertExtensionInfo + +struct _CertFieldInfos +{ + // SIM or Terminal Certificates + _CaCertType certType; + int certFileId; + char serialNo[_MAX_SERIAL_NUMBER_SIZE + 1]; + char sigAlgorithm[_MAX_CERT_ALGORITHM_SIZE + 1]; + char validityFrom[_MAX_CERT_VALIDITY_SIZE + 1]; + char validityTo[_MAX_CERT_VALIDITY_SIZE + 1]; + char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE + 2]; + char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE + 2]; + char fingerPrint[_MAX_CERT_FINGERPRINT_SIZE + 1]; + int fingerPrintLen; + char publicKey[_MAX_CERT_PUBLIC_KEY_SIZE + 1]; + char certTypeFormat[_MAX_CERT_TYPE_SIZE + 1]; + int certVersion; + char certTitle[_MAX_ISSUER_SUBJECT_NAME_SIZE + 1]; + char certSubTitle[_MAX_ISSUER_SUBJECT_NAME_SIZE + 1]; +}; //_CertFieldInfos + +struct _CertRootList +{ + _CertFormat format; + int length; + byte certificate[_MAX_CERTIFICATE_SIZE]; + _CertRootList* pNext; + +}; //_CertRootList; + + +struct _CertificateListInfo +{ + int certFileId; + _CertFormat format; + _CaCertType certType; + int length; + int priKeyLen; //length of a private key + byte certificate[_MAX_CERTIFICATE_SIZE]; + byte privatekey[_MAX_CERT_PRIVATE_KEY_SIZE]; // buffer with the private key + _CertificateListInfo* pNext; + +}; //_CertificateListInfo; + +/** + * @struct _CertInfo + * @brief This struct represent a certificate information. + * @since 2.1 + */ +struct _CertInfo +{ + int certId; /**< %Certificate id as in database */ + _CertFormat certFormat; /**< %Certificate format */ + _CaCertType certType; /**< %Certificate type */ + int certLength; /**< %Certificate buffer length */ + int privateKeyLen; /**< %Private key length */ + byte certificate[_MAX_CERTIFICATE_SIZE]; /**< %Certificate buffer */ + byte privatekey[_MAX_CERT_PRIVATE_KEY_SIZE]; /**< %Private key buffer */ + +}; //_CertInfo; + +struct _CertRootCaInfo +{ + _CertRootList* pRootList; + _CertRootList* pCurrRootList; + int curPos; + int count; +}; //_CertRootCaInfo + +} } } //Tizen::Security::Cert + +#endif // _FSEC_INTERNAL_CERT_TYPES_H_ diff --git a/src/security/inc/FSec_AccessControlTypes.h b/src/security/inc/FSec_AccessControlTypes.h new file mode 100644 index 0000000..c4be9aa --- /dev/null +++ b/src/security/inc/FSec_AccessControlTypes.h @@ -0,0 +1,397 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_AccessControlTypes.h + * @brief This is the header file for the _AccessControl. + * This header file contains the declarations of the _AccessControl. + */ + +#ifndef _FSEC_INTERNAL_ACCESS_CONTROL_TYPES_H_ +#define _FSEC_INTERNAL_ACCESS_CONTROL_TYPES_H_ + +#include +#include + +namespace Tizen { namespace Security +{ + +enum _Privilege +{ + _PRV_ALARM = 0, + _PRV_APPLICATION_KILL, + _PRV_APPLICATION_LAUNCH, + _PRV_APPMANAGER_LAUNCH, + _PRV_APPSETTING, + _PRV_APPUSAGE, + _PRV_AUDIOMANAGER_ROUTE, + _PRV_AUDIOMANAGER_SESSION, + _PRV_AUDIOMANAGER_VOIPSESSION, + _PRV_AUDIORECORDER, + _PRV_BLUETOOTH_ADMIN, + _PRV_BLUETOOTH_GAP, + _PRV_BLUETOOTH_HEALTH, + _PRV_BLUETOOTH_OPP, + _PRV_BLUETOOTH_SPP, + _PRV_BLUETOOTHMANAGER, + _PRV_CALENDAR_READ, + _PRV_CALENDAR_WRITE, + _PRV_CALLFORWARD, + _PRV_CALLHISTORY_READ, + _PRV_CALLHISTORY_WRITE, + _PRV_CAMERA, + _PRV_CELLBROADCAST, + _PRV_CERTIFICATE_READ, + _PRV_CERTIFICATE_WRITE, + _PRV_CONTACT_READ, + _PRV_CONTACT_WRITE, + _PRV_CONTENT_READ, + _PRV_CONTENT_WRITE, + _PRV_CUSTOMNETACCOUNT, + _PRV_DNS, + _PRV_DOWNLOAD, + _PRV_DRMSERVICE, + _PRV_HTTP, + _PRV_IME, + _PRV_IMEMANAGER, + _PRV_INPUTMANAGER, + _PRV_LOCATION, + _PRV_MESSAGING_EMAIL, + _PRV_MESSAGING_MMS, + _PRV_MESSAGING_SMS, + _PRV_NETWORK_ACCOUNT, + _PRV_NETWORK_CONNECTION, + _PRV_NETWORK_STATISTICS_READ, + _PRV_NETWORK_STATISTICS_WRITE, + _PRV_NETWORKMANAGER, + _PRV_NFC_ADMIN, + _PRV_NFC_CARDEMULATION, + _PRV_NFC_COMMON, + _PRV_NFC_P2P, + _PRV_NFC_TAG, + _PRV_NOTIFICATION, + _PRV_NOTIFICATIONMANAGER, + _PRV_PACKAGEINFO, + _PRV_PACKAGELICENSEMANAGER, + _PRV_PACKAGEMANAGER_INSTALL, + _PRV_PACKAGESETTING, + _PRV_PLATFORMINFO, + _PRV_POWER, + _PRV_PUSH, + _PRV_SETTING, + _PRV_SMSTRIGGER, + _PRV_SOCKET, + _PRV_SYSTEMINFO, + _PRV_SYSTEMSETTING_READ, + _PRV_SYSTEMSETTING_WRITE, + _PRV_TELEPHONYMANAGER, + _PRV_UIMANAGER, + _PRV_USERIDENTITY, + _PRV_VIBRATOR, + _PRV_VIDEORECORDER, + _PRV_WAPPUSH, + _PRV_WEB_PRIVACY, + _PRV_WEB_SERVICE, + _PRV_WIFI_ADMIN, + _PRV_WIFI_READ, + _PRV_WIFI_WIFIDIRECT_ADMIN, + _PRV_WIFI_WIFIDIRECT_READ, + _PRV_WIFIMANAGER, + _MAX_PRIVILEGE_ENUM +}; + +typedef struct +{ + const wchar_t* privilegeString; + _Privilege privilege; + +} _PrivilegeStringList; + +const static _PrivilegeStringList privilegeListTable[_MAX_PRIVILEGE_ENUM] = +{ + {L"alarm", _PRV_ALARM}, + {L"application.kill", _PRV_APPLICATION_KILL}, + {L"application.launch", _PRV_APPLICATION_LAUNCH}, + {L"appmanager.launch", _PRV_APPMANAGER_LAUNCH}, + {L"appsetting", _PRV_APPSETTING}, + {L"appusage", _PRV_APPUSAGE}, + {L"audiomanager.route", _PRV_AUDIOMANAGER_ROUTE}, + {L"audiomanager.session", _PRV_AUDIOMANAGER_SESSION}, + {L"audiomanager.voipsession", _PRV_AUDIOMANAGER_VOIPSESSION}, + {L"audiorecorder", _PRV_AUDIORECORDER}, + {L"bluetooth.admin", _PRV_BLUETOOTH_ADMIN}, + {L"bluetooth.gap", _PRV_BLUETOOTH_GAP}, + {L"bluetooth.health", _PRV_BLUETOOTH_HEALTH}, + {L"bluetooth.opp", _PRV_BLUETOOTH_OPP}, + {L"bluetooth.spp", _PRV_BLUETOOTH_SPP}, + {L"bluetoothmanager", _PRV_BLUETOOTHMANAGER}, + {L"calendar.read", _PRV_CALENDAR_READ}, + {L"calendar.write", _PRV_CALENDAR_WRITE}, + {L"callforward", _PRV_CALLFORWARD}, + {L"callhistory.read", _PRV_CALLHISTORY_READ}, + {L"callhistory.write", _PRV_CALLHISTORY_WRITE}, + {L"camera", _PRV_CAMERA}, + {L"cellbroadcast", _PRV_CELLBROADCAST}, + {L"certificate.read", _PRV_CERTIFICATE_READ}, + {L"certificate.write", _PRV_CERTIFICATE_WRITE}, + {L"contact.read", _PRV_CONTACT_READ}, + {L"contact.write", _PRV_CONTACT_WRITE}, + {L"content.read", _PRV_CONTENT_READ}, + {L"content.write", _PRV_CONTENT_WRITE}, + {L"customnetaccount", _PRV_CUSTOMNETACCOUNT}, + {L"dns", _PRV_DNS}, + {L"download", _PRV_DOWNLOAD}, + {L"drmservice", _PRV_DRMSERVICE}, + {L"http", _PRV_HTTP}, + {L"ime", _PRV_IME}, + {L"imemanager", _PRV_IMEMANAGER}, + {L"inputmanager", _PRV_INPUTMANAGER}, + {L"location", _PRV_LOCATION}, + {L"messaging.email", _PRV_MESSAGING_EMAIL}, + {L"messaging.mms", _PRV_MESSAGING_MMS}, + {L"messaging.sms", _PRV_MESSAGING_SMS}, + {L"network.account", _PRV_NETWORK_ACCOUNT}, + {L"network.connection", _PRV_NETWORK_CONNECTION}, + {L"network.statistics.read", _PRV_NETWORK_STATISTICS_READ}, + {L"network.statistics.write", _PRV_NETWORK_STATISTICS_WRITE}, + {L"networkmanager", _PRV_NETWORKMANAGER}, + {L"nfc.admin", _PRV_NFC_ADMIN}, + {L"nfc.cardemulation", _PRV_NFC_CARDEMULATION}, + {L"nfc.common", _PRV_NFC_COMMON}, + {L"nfc.p2p", _PRV_NFC_P2P}, + {L"nfc.tag", _PRV_NFC_TAG}, + {L"notification", _PRV_NOTIFICATION}, + {L"notificationmanager", _PRV_NOTIFICATIONMANAGER}, + {L"packageinfo", _PRV_PACKAGEINFO}, + {L"packagelicensemanager", _PRV_PACKAGELICENSEMANAGER}, + {L"packagemanager.install", _PRV_PACKAGEMANAGER_INSTALL}, + {L"packagesetting", _PRV_PACKAGESETTING}, + {L"platforminfo", _PRV_PLATFORMINFO}, + {L"power", _PRV_POWER}, + {L"push", _PRV_PUSH}, + {L"setting", _PRV_SETTING}, + {L"smstrigger", _PRV_SMSTRIGGER}, + {L"socket", _PRV_SOCKET}, + {L"systeminfo", _PRV_SYSTEMINFO}, + {L"systemsetting.read", _PRV_SYSTEMSETTING_READ}, + {L"systemsetting.write", _PRV_SYSTEMSETTING_WRITE}, + {L"telephonymanager", _PRV_TELEPHONYMANAGER}, + {L"uimanager", _PRV_UIMANAGER}, + {L"useridentity", _PRV_USERIDENTITY}, + {L"vibrator", _PRV_VIBRATOR}, + {L"videorecorder", _PRV_VIDEORECORDER}, + {L"wappush", _PRV_WAPPUSH}, + {L"web.privacy", _PRV_WEB_PRIVACY}, + {L"web.service", _PRV_WEB_SERVICE}, + {L"wifi.admin", _PRV_WIFI_ADMIN}, + {L"wifi.read", _PRV_WIFI_READ}, + {L"wifi.wifidirect.admin", _PRV_WIFI_WIFIDIRECT_ADMIN}, + {L"wifi.wifidirect.read", _PRV_WIFI_WIFIDIRECT_READ}, + {L"wifimanager", _PRV_WIFIMANAGER}, +}; + +enum _PrivilegeApiVersion +{ + _PRV_API_VER_2_0 = 0, + _PRV_API_VER_MAX +}; + +const static Tizen::Base::_ApiVisibility visibilityLevelListTable[_MAX_PRIVILEGE_ENUM][_PRV_API_VER_MAX] = +{ + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // alarm + { Tizen::Base::_API_VISIBILITY_PARTNER }, // application.kill + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // application.launch + { Tizen::Base::_API_VISIBILITY_PARTNER }, // appmanager.launch + { Tizen::Base::_API_VISIBILITY_PARTNER }, // appsetting + { Tizen::Base::_API_VISIBILITY_PARTNER }, // appusage + { Tizen::Base::_API_VISIBILITY_PARTNER }, // audiomanager.route + { Tizen::Base::_API_VISIBILITY_PARTNER }, // audiomanager.session + { Tizen::Base::_API_VISIBILITY_PARTNER }, // audiomanager.voipsession + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // audiorecorder + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // bluetooth.admin + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // bluetooth.gap + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // bluetooth.health + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // bluetooth.opp + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // bluetooth.spp + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // bluetoothmanager + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // calendar.read + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // calendar.write + { Tizen::Base::_API_VISIBILITY_PARTNER_OPERATOR }, // callforward + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // callhistory.read + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // callhistory.write + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // camera + { Tizen::Base::_API_VISIBILITY_PARTNER_OPERATOR }, // cellbroadcast + { Tizen::Base::_API_VISIBILITY_PARTNER }, // certificate.read + { Tizen::Base::_API_VISIBILITY_PARTNER }, // certificate.write + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // contact.read + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // contact.write + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // content.read + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // content.write + { Tizen::Base::_API_VISIBILITY_PARTNER }, // customnetaccount + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // dns + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // download + { Tizen::Base::_API_VISIBILITY_PARTNER_OPERATOR }, // drmservice + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // http + { Tizen::Base::_API_VISIBILITY_PARTNER }, // ime + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // imemanager + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // inputmanager + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // location + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // messaging.email + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // messaging.mms + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // messaging.sms + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // network.account + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // network.connection + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // network.statistics.read + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // network.statistics.write + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // networkmanager + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // nfc.admin + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // nfc.cardemulation + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // nfc.common + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // nfc.p2p + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // nfc.tag + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // notification + { Tizen::Base::_API_VISIBILITY_PARTNER }, // notificationmanager + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // packageinfo + { Tizen::Base::_API_VISIBILITY_PARTNER_OPERATOR }, // packagelicensemanager + { Tizen::Base::_API_VISIBILITY_PARTNER_OPERATOR }, // packagemanager.install + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // packagesetting + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // platforminfo + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // power + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // push + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // setting + { Tizen::Base::_API_VISIBILITY_PARTNER }, // smstrigger + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // socket + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // systeminfo + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // systemsetting.read + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // systemsetting.write + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // telephonymanager + { Tizen::Base::_API_VISIBILITY_PARTNER_OPERATOR }, // uimanager + { Tizen::Base::_API_VISIBILITY_PARTNER }, // useridentity + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // vibrator + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // videorecorder + { Tizen::Base::_API_VISIBILITY_PARTNER_OPERATOR }, // wappush + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // web.privacy + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // web.service + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // wifi.admin + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // wifi.read + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // wifi.wifidirect.admin + { Tizen::Base::_API_VISIBILITY_PUBLIC }, // wifi.wifidirect.read + { Tizen::Base::_API_VISIBILITY_PARTNER_MANUFACTURER }, // wifimanager +}; + +enum _PrivilegeLevel +{ + _PRV_LEVEL_USER = 0, + _PRV_LEVEL_SYSTEM +}; + +const static _PrivilegeLevel privilegeLevelListTable[_MAX_PRIVILEGE_ENUM][_PRV_API_VER_MAX] = +{ + { _PRV_LEVEL_USER }, // alarm + { _PRV_LEVEL_SYSTEM }, // application.kill + { _PRV_LEVEL_USER }, // application.launch + { _PRV_LEVEL_SYSTEM }, // appmanager.launch + { _PRV_LEVEL_USER }, // appsetting + { _PRV_LEVEL_USER }, // appusage + { _PRV_LEVEL_USER }, // audiomanager.route + { _PRV_LEVEL_USER }, // audiomanager.session + { _PRV_LEVEL_USER }, // audiomanager.voipsession + { _PRV_LEVEL_USER }, // audiorecorder + { _PRV_LEVEL_USER }, // bluetooth.admin + { _PRV_LEVEL_USER }, // bluetooth.gap + { _PRV_LEVEL_USER }, // bluetooth.health + { _PRV_LEVEL_USER }, // bluetooth.opp + { _PRV_LEVEL_USER }, // bluetooth.spp + { _PRV_LEVEL_SYSTEM }, // bluetoothmanager + { _PRV_LEVEL_USER }, // calendar.read + { _PRV_LEVEL_USER }, // calendar.write + { _PRV_LEVEL_SYSTEM }, // callforward + { _PRV_LEVEL_USER }, // callhistory.read + { _PRV_LEVEL_USER }, // callhistory.write + { _PRV_LEVEL_USER }, // camera + { _PRV_LEVEL_USER }, // cellbroadcast + { _PRV_LEVEL_SYSTEM }, // certificate.read + { _PRV_LEVEL_SYSTEM }, // certificate.write + { _PRV_LEVEL_USER }, // contact.read + { _PRV_LEVEL_USER }, // contact.write + { _PRV_LEVEL_USER }, // content.read + { _PRV_LEVEL_USER }, // content.write + { _PRV_LEVEL_USER }, // customnetaccount + { _PRV_LEVEL_USER }, // dns + { _PRV_LEVEL_USER }, // download + { _PRV_LEVEL_USER }, // drmservice + { _PRV_LEVEL_USER }, // http + { _PRV_LEVEL_USER }, // ime + { _PRV_LEVEL_SYSTEM }, // imemanager + { _PRV_LEVEL_USER }, // inputmanager + { _PRV_LEVEL_USER }, // location + { _PRV_LEVEL_USER }, // messaging.email + { _PRV_LEVEL_USER }, // messaging.mms + { _PRV_LEVEL_USER }, // messaging.sms + { _PRV_LEVEL_USER }, // network.account + { _PRV_LEVEL_USER }, // network.connection + { _PRV_LEVEL_USER }, // network.statistics.read + { _PRV_LEVEL_USER }, // network.statistics.write + { _PRV_LEVEL_SYSTEM }, // networkmanager + { _PRV_LEVEL_USER }, // nfc.admin + { _PRV_LEVEL_USER }, // nfc.cardemulation + { _PRV_LEVEL_USER }, // nfc.common + { _PRV_LEVEL_USER }, // nfc.p2p + { _PRV_LEVEL_USER }, // nfc.tag + { _PRV_LEVEL_USER }, // notification + { _PRV_LEVEL_USER }, // notificationmanager + { _PRV_LEVEL_USER }, // packageinfo + { _PRV_LEVEL_USER }, // packagelicensemanager + { _PRV_LEVEL_SYSTEM }, // packagemanager.install + { _PRV_LEVEL_USER }, // packagesetting + { _PRV_LEVEL_USER }, // platforminfo + { _PRV_LEVEL_USER }, // power + { _PRV_LEVEL_USER }, // push + { _PRV_LEVEL_USER }, // setting + { _PRV_LEVEL_USER }, // smstrigger + { _PRV_LEVEL_USER }, // socket + { _PRV_LEVEL_USER }, // systeminfo + { _PRV_LEVEL_SYSTEM }, // systemsetting.read + { _PRV_LEVEL_SYSTEM }, // systemsetting.write + { _PRV_LEVEL_SYSTEM }, // telephonymanager + { _PRV_LEVEL_SYSTEM }, // uimanager + { _PRV_LEVEL_SYSTEM }, // useridentity + { _PRV_LEVEL_USER }, // vibrator + { _PRV_LEVEL_USER }, // videorecorder + { _PRV_LEVEL_USER }, // wappush + { _PRV_LEVEL_USER }, // web.privacy + { _PRV_LEVEL_USER }, // web.service + { _PRV_LEVEL_USER }, // wifi.admin + { _PRV_LEVEL_USER }, // wifi.read + { _PRV_LEVEL_USER }, // wifi.wifidirect.admin + { _PRV_LEVEL_USER }, // wifi.wifidirect.read + { _PRV_LEVEL_SYSTEM }, // wifimanager +}; + +const int MAX_BITWISE_PRIV_SIZE = (((_MAX_PRIVILEGE_ENUM - 1) / 32) + 1) * 4; +const int MAX_APP_ID_SIZE = 10; +const int MAX_CACHE_SIZE = 20; +const int MAX_ACTIVE_CACHE_SIZE = 5; + +const int _KEY_LEN = 16; +const int _IV_LEN = 16; +const int _BITS_IN_BYTE = 8; + +}; +} // Tizen::Security + +#endif // _FSEC_INTERNAL_ACCESS_CONTROL_TYPES_H_ diff --git a/src/security/inc/FSec_AccessController.h b/src/security/inc/FSec_AccessController.h new file mode 100644 index 0000000..c08fff0 --- /dev/null +++ b/src/security/inc/FSec_AccessController.h @@ -0,0 +1,92 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_AccessController.h + * @brief This is the header file for the _AccessController. + * This header file contains the declarations of the _AccessController. + */ + +#ifndef _FSEC_INTERNAL_ACCESS_CONTROLLER_H_ +#define _FSEC_INTERNAL_ACCESS_CONTROLLER_H_ + +#include + +#include "FSec_AccessControlTypes.h" + +namespace Tizen { namespace Security +{ + +class _PrivilegeManager; + +/** + * @class _AccessController + * @brief This class provides a way to check the privilege and visibility. + * @since 2.0 + * + * This class provides a way to check the privilege and visibility. + */ +class _OSP_EXPORT_ _AccessController +{ + +public: + /** + * Checks whether the application has a privilege and a visibility to invoke the API. + * + * @since 2.0 + * @return An error code + * @param[in] appId The application ID. + * @param[in] privilege A value of enumerator of the specified privilege. + * @exception E_SUCCESS The method is successful and request is granted. + * @exception E_DATA_NOT_FOUND The privilege information does not exist. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege. + * @exception E_SYSTEM An unexpected system error occurred. + */ + static result CheckSystemPrivilege(const Tizen::App::AppId& appId, _Privilege privilege); + + /** + * Checks whether the application has a privilege and a visibility to invoke the API. + * + * @since 2.0 + * @return An error code + * @param[in] privilege A value of enumerator of the specified privilege. + * @exception E_SUCCESS The method is successful and request is granted. + * @exception E_DATA_NOT_FOUND The privilege information does not exist. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_PRIVILEGE_DENIED The application does not have the privilege. + * @exception E_SYSTEM An unexpected system error occurred. + */ + static result CheckUserPrivilege(_Privilege privilege); + +private: + + _AccessController(void); + ~_AccessController(void); + + _AccessController(const _AccessController& rhs); + _AccessController& operator =(const _AccessController& rhs); + + static void Initialize(void); + + static _PrivilegeManager* __pPrivilegeManager; + +}; // _AccessController + +}} // Tizen::Security + +#endif // _FSEC_INTERNAL_ACCESS_CONTROLLER_H_ diff --git a/src/security/inc/FSec_DeviceKeyGenerator.h b/src/security/inc/FSec_DeviceKeyGenerator.h new file mode 100644 index 0000000..012bea8 --- /dev/null +++ b/src/security/inc/FSec_DeviceKeyGenerator.h @@ -0,0 +1,77 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_DeviceKey.h + * @brief This is the header file for the %_DeviceKey class. + * + * This header file contains the declarations of the %_DeviceKey class. + */ +#ifndef _FSEC_INTERNAL_DEVICE_KEY_GENERATOR_H_ +#define _FSEC_INTERNAL_DEVICE_KEY_GENERATOR_H_ + +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +}} + + +namespace Tizen { namespace Security +{ +class ISecretKey; + +/** + * @class _DeviceKeyGenerator + * @brief This class generates a device unique key. + * @since 2.1 + * + * The %_DeviceKeyGenerator class generates a device unique key. + * + */ + + +class _OSP_EXPORT_ _DeviceKeyGenerator +{ +public: + /** + * Gets a device unique key. + * + * @since 2.1 + * @return The device unique key + * @param[in] keySize The size of device unique key. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + * + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static ISecretKey* GenerateDeviceKeyN(int keySize); + static ISecretKey* GenerateDeviceKeyN(Tizen::Base::String& appId, int keySize); + +private: + _DeviceKeyGenerator(void); + ~_DeviceKeyGenerator(void); + _DeviceKeyGenerator(const _DeviceKeyGenerator& value); + _DeviceKeyGenerator& operator =(const _DeviceKeyGenerator& value); + +}; //_DeviceKeyGenerator +}} + +#endif // _FSEC_INTERNAL_DEVICE_KEY_GENERATOR_H_ diff --git a/src/security/inc/FSec_PrivilegeManager.h b/src/security/inc/FSec_PrivilegeManager.h new file mode 100644 index 0000000..3123283 --- /dev/null +++ b/src/security/inc/FSec_PrivilegeManager.h @@ -0,0 +1,115 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_PrivilegeManager.h + * @brief This is the header file for the _PrivilegeManager. + * This header file contains the declarations of the _PrivilegeManager. + */ + +#ifndef _FSEC_INTERNAL_PRIVILEGE_MANAGER_H_ +#define _FSEC_INTERNAL_PRIVILEGE_MANAGER_H_ + +#include +#include + +#include "FSec_AccessControlTypes.h" + +namespace Tizen { namespace Base { namespace Collection +{ +class IList; +}}} + +namespace Tizen { namespace Base +{ +class String; +}} + +class PrivilegeService; + +namespace Tizen { namespace Security +{ + +class _PrivilegeCache; +class _PrivilegeInfo; + +/** + * @class _PrivilegeManager + * @brief This class provides a way to manage the privilege information. + * @since 2.0 + * + * This class provides a way to manage the privilege information. + * + */ + +class _OSP_EXPORT_ _PrivilegeManager + : public Tizen::Base::Object + , public Tizen::App::Package::IPackageInstallationEventListener +{ + +public: + + /** + * Gets the list of privilege string. + * + * @since 2.0 + * @return A list of privilege string + * @param[in] appId The application ID. + * @exception E_SUCCESS The method is successful. + * @exception E_DATA_NOT_FOUND The privilege information does not exist. + * @exception E_SYSTEM An unexpected system error occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Tizen::Base::Collection::IList* GetPrivilegeListN(const Tizen::App::AppId& appId); + + virtual void OnPackageInstallationCompleted(const Tizen::App::PackageId& packageId, Tizen::App::Package::PackageInstallationResult installationResult); + virtual void OnPackageInstallationInProgress(const Tizen::App::PackageId& packageId, int progress) {} + virtual void OnPackageUninstallationCompleted(const Tizen::App::PackageId& packageId, bool uninstallationResult) {} + + +private: + + _PrivilegeManager(void); + virtual ~_PrivilegeManager(void); + + result Construct(void); + static _PrivilegeManager* GetInstance(void); + + static result RetrieveCipherPrivilege(const Tizen::App::AppId& appId, Tizen::Base::String& encryptedPrivileges, Tizen::Base::String& checksum); + static result RetrieveCipherPrivilegeEx(const Tizen::App::AppId& appId, Tizen::Base::String& encryptedPrivileges, Tizen::Base::String& checksum); + _PrivilegeInfo* RetrievePrivilegeInfoN(const Tizen::App::AppId& appId) const; + + static Tizen::Base::Collection::IList* UnpackPrivilegeN(const byte* pBitwisePrivilege); + + _PrivilegeManager(const _PrivilegeManager& rhs); + _PrivilegeManager& operator =(const _PrivilegeManager& rhs); + + static void InitInstance(void); + +private: + + _PrivilegeCache* __pPrivilegeCache; + static _PrivilegeManager* __pPrivilegeManagerInstance; + + friend class ::PrivilegeService; + friend class _AccessController; + +}; // _PrivilegeManager + +}} // Tizen::Security + +#endif // _FSEC_INTERNAL_PRIVILEGE_MANAGER_H_ diff --git a/src/security/inc/FSec_PrivilegeManagerMessage.h b/src/security/inc/FSec_PrivilegeManagerMessage.h new file mode 100644 index 0000000..8b34683 --- /dev/null +++ b/src/security/inc/FSec_PrivilegeManagerMessage.h @@ -0,0 +1,30 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSec_PrivilegeManagerMessage.h + * @brief This is the message type of the IPC communication of _AccessControl and _PrivilegeManager. + */ + +#include +#include +#include + +#define IPC_MESSAGE_START PrivilegeManagerMsgStart + +IPC_SYNC_MESSAGE_CONTROL0_3(PrivilegeManagerMsg_retrieve, Tizen::Base::String, Tizen::Base::String, result) +IPC_SYNC_MESSAGE_CONTROL0_3(PrivilegeManagerMsg_retrieveEx, Tizen::Base::String, Tizen::Base::String, result) diff --git a/src/system/CMakeLists.txt b/src/system/CMakeLists.txt new file mode 100755 index 0000000..410fdb7 --- /dev/null +++ b/src/system/CMakeLists.txt @@ -0,0 +1,71 @@ +SET (this_target system) + +INCLUDE_DIRECTORIES( + ${SLP_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/inc + ./ + inc + ${CMAKE_SOURCE_DIR}/src/base/inc + ${CMAKE_SOURCE_DIR}/src/io/inc + ${CMAKE_SOURCE_DIR}/src/locales + ${CMAKE_SOURCE_DIR}/src/locales/inc + ${CMAKE_SOURCE_DIR}/src/app/inc + ${CMAKE_SOURCE_DIR}/src/security/inc + ${CMAKE_SOURCE_DIR}/src/io/ext/chromium + /usr/include/network + ) + +SET (${this_target}_SOURCE_FILES + FSysAlarm.cpp + FSys_AlarmImpl.cpp + FSysBattery.cpp + FSys_BatteryImpl.cpp + FSysDeviceManager.cpp + FSys_DeviceManagerImpl.cpp + FSysPowerManager.cpp + FSys_PowerManagerImpl.cpp + FSysRuntimeInfo.cpp + FSys_RuntimeInfoImpl.cpp + FSysSettingInfo.cpp + FSys_SettingInfoImpl.cpp + FSys_DeviceId.cpp + FSysSystemInfo.cpp + FSys_SystemInfoImpl.cpp + FSysSystemTime.cpp + FSys_SystemTimeImpl.cpp + FSysVibrator.cpp + FSys_VibratorImpl.cpp + FSys_DeviceManagerEventProvider.cpp + FSys_SystemResource.cpp + FSysEnvironment.cpp + FSys_EnvironmentImpl.cpp + FSys_DeviceEventListenerContainer.cpp + FSys_SettingManager.cpp + FSys_SettingIcu.cpp +) + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") + +## SET EXTRA COMPILER FLAGS +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fPIC" ) + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} STATIC ${${this_target}_SOURCE_FILES}) + +## SET LINKER FLAGS +SET(CMAKE_SHARED_LINKER_FLAGS -Wl, --no-undefined) + +TARGET_LINK_LIBRARIES(${this_target} "-lnetwork") +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-network-wifi") +TARGET_LINK_LIBRARIES(${this_target} "-lwifi-direct") +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-network-bluetooth") +TARGET_LINK_LIBRARIES(${this_target} "-lcapi-network-tethering") +TARGET_LINK_LIBRARIES(${this_target} "-lhaptic") +TARGET_LINK_LIBRARIES(${this_target} "-lSLP-tapi") +TARGET_LINK_LIBRARIES(${this_target} "-lsysman") diff --git a/src/system/FSysAlarm.cpp b/src/system/FSysAlarm.cpp new file mode 100644 index 0000000..fe8bd52 --- /dev/null +++ b/src/system/FSysAlarm.cpp @@ -0,0 +1,122 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysAlarm.cpp + * @brief This is the implementation file for Alarm class. + */ + + +#include + +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Security; + +namespace Tizen { namespace System +{ + +Alarm::Alarm(void) + : __pAlarmImpl(null) +{ +} + +Alarm::~Alarm(void) +{ + delete __pAlarmImpl; + __pAlarmImpl = null; +} + +result +Alarm::Construct(IAlarmEventListener& listener) +{ + result r = E_SUCCESS; + + if (!__pAlarmImpl) + { + __pAlarmImpl = new (std::nothrow) _AlarmImpl(this); + SysTryReturnResult(NID_SYS, __pAlarmImpl, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + __pAlarmImpl->Construct(); + } + + r = __pAlarmImpl->SetAlarmEventListener(&listener); + SysTryReturnResult(NID_SYS, !IsFailed(r), r, "Construction is failed"); + + return E_SUCCESS; +} + +result +Alarm::Set(const DateTime& startTime) +{ + return this->Set(startTime, 0, null); +} + +result +Alarm::Set(const DateTime& startTime, int period, const DateTime* pEndTime) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_ALARM); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + SysAssertf(__pAlarmImpl != null, "Not yet constructed. Construct() should be called before use."); + if(pEndTime != null) + { + SysTryReturn(NID_SYS, startTime <= *pEndTime, E_INVALID_ARG, E_INVALID_ARG, + "[E_INVALID_ARG] end time(%ls) is early than start time(%ls)", + pEndTime->ToString().GetPointer(), startTime.ToString().GetPointer()); + } + SysTryReturn(NID_SYS, period >= 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The period(%d) must be greater than 0.", period); + + return __pAlarmImpl->Set(startTime, period, pEndTime); +} + +result +Alarm::Cancel(void) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_ALARM); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + SysAssertf(__pAlarmImpl != null, "Not yet constructed. Construct() should be called before use."); + r = __pAlarmImpl->Cancel(); + return r; +} + +const DateTime +Alarm::GetStartTime(void) const +{ + return __pAlarmImpl->GetStartTime(); +} + +int +Alarm::GetPeriod(void) const +{ + return __pAlarmImpl->GetPeriod(); +} + +const DateTime* +Alarm::GetEndTime(void) const +{ + return __pAlarmImpl->GetEndTime(); +} + +} } // Tizen::System diff --git a/src/system/FSysBattery.cpp b/src/system/FSysBattery.cpp new file mode 100644 index 0000000..7bb94c1 --- /dev/null +++ b/src/system/FSysBattery.cpp @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + + +/** + * @file FSysBattery.cpp + * @brief This is the implementation file for Battery class. + */ + +#include +#include + +#include +#include +#include +#include "FSys_BatteryImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + +namespace Tizen { namespace System +{ + +Battery::Battery(void) +{ +} + +Battery::~Battery(void) +{ +} + +result +Battery::IsCharging(bool& charging) +{ + return _BatteryImpl::IsCharging(charging); +} + +result +Battery::GetCurrentLevelInPercentage(int& level) +{ + return _BatteryImpl::GetCurrentLevelInPercentage(level); +} + +result +Battery::GetCurrentLevel(BatteryLevel& level) +{ + return _BatteryImpl::GetCurrentLevel(level); +} + +} } // Tizen::System diff --git a/src/system/FSysDeviceManager.cpp b/src/system/FSysDeviceManager.cpp new file mode 100644 index 0000000..d256bf9 --- /dev/null +++ b/src/system/FSysDeviceManager.cpp @@ -0,0 +1,78 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + + +/** + * @file FSysDeviceManager.cpp + * @brief This is the implementation for the DeviceManager class. + */ + +#include + +#include +#include +#include +#include "FSys_DeviceManagerImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Security; + +namespace Tizen { namespace System +{ + +DeviceManager::DeviceManager(void) + :__pDeviceManagerImpl(null) +{ +} + +DeviceManager::~DeviceManager(void) +{ +} + +result +DeviceManager::GetState(DeviceType deviceType, Tizen::Base::String& state) +{ + _DeviceManagerImpl* pDeviceManagerImpl = _DeviceManagerImpl::GetInstance(); + SysTryReturnResult(NID_SYS, pDeviceManagerImpl != null, E_SYSTEM, "Failed to get _DeviceManagerImpl instance"); + return pDeviceManagerImpl->GetState(deviceType, state); +} + +result +DeviceManager::AddDeviceEventListener(DeviceType deviceType, IDeviceEventListener& listener) +{ + _DeviceManagerImpl* pDeviceManagerImpl = _DeviceManagerImpl::GetInstance(); + SysTryReturnResult(NID_SYS, pDeviceManagerImpl != null, E_SYSTEM, "Failed to get _DeviceManagerImpl instance"); + return pDeviceManagerImpl->AddDeviceEventListener(deviceType, &listener); +} + +result +DeviceManager::RemoveDeviceEventListener(DeviceType deviceType, IDeviceEventListener& listener) +{ + _DeviceManagerImpl* pDeviceManagerImpl = _DeviceManagerImpl::GetInstance(); + SysTryReturnResult(NID_SYS, pDeviceManagerImpl != null, E_SYSTEM, "Failed to get _DeviceManagerImpl instance"); + return pDeviceManagerImpl->RemoveDeviceEventListener(deviceType, &listener); +} + +result +DeviceManager::RemoveAllDeviceEventListeners(void) +{ + _DeviceManagerImpl* pDeviceManagerImpl = _DeviceManagerImpl::GetInstance(); + SysTryReturnResult(NID_SYS, pDeviceManagerImpl != null, E_SYSTEM, "Failed to get _DeviceManagerImpl instance"); + return pDeviceManagerImpl->RemoveAllDeviceEventListeners(); +} + +}} diff --git a/src/system/FSysEnvironment.cpp b/src/system/FSysEnvironment.cpp new file mode 100644 index 0000000..28036b9 --- /dev/null +++ b/src/system/FSysEnvironment.cpp @@ -0,0 +1,65 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysEnvironment.cpp + * @brief This is the implementation file for %Environment class. + */ + +#include + +#include +#include + +using namespace Tizen::Base; + +namespace Tizen { namespace System +{ + +Environment::Environment(void) +{ +} + +Environment::~Environment(void) +{ +} + +String +Environment::GetMediaPath(void) +{ + return _EnvironmentImpl::GetMediaPath(); +} + +String +Environment::GetDefaultDownloadPath(void) +{ + return _EnvironmentImpl::GetDefaultDownloadPath(); +} + +String +Environment::GetExternalStoragePath(void) +{ + return _EnvironmentImpl::GetExternalStoragePath(); +} + +String +Environment::GetPredefinedPath(PredefinedDirectoryType dirType) +{ + return _EnvironmentImpl::GetPredefinedPath(dirType); +} + +}} // Tizen::System diff --git a/src/system/FSysPowerManager.cpp b/src/system/FSysPowerManager.cpp new file mode 100644 index 0000000..8610334 --- /dev/null +++ b/src/system/FSysPowerManager.cpp @@ -0,0 +1,152 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysPowerManager.cpp + * @brief This is the implementation file for PowerManager class. + */ + +#include +#include + +#include +#include +#include +#include + +using namespace Tizen::Security; + +namespace Tizen { namespace System +{ + +PowerManager::PowerManager(void) + :__pPowerManagerImpl(null) +{ +} + +PowerManager::~PowerManager(void) +{ +} + +result +PowerManager::KeepScreenOnState(bool keepOn, bool dimming) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_POWER); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _PowerManagerImpl::KeepScreenOnState(keepOn, dimming); +} + +result +PowerManager::KeepCpuAwake(bool enable) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_POWER); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _PowerManagerImpl::KeepCpuAwake(enable); +} + +void +PowerManager::SetScreenEventListener(IScreenEventListener& listener) +{ + _PowerManagerImpl::SetScreenEventListener(listener); +} + +void +PowerManager::SetChargingEventListener(IChargingEventListener& listener) +{ + _PowerManagerImpl::SetChargingEventListener(listener); +} + +result +PowerManager::RestoreScreenBrightness(void) +{ + return _PowerManagerImpl::RestoreScreenBrightness(); +} +result +PowerManager::SetScreenBrightness(int brightness) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_POWER); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _PowerManagerImpl::SetScreenBrightness(brightness); +} + +int +PowerManager::GetScreenBrightness(void) +{ + return _PowerManagerImpl::GetScreenBrightness(); +} + +bool +PowerManager::IsScreenOn(void) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_POWER); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _PowerManagerImpl::IsScreenOn(); +} + +result +PowerManager::TurnScreenOn(void) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_POWER); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _PowerManagerImpl::TurnScreenOn(); +} + +result +PowerManager::TurnScreenOff(void) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_POWER); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _PowerManagerImpl::TurnScreenOff(); +} + +int +PowerManager::GetCurrentBatteryLevelInPercentage(void) +{ + return _PowerManagerImpl::GetCurrentBatteryLevelInPercentage(); +} + +BatteryLevel +PowerManager::GetCurrentBatteryLevel(void) +{ + return _PowerManagerImpl::GetCurrentBatteryLevel(); +} + +bool +PowerManager::IsCharging(void) +{ + return _PowerManagerImpl::IsCharging(); +} + +result +PowerManager::SetBatteryEventListener(IBatteryEventListener* pListener) +{ + return _PowerManagerImpl::SetBatteryEventListener(pListener); +} + +} } //Tizen::System diff --git a/src/system/FSysRuntimeInfo.cpp b/src/system/FSysRuntimeInfo.cpp new file mode 100644 index 0000000..ad102e7 --- /dev/null +++ b/src/system/FSysRuntimeInfo.cpp @@ -0,0 +1,94 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysRuntimeInfo.cpp + * @brief This is the implementation file for RuntimeInfo class. + * + * + * This file contains the implementation of RuntimeInfo class. + */ + +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Security; + +namespace Tizen { namespace System +{ + +RuntimeInfo::RuntimeInfo(void) + :__pRuntimeInfoImpl(null) +{ +} + +RuntimeInfo::~RuntimeInfo(void) +{ +} + +result +RuntimeInfo::GetValue(const String& key, String& value) +{ + return _RuntimeInfoImpl::GetValue(key, value); +} + +result +RuntimeInfo::GetValue(const String& key, int& value) +{ + return _RuntimeInfoImpl::GetValue(key, value); +} + +result +RuntimeInfo::GetValue(const String& key, long long& value) +{ + return _RuntimeInfoImpl::GetValue(key, value); +} + +result +RuntimeInfo::GetValue(const String& key, double& value) +{ + return _RuntimeInfoImpl::GetValue(key, value); +} + +result +RuntimeInfo::GetValue(const String& key, bool& value) +{ + return _RuntimeInfoImpl::GetValue(key, value); +} + +result +RuntimeInfo::GetValue(const String& key, UuId& value) +{ + return _RuntimeInfoImpl::GetValue(key, value); +} + +result +RuntimeInfo::GetValueAsync(const String& key, IRuntimeInfoGetIntAsyncResultListener* listener) +{ + return _RuntimeInfoImpl::GetValueAsync(key, listener); +} + +result +RuntimeInfo::GetValueAsync(const String& key, IRuntimeInfoGetLonglongAsyncResultListener* listener) +{ + return _RuntimeInfoImpl::GetValueAsync(key, listener); +} + +} } // Tizen::System diff --git a/src/system/FSysSettingInfo.cpp b/src/system/FSysSettingInfo.cpp new file mode 100644 index 0000000..c1598a8 --- /dev/null +++ b/src/system/FSysSettingInfo.cpp @@ -0,0 +1,210 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysSettingInfo.cpp + * @brief This is the implementation file for SettingInfo class. + */ + +#include +#include + +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Security; + +namespace Tizen { namespace System +{ + +SettingInfo::SettingInfo(void) + :__pSettingInfoImpl(null) +{ +} + +SettingInfo::~SettingInfo(void) +{ +} + +result +SettingInfo::SetSettingEventListener(ISettingEventListener* pListener) +{ + return _SettingInfoImpl::SetSettingEventListener(pListener); +} + +result +SettingInfo::AddSettingEventListener(ISettingEventListener& listener) +{ + return _SettingInfoImpl::AddSettingEventListener(listener); +} + +result +SettingInfo::RemoveSettingEventListener(ISettingEventListener& listener) +{ + return _SettingInfoImpl::RemoveSettingEventListener(listener); +} + +result +SettingInfo::GetValue(const String& key, String& value) +{ + return _SettingInfoImpl::GetValue(key, value); +} + +result +SettingInfo::GetValue(const String& key, int& value) +{ + return _SettingInfoImpl::GetValue(key, value); +} + +result +SettingInfo::GetValue(const String& key, long long& value) +{ + return _SettingInfoImpl::GetValue(key, value); +} + +result +SettingInfo::GetValue(const String& key, double& value) +{ + return _SettingInfoImpl::GetValue(key, value); +} + +result +SettingInfo::GetValue(const String& key, bool& value) +{ + return _SettingInfoImpl::GetValue(key, value); +} + +result +SettingInfo::GetValue(const String& key, UuId& value) +{ + return _SettingInfoImpl::GetValue(key, value); +} + +result +SettingInfo::SetWallpaper(const String& filePath) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SETTING); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _SettingInfoImpl::SetWallpaper(filePath); +} + +result +SettingInfo::SetRingtone(const String& filePath) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SETTING); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _SettingInfoImpl::SetRingtone(filePath); +} + +result +SettingInfo::SetVolume(const String& soundCategory, int level) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SETTING); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _SettingInfoImpl::SetVolume(soundCategory, level); +} + +result +SettingInfo::GetValueForPrivilegedKey(const String& key, bool& value) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SYSTEMSETTING_READ); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + return _SettingInfoImpl::GetValueForPrivilegedKey(key, value); +} + +bool +SettingInfo::HasKey(const String& key) +{ + return _SettingInfoImpl::HasKey(key); +} + +result +SettingInfo::SetValue(const String& key, bool value) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SETTING); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _SettingInfoImpl::SetValue(key, value); +} + +result +SettingInfo::SetValue(const String& key, int value) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SETTING); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _SettingInfoImpl::SetValue(key, value); +} + +result +SettingInfo::SetValue(const String& key, String value) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SETTING); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + return _SettingInfoImpl::SetValue(key, value); +} + +result +SettingInfo::SetValueForPrivilegedKey(const String& key, bool value) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SYSTEMSETTING_WRITE); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + return _SettingInfoImpl::SetValueForPrivilegedKey(key, value); +} + +result +SettingInfo::SetValueForPrivilegedKey(const String& key, String value) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SYSTEMSETTING_WRITE); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + return _SettingInfoImpl::SetValueForPrivilegedKey(key, value); +} + +result +SettingInfo::ResetToFactoryDefault(void) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SYSTEMSETTING_WRITE); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + return _SettingInfoImpl::ResetToFactoryDefault(); +} + +result +SettingInfo::SetValueAsyncForPrivilegedKey(const String& key, bool value, ISettingInfoSetValueAsyncResultListener* listener) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_SYSTEMSETTING_WRITE); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + return _SettingInfoImpl::SetValueAsyncForPrivilegedKey(key, value, listener); +} + +} } // Tizen::System diff --git a/src/system/FSysSystemInfo.cpp b/src/system/FSysSystemInfo.cpp new file mode 100644 index 0000000..2fe4fb7 --- /dev/null +++ b/src/system/FSysSystemInfo.cpp @@ -0,0 +1,175 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysSystemInfo.cpp + * @brief This is the implementation file for SystemInfo class. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace std; + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; +using namespace Tizen::Security; + +namespace Tizen { namespace System +{ + +SystemInfo::SystemInfo(void) + :__pSystemInfoImpl(null) +{ +} + +SystemInfo::~SystemInfo(void) +{ +} + +result +SystemInfo::GetValue(const Tizen::Base::String& key, bool& value) +{ + SysTryReturn(NID_SYS, key.GetLength() > 0, E_INVALID_ARG, E_INVALID_ARG, ("Key length should be greater than 0.")); + + return _SystemInfoImpl::GetSysInfo(key, value); +} + +result +SystemInfo::GetValue(const String& key, String& value) +{ + SysTryReturn(NID_SYS, key.GetLength() > 0, E_INVALID_ARG, E_INVALID_ARG, ("Key length should be greater than 0.")); + + return _SystemInfoImpl::GetSysInfo(key, value); +} + +result +SystemInfo::GetValue(const String& key, int& value) +{ + SysTryReturn(NID_SYS, key.GetLength() > 0, E_INVALID_ARG, E_INVALID_ARG, ("Key length should be greater than 0.")); + + return _SystemInfoImpl::GetSysInfo(key, value); +} + +result +SystemInfo::GetValue(const String& key, double& value) +{ + SysTryReturn(NID_SYS, key.GetLength() > 0, E_INVALID_ARG, E_INVALID_ARG, ("Key length should be greater than 0.")); + + return _SystemInfoImpl::GetSysInfo(key, value); +} + +result +SystemInfo::GetValue(const String& key, UuId& value) +{ + SysTryReturn(NID_SYS, key.GetLength() > 0, E_INVALID_ARG, E_INVALID_ARG, ("Key length should be greater than 0.")); + + return _SystemInfoImpl::GetSysInfo(key, value); +} + +IList* +SystemInfo::GetValuesN(const String& key, SystemInfoValueType type) +{ + result r = E_SUCCESS; + IList* pValues = null; + SysTryCatch(NID_SYS, key.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, ("Key length should be greater than 0.")); + + pValues = _SystemInfoImpl::GetSysInfoValuesN(key, type); + if(pValues == null) + { + r = E_OBJ_NOT_FOUND; + } +CATCH: + SetLastResult(r); + return pValues; +} + +result +SystemInfo::GetPlatformVersion(String& platformVersion) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_PLATFORMINFO); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + return _SystemInfoImpl::GetPlatformVersion(platformVersion); +} + +result +SystemInfo::GetNativeApiVersion(String& nativeApiVersion) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_PLATFORMINFO); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + return _SystemInfoImpl::GetNativeApiVersion(nativeApiVersion); +} + +result +SystemInfo::GetWebApiVersion(String& webApiVersion) +{ + result r = _AccessController::CheckUserPrivilege(_PRV_PLATFORMINFO); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + return _SystemInfoImpl::GetWebApiVersion(webApiVersion); +} + +result +SystemInfo::GetImei(String& imei) +{ + result r = E_SUCCESS; + + ArrayList requestMessage; + ArrayList responseMessage; + + unique_ptr<_IpcClient> pIpcClient (new (std::nothrow) _IpcClient()); + SysTryReturn(NID_SYS, pIpcClient != null, E_OUT_OF_MEMORY, r, "It is failed to create IPC instance."); + + r = pIpcClient->Construct(_COMMUNICATION_DISPATCHER_IPC_ID); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "It is failed to create IpcClient. [%s]", GetErrorMessage(r)); + + requestMessage.Construct(); + responseMessage.Construct(); + + String serviceId = _SYSTEM_SERVICE_ID; + String commandId = _SYSTEM_COMMAND_GET_IMEI; + + requestMessage.Add(serviceId); + requestMessage.Add(commandId); + + unique_ptr pMsg(new (std::nothrow) IoService_Request(requestMessage, &responseMessage)); + SysTryReturnResult(NID_SYS, pMsg != null, E_OUT_OF_MEMORY, "It is failed to create Ipc message"); + + r = pIpcClient->SendRequest(pMsg.get()); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "It is failed to send ipc message. [%s]", GetErrorMessage(r)); + + unique_ptr pResult((String*)responseMessage.GetAt(_SYSTEM_RESPONSE_DATA)); + unique_ptr pImei((String*)responseMessage.GetAt(_SYSTEM_RESPONSE_DATA+1)); + + SysTryReturnResult(NID_SYS, pResult != null, E_SYSTEM, "It is failed to receive result on IPC response message."); + SysTryReturnResult(NID_SYS, pImei != null, E_SYSTEM, "It is failed to receive IMEI value on IPC response message."); + + SysTryReturnResult(NID_SYS, *pResult != _SYSTEM_RESULT_PRIVILEGED, E_PRIVILEGE_DENIED, "It is failed to get privilege."); + SysTryReturnResult(NID_SYS, *pResult == _SYSTEM_RESULT_OK, E_SYSTEM, "It is failed to get IMEI value."); + + imei = *pImei; + return r; +} + +}} // Tizen::System diff --git a/src/system/FSysSystemTime.cpp b/src/system/FSysSystemTime.cpp new file mode 100644 index 0000000..67e9f5f --- /dev/null +++ b/src/system/FSysSystemTime.cpp @@ -0,0 +1,77 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysSystemTime.cpp + * @brief This is the implementation file for SystemTime class. + */ + +#include +#include +#include + +#include +#include + +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Locales; +namespace Tizen { namespace System +{ + +SystemTime::SystemTime(void) + :__pSystemTimeImpl(null) +{ +} + +SystemTime::~SystemTime(void) +{ +} + +result +SystemTime::GetUptime(TimeSpan& uptime) +{ + return _SystemTimeImpl::GetUptime(uptime); +} + +result +SystemTime::GetCurrentTime(TimeMode timeMode, DateTime& currentTime) +{ + return _SystemTimeImpl::GetCurrentTime(timeMode, currentTime); +} + +result +SystemTime::GetCurrentTime(DateTime& currentTime) +{ + return _SystemTimeImpl::GetCurrentTime(currentTime); +} + +result +SystemTime::GetTicks(long long& ticks) +{ + return _SystemTimeImpl::GetTicks(ticks); +} + +result +SystemTime::SetCurrentTime(const DateTime& currentTime) +{ + return _SystemTimeImpl::SetCurrentTime(currentTime); +} + +} } // Tizen::System diff --git a/src/system/FSysVibrator.cpp b/src/system/FSysVibrator.cpp new file mode 100644 index 0000000..9134864 --- /dev/null +++ b/src/system/FSysVibrator.cpp @@ -0,0 +1,118 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysVibrator.cpp + * @brief This is the implementation file for Vibrator class. + */ + + +#include + +#include + +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Security; + +namespace Tizen { namespace System +{ + +Vibrator::Vibrator(void) + : __pVibratorImpl(null) +{ +} + +Vibrator::~Vibrator(void) +{ + if (__pVibratorImpl) + { + delete __pVibratorImpl; + __pVibratorImpl = null; + } +} + +result +Vibrator::Construct(void) +{ + result r = E_SUCCESS; + + SysAssertf(__pVibratorImpl == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class."); + + __pVibratorImpl = new (std::nothrow) _VibratorImpl(); + SysTryReturn(NID_SYS, __pVibratorImpl != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient."); + + r = __pVibratorImpl->Construct(); + SysTryReturn(NID_SYS, r == E_SUCCESS, r, r, "[%s] Error is occured", GetErrorMessage(r)); + + return r; +} + +result +Vibrator::Start(long onPeriod, long offPeriod, int count, int level) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_VIBRATOR); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + SysAssertf(__pVibratorImpl != null, "Not yet constructed. Construct() should be called before use."); + SysTryReturn(NID_SYS, (onPeriod > 0) && (offPeriod >= 0), E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Period is out of range."); + SysTryReturn(NID_SYS, count > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Count is out of range."); + SysTryReturn(NID_SYS, (level >= 0) && (level <= 100), E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Level is out of range."); + + r = __pVibratorImpl->Start(onPeriod, offPeriod, count, level); + SysTryReturn(NID_SYS, r == E_SUCCESS, r, r, "[%s] Error is occured", GetErrorMessage(r)); + + return r; +} + +result +Vibrator::Start(long milliseconds, int level) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_VIBRATOR); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + SysAssertf(__pVibratorImpl != null, "Not yet constructed. Construct() should be called before use."); + SysTryReturn(NID_SYS, milliseconds > 0, E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Time is out of range."); + SysTryReturn(NID_SYS, (level >= 0) && (level <= 100), E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] Level is out of range."); + + r = __pVibratorImpl->Start(milliseconds, 0, 1, level); + SysTryReturn(NID_SYS, r == E_SUCCESS, r, r, "[%s] Error is occured", GetErrorMessage(r)); + + return r; +} + +result +Vibrator::Stop(void) +{ + result r = E_SUCCESS; + r = _AccessController::CheckUserPrivilege(_PRV_VIBRATOR); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_PRIVILEGE_DENIED, E_PRIVILEGE_DENIED, ("[E_PRIVILEGE_DENIED] The application does not have the privilege to call this method.")); + + SysAssertf(__pVibratorImpl != null, "Not yet constructed. Construct() should be called before use."); + + r = __pVibratorImpl->Stop(); + SysTryReturn(NID_SYS, r == E_SUCCESS, r, r, "[%s] Error is occured", GetErrorMessage(r)); + + return r; +} + +} } // Tizen::System diff --git a/src/system/FSys_AlarmImpl.cpp b/src/system/FSys_AlarmImpl.cpp new file mode 100644 index 0000000..9f77bee --- /dev/null +++ b/src/system/FSys_AlarmImpl.cpp @@ -0,0 +1,485 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_AlarmImpl.cpp + * @brief This is the implementation file for _AlarmImpl class. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include "FSys_AlarmImpl.h" +#include "FSys_SystemTimeImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +namespace Tizen { namespace System +{ + +static const wchar_t* _COMMUNICATION_DISPATCHER_IPC_ID = L"osp.app.ipcserver.communicationdispatcher"; +static const wchar_t* _ALARM_SERVICE_ID = L"osp.alarm.service"; +static const wchar_t* _ALARM_SET_SINGLEALARM = L"osp.alarm.set.singlealarm"; +static const wchar_t* _ALARM_SET_REPEATEDALARM = L"osp.alarm.set.repeatedalarm"; +static const wchar_t* _ALARM_CANCEL = L"osp.alarm.cancel"; +static const wchar_t* _ALARM_EXPIRY_EVENT = L"osp.alarm.expired.callback"; +static const wchar_t* _ALARM_RESULT_OK = L"osp.alarm.result.ok"; + +const int _ALARM_SERVICE_IPC_MESSAGE_SERVICE_ID = 0; +const int _ALARM_SERVICE_IPC_MESSAGE_COMMAND_ID = 1; +const int _ALARM_SERVICE_RESPONSE_DATA = 2; +const int _ALARM_SERVICE_ALARM_ID = 3; + + +class _AlarmEventArg : public IEventArg +{ +public: + _AlarmEventArg() + : pAlarm(null) + { + } + Alarm* pAlarm; +}; + +class _AlarmEvent : public Event +{ +protected: + virtual void FireImpl(IEventListener& listener, const IEventArg& arg) + { + IAlarmEventListener* pListener = dynamic_cast (&listener); + const _AlarmEventArg* pArg = dynamic_cast(&arg); + + if(pListener == null || pArg == null) + { + SysLogException(NID_SYS, E_SYSTEM, "listener or arg is null."); + return; + } + + if(pArg->pAlarm == null) + { + SysLogException(NID_SYS, E_SYSTEM, "Alarm data is invalid."); + return; + } + + pListener->OnAlarmExpired(*(pArg->pAlarm)); + } +}; + +_AlarmImpl::_AlarmImpl(Alarm* pAlarm) + : __pIpcClient(null) + , __period(0) + , __pAlarmId(null) + , __pEndTime(null) + , __pEvent(null) + , __pAlarm(pAlarm) +{ + +} + +result +_AlarmImpl::Construct(void) +{ + result r = E_SUCCESS; + + if(__pIpcClient == null) + { + __pIpcClient = new (std::nothrow) _IpcClient(); + SysTryReturnResult(NID_SYS, __pIpcClient != null, E_OUT_OF_MEMORY, "The memory is insufficient."); + + r = __pIpcClient->Construct(_COMMUNICATION_DISPATCHER_IPC_ID, this); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "[%s] Error is occured", GetErrorMessage(r)); + } + + return r; +} + +_AlarmImpl::~_AlarmImpl(void) +{ + result r = E_SUCCESS; + + r = Cancel(); + SysLog(NID_SYS, "Alarm cancel %s", IsFailed(r) ? "failed" : "succeed"); + + if(__pIpcClient != null) + { + delete __pIpcClient; + } + + if(__pAlarmId != null) + { + delete __pAlarmId; + } +} + +_IpcClient* +_AlarmImpl::GetIpcClient(void) +{ + return __pIpcClient; +} + +result +_AlarmImpl::Set(const Tizen::Base::DateTime& startTime, int period, const Tizen::Base::DateTime* pEndTime) +{ + result r = E_SUCCESS; + ArrayList requestMessage; + ArrayList responseMessage; + std::unique_ptr pRequest(null); + + std::unique_ptr pResult(null); + std::unique_ptr pAlarmId(null); + + int alarmVal = -1; + + String startTimeStr; + String periodStr; + + String serviceId = _ALARM_SERVICE_ID; + String commandId = _ALARM_SET_SINGLEALARM; + DateTime currentTime; + + //Status check + SysTryReturnResult(NID_SYS, __pIpcClient != null, E_INVALID_STATE, "This instance has not been constructed as yet."); + + //Argument check + r = SystemTime::GetCurrentTime(WALL_TIME, currentTime); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get current time"); + + SysTryReturnResult(NID_SYS, DateTime::Compare(currentTime, startTime) < 0, E_INVALID_ARG, "Designated start time has to be greater then current time"); + + SysTryReturnResult(NID_SYS, period > -1, E_INVALID_ARG, "Period has to greater then -1"); + + if(pEndTime != null) + { + SysTryReturnResult(NID_SYS, DateTime::Compare(startTime, *pEndTime) < 0, E_INVALID_ARG, "Designated end time is less then start time"); + } + + //Exist alarm check + if(__pAlarmId != null) + { + SysLog(NID_SYS, "Alarm is already registered. Request to unregister to osp-app-service"); + r = Cancel(); + + delete __pAlarmId; + __pAlarmId = null; + + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to unregister exist alarm %s", GetErrorMessage(r)); + SysLog(NID_SYS, "Exist alarm is unregistered successfully"); + } + + //Alarm data construction + __startTime = startTime; + __period.value = period; + + if(period > 0) //If period is 0, alarm is operated as Single alarm. + { + commandId = _ALARM_SET_REPEATEDALARM; + } + + if(pEndTime != null) + { + SysTryCatch(NID_SYS, startTime.CompareTo(*pEndTime) <= 0, r = E_INVALID_ARG, r, "Start time should be greater then the end time"); + __pEndTime = new (std::nothrow) DateTime(*pEndTime); + SysTryCatch(NID_SYS, __pEndTime != null, r = E_SYSTEM, r, "__pEndTime should not be null"); + } + + //IPC data construction + r = requestMessage.Construct(); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to create request instance"); + r = responseMessage.Construct(); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to create response instance"); + + r = requestMessage.Add(serviceId); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to add service id"); + r = requestMessage.Add(commandId); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to add command id"); + startTimeStr = __startTime.ToString(); + r = requestMessage.Add(startTimeStr); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to add start time value"); + periodStr = __period.ToString(); + r = requestMessage.Add(periodStr); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to add period value"); + + if(__pEndTime) + { + SysLog(NID_SYS, "End time is valid and adding to message"); + std::unique_ptr pEndTime(new (std::nothrow) String(__pEndTime->ToString())); + SysTryCatch(NID_SYS, pEndTime != null, r = E_SYSTEM, r, "pEndTime should not be null"); + + r = requestMessage.Add(*(pEndTime.release())); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to add end time value"); + } + + pRequest.reset(new (std::nothrow) IoService_Request(requestMessage, &responseMessage)); + SysTryCatch(NID_SYS, pRequest != null, r = E_SYSTEM, r, "Failed to create Ipc message"); + + //IPC data delivery + r = __pIpcClient->SendRequest(pRequest.get()); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to send ipc message"); + SysLog(NID_SYS, "Alarm reqeust is deliverted to osp-app-service successfully"); + + //IPC data response check + pResult.reset((String*)responseMessage.GetAt(_ALARM_SERVICE_RESPONSE_DATA)); + SysTryCatch(NID_SYS, pResult != null, r = E_SYSTEM, r, "Failed to receive Ipc response"); + SysTryCatch(NID_SYS, *pResult == _ALARM_RESULT_OK, r = E_SYSTEM, r, "Failed to create alarm"); + + pAlarmId.reset((String*)responseMessage.GetAt(_ALARM_SERVICE_ALARM_ID)); + SysTryCatch(NID_SYS, pAlarmId != null, r = E_SYSTEM, r, "Failed to get Alarm Id"); + + Integer::Parse(*(pAlarmId.get()), alarmVal); + + SysLog(NID_SYS, "Reserved alarm id is %d from osp-app-service.", alarmVal); + + __pAlarmId = new (std::nothrow) Integer(alarmVal); + SysTryCatch(NID_SYS, __pAlarmId != null, r = E_SYSTEM, r, "Fail to copy alarm id"); + SysTryCatch(NID_SYS, __pAlarmId->ToInt() >= 0, r = E_SYSTEM, r, "Alarm Id is invalid"); + +CATCH: + if(r != E_SUCCESS) + { + if(__pEndTime != null) + { + delete __pEndTime; + __pEndTime = null; + } + + if(__pAlarmId != null) + { + delete __pAlarmId; + __pAlarmId = null; + } + } + + return r; +} + +result +_AlarmImpl::Cancel(void) +{ + result r = E_SUCCESS; + + ArrayList requestMessage; + ArrayList responseMessage; + std::unique_ptrpRequest(null); + std::unique_ptr pResult(null); + std::unique_ptr pAlarmIdStr(null); + String serviceId = _ALARM_SERVICE_ID; + String commandId = _ALARM_CANCEL; + + + //Status check + SysTryReturnResult(NID_SYS, __pIpcClient != null, E_INVALID_STATE, "This instance has not been constructed as yet."); + SysTryReturnResult(NID_SYS, __pAlarmId != null, r = E_SUCCESS, "Alarm is not created yet."); + SysTryCatch(NID_SYS, (__pAlarmId->ToInt()) != -1, r = E_SYSTEM, r, "Alarm is not created yet."); + + //IPC data construction + r = requestMessage.Construct(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to create request instance"); + r = responseMessage.Construct(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to create response instance"); + + r = requestMessage.Add(serviceId); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add service id"); + r = requestMessage.Add(commandId); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add command id"); + pAlarmIdStr.reset(new (std::nothrow) String(__pAlarmId->ToString())); + SysTryCatch(NID_SYS, pAlarmIdStr != null, r = E_SYSTEM, r, "pAlarmIdStr should not be null"); + + r = requestMessage.Add(*(pAlarmIdStr.release())); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add alarm id value"); + + //IPC data delivery + pRequest.reset(new (std::nothrow) IoService_Request(requestMessage, &responseMessage)); + SysTryCatch(NID_SYS, pRequest != null, r = E_SYSTEM, r, "Failed to create Ipc message"); + + r = __pIpcClient->SendRequest(pRequest.get()); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "Failed to send ipc message"); + SysLog(NID_SYS, "Alarm cancel reqeust is deliverted to osp-app-service successfully"); + + //IPC data response check + pResult.reset((String*)responseMessage.GetAt(_ALARM_SERVICE_RESPONSE_DATA)); + SysTryCatch(NID_SYS, pResult != null, r = E_SYSTEM, r, "Failed to receive Ipc response"); + SysTryCatch(NID_SYS, *pResult == _ALARM_RESULT_OK, r = E_SUCCESS, r, "Failed to cancel alarm"); + +CATCH: + if(__pAlarmId != null) + { + delete __pAlarmId; + __pAlarmId = null; + } + return r; +} + +void +_AlarmImpl::OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message) +{ + IPC_BEGIN_MESSAGE_MAP(_AlarmImpl, message) + IPC_MESSAGE_HANDLER_EX(IoService_Data, &client, OnDataReceived) + IPC_END_MESSAGE_MAP_EX() +} + +void +_AlarmImpl::OnDataReceived(const ArrayList& data) +{ + result r = E_SUCCESS; + StringComparer stringComparer; + String alarmIdStr; + + int cmp = 0; + std::unique_ptr pServiceId((String*) data.GetAt(_ALARM_SERVICE_IPC_MESSAGE_SERVICE_ID)); + std::unique_ptr pCommandId((String*) data.GetAt(_ALARM_SERVICE_IPC_MESSAGE_COMMAND_ID)); + std::unique_ptr pData((String*) data.GetAt(_ALARM_SERVICE_RESPONSE_DATA)); + + String serviceId = _ALARM_SERVICE_ID; + String commandId = _ALARM_EXPIRY_EVENT; + + SysTryCatch(NID_SYS, pServiceId != null && pCommandId != null && pData != null, r = E_SYSTEM, + E_SYSTEM, "There is no device data."); + + stringComparer.Compare(*(pServiceId.release()), serviceId, cmp); + if(cmp == 0) + { + stringComparer.Compare(*(pCommandId.release()), commandId, cmp); + if(cmp == 0) + { + if(__pAlarmId != null) + { + alarmIdStr = __pAlarmId->ToString(); + stringComparer.Compare(*(pData.release()), alarmIdStr, cmp); + if(cmp == 0) + { + OnAlarmExpired(__pAlarmId->ToInt()); + } + else + { + SysLog(NID_SYS, "Wrong alarm is delivered, Reserved alarm id of current instance is %d", __pAlarmId->value); + } + } + else + { + SysLog(NID_SYS, "Current instance does not reserve alarm."); + } + } + else + { + SysLog(NID_SYS, "This is not alarm command."); + } + } + else + { + SysLog(NID_SYS, "This is not alarm service."); + } +CATCH: + SetLastResult(r); +} + +const DateTime +_AlarmImpl::GetStartTime(void) const +{ + ClearLastResult(); + return __startTime; +} + +int +_AlarmImpl::GetPeriod(void) const +{ + ClearLastResult(); + return __period.ToInt(); +} + +const DateTime* +_AlarmImpl::GetEndTime(void) const +{ + ClearLastResult(); + return __pEndTime; +} + +result +_AlarmImpl::SetAlarmEventListener(IAlarmEventListener* pListener) +{ + if(pListener == null) + { + SysLog(NID_SYS, "Listener null set doesn't mean disalarm"); + if(__pEvent != null) + { + delete __pEvent; + __pEvent = null; + } + } + else + { + if(__pEvent == null) + { + _AlarmEvent* pAlarmEvent = new (std::nothrow) _AlarmEvent(); + SysTryReturnResult(NID_SYS, pAlarmEvent != null, E_OUT_OF_MEMORY, "It is failed to create Event instance"); + __pEvent = pAlarmEvent; + } + __pEvent->AddListener(*pListener); + } + return E_SUCCESS; +} + +void +_AlarmImpl::OnAlarmExpired(int alarmId) +{ + if(__pEvent != null) + { + _AlarmEventArg* pAlarmEventArg= new (std::nothrow) _AlarmEventArg(); + if(pAlarmEventArg == null) + { + SysLogException(NID_SYS, E_OUT_OF_MEMORY, "It is failed to create instance of _AlarmEventArg class."); + return; + } + pAlarmEventArg->pAlarm = this->__pAlarm; + if(pAlarmEventArg != null) + { + __pEvent->Fire(*pAlarmEventArg); + } + SysLog(NID_SYS, "Alarm Expired for alarm id: %d and listener called.", alarmId); + } + else + { + SysLog(NID_SYS, "Reserved alarm is expired. However, Listener point is unavailable."); + } +} + + +_AlarmImpl* +_AlarmImpl::GetInstance(Alarm* pAlarm) +{ + return (pAlarm) ? pAlarm->__pAlarmImpl : null; +} + +const _AlarmImpl* +_AlarmImpl::GetInstance(const Alarm* pAlarm) +{ + return (pAlarm) ? pAlarm->__pAlarmImpl : null; +} + +} } // Tizen::System diff --git a/src/system/FSys_BatteryImpl.cpp b/src/system/FSys_BatteryImpl.cpp new file mode 100644 index 0000000..da4f964 --- /dev/null +++ b/src/system/FSys_BatteryImpl.cpp @@ -0,0 +1,113 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_BatteryImpl.cpp + * @brief This is the implementation file for _BatteryImpl class. + */ + +#include +#include + +#include + +#include +#include +#include +#include + +#include "FSys_SystemInfoImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace System +{ + +_BatteryImpl::_BatteryImpl(void) +{ +} + +_BatteryImpl::~_BatteryImpl(void) +{ +} + +result +_BatteryImpl::IsCharging(bool& charging) +{ + bool chargeState = false; + int ret = 0; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_BATTERY_IS_CHARGING, &chargeState); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] runtime_info_get_value_bool returns %d.", ret); + charging = chargeState; + return E_SUCCESS; +} + +result +_BatteryImpl::GetCurrentLevelInPercentage(int& level) +{ + int ret = 0; + int batteryLevel = 0; + + ret = device_battery_get_percent(&batteryLevel); + SysTryReturnResult(NID_SYS, ret == DEVICE_ERROR_NONE, E_SYSTEM, "Failed to get the device battery percentage"); + + level = batteryLevel; + + return E_SUCCESS; +} + +result +_BatteryImpl::GetCurrentLevel(BatteryLevel& level) +{ + int ret = 0; + int batteryLevel = 0; + device_battery_warn_e batteryStatus; + + result r = device_battery_get_percent(&batteryLevel); + SysTryReturnResult(NID_SYS, !IsFailed(r), r, "Failed to get the device battery percentage"); + + if (batteryLevel == _BATTERY_LEVEL_FULL) + { + level = BATTERY_FULL; + return E_SUCCESS; + } + + ret = device_battery_get_warning_status(&batteryStatus); + + switch (batteryStatus) + { + case DEVICE_BATTERY_WARN_NORMAL: + level = BATTERY_HIGH; + break; + case DEVICE_BATTERY_WARN_LOW: + level = BATTERY_LOW; + break; + case DEVICE_BATTERY_WARN_CRITICAL: + level = BATTERY_CRITICAL; + break; + case DEVICE_BATTERY_WARN_EMPTY: + level = BATTERY_EMPTY; + break; + default: + SysLogException(NID_SYS, E_SYSTEM, "There is a system error occured."); + return E_SYSTEM; + } + + return E_SUCCESS; +} + +} } // Tizen::System diff --git a/src/system/FSys_BatteryImpl.h b/src/system/FSys_BatteryImpl.h new file mode 100644 index 0000000..9bc5ee1 --- /dev/null +++ b/src/system/FSys_BatteryImpl.h @@ -0,0 +1,50 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_BatteryImpl.h + * @brief This is the header file for _BatteryImpl class. + */ + +#ifndef _FSYS_INTERNAL_BATTERY_IMPL_H_ +#define _FSYS_INTERNAL_BATTERY_IMPL_H_ + +#include + +#include + +namespace Tizen { namespace System +{ + +class _BatteryImpl + : public Tizen::Base::Object +{ + +public: + static result GetCurrentLevelInPercentage(int& level); + static result GetCurrentLevel(BatteryLevel& level); + static result IsCharging(bool& charging); + +private: + _BatteryImpl(void); + virtual ~_BatteryImpl(void); + +}; //_BatteryImpl + +} } // Tizen::Sys + +#endif //_FSYS_INTERNAL_BATTERY_IMPL_H_ diff --git a/src/system/FSys_DeviceEventListenerContainer.cpp b/src/system/FSys_DeviceEventListenerContainer.cpp new file mode 100644 index 0000000..2a47dec --- /dev/null +++ b/src/system/FSys_DeviceEventListenerContainer.cpp @@ -0,0 +1,64 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_DeviceEventListenerContainer.cpp + * @brief This is the implementation file for _DeviceEventListenerContainer class. + */ + +#include + +using namespace Tizen::Base::Runtime; + +namespace Tizen { namespace System +{ + +_DeviceEventListenerContainer::_DeviceEventListenerContainer(void) + : __bluetoothHeadset(false) + , __charger(false) + , __usbClient(false) + , __tvOut(false) + , __wiredHeadset(false) + , __wiredHeadphone(false) + , __storageCard(false) + , __keyboard(false) + , __hdmi(false) + , __pEvent(null) + , __pListener(null) +{ +} + +_DeviceEventListenerContainer::~_DeviceEventListenerContainer(void) +{ +} + +bool +_DeviceEventListenerContainer::IsInvalid() +{ + if(__bluetoothHeadset == false && __charger == false + && __usbClient == false && __tvOut == false + && __wiredHeadset == false && __wiredHeadphone == false + && __storageCard == false && __keyboard == false && __hdmi == false) + { + return true; + } + else + { + return false; + } +} +} } diff --git a/src/system/FSys_DeviceEventListenerContainer.h b/src/system/FSys_DeviceEventListenerContainer.h new file mode 100644 index 0000000..eb3c511 --- /dev/null +++ b/src/system/FSys_DeviceEventListenerContainer.h @@ -0,0 +1,56 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_DeviceEventListenerContainer.h + * @brief This is the header file for the _DeviceEventListenerContainer class. + */ + +#ifndef _FSYS_INTERNAL_DEVICE_EVENT_LISTENER_CONATINER_H_ +#define _FSYS_INTERNAL_DEVICE_EVENT_LISTENER_CONATINER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +class _DeviceEventListenerContainer +{ +public: + _DeviceEventListenerContainer(void); + virtual ~_DeviceEventListenerContainer(void); + + bool IsInvalid(void); +public: + //Interested device event list + bool __bluetoothHeadset; + bool __charger; + bool __usbClient; + bool __tvOut; + bool __wiredHeadset; + bool __wiredHeadphone; + bool __storageCard; + bool __keyboard; + bool __hdmi; + + Tizen::Base::Runtime::Event* __pEvent; + IDeviceEventListener* __pListener; +}; + +} } +#endif // _FSYS_INTERNAL_DEVICE_EVENT_LISTENER_CONATINER_H_ diff --git a/src/system/FSys_DeviceId.cpp b/src/system/FSys_DeviceId.cpp new file mode 100644 index 0000000..753734c --- /dev/null +++ b/src/system/FSys_DeviceId.cpp @@ -0,0 +1,263 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_DeviceId.cpp + * @brief This is the implementation file for _DeviceId class. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include "FSys_DeviceId.h" + +using namespace Tizen::Base; +using namespace Tizen::Text; + + +namespace Tizen { namespace System +{ + +#define POLYNOMIAL 0x04c11db7L + +const int _CONVERT_SIZE = 10; +const int _CRC_TABLE_SIZE = 256; +const int _CRYPT_KEY_SIZE = 8; +const int _CRYPT_MAX_SIZE = 100; +const int _DUID_LENGTH = 13; // crc64() strlen * 8 / 5 +const int _IMEI_SIZE = 18; + +static const char BASE32_CHAR_SET[] = "abcdefghijklmnopqrstuvwxyz0123456789"; + +String _DeviceId::__deviceId = ""; + +unsigned long long int* +GenCrc64Table(int size) +{ + int i, j; + unsigned long long int *pCrcTable = null; + unsigned long long int crcAccum = 0; + + pCrcTable = (unsigned long long int*)malloc(sizeof(unsigned long long int) * size); + if(pCrcTable == null) + { + return null; + } + + memset(pCrcTable, 0, sizeof(unsigned long long int) * size); + + for(i=0; i(input.GetPointer()); + unsigned long long int* pCrcTable = null; + int inputSize = input.GetRemaining(); + + value = 0ULL; + + pCrcTable = GenCrc64Table(_CRC_TABLE_SIZE); + + while (inputSize--) + { + value = pCrcTable[(value ^ *pPu8++) & 0xff] ^ (value >> 8); + } + free(pCrcTable); + + return r; +} + +result +_DeviceId::Base32Encode(Tizen::Base::ByteBuffer& input, Tizen::Base::ByteBuffer& output) +{ + result r = E_SUCCESS; + + byte* pEncodingPointer = null; + byte* pSrcPointer = null; + int i = 0; + + const byte* pInputData = input.GetPointer(); + int inputSize = input.GetRemaining(); + + byte* pBuffer = null; + int bufferLength = 0; + + bufferLength = 8 * (inputSize / 5 + 1) + 1; + pBuffer = (byte*) calloc(1, bufferLength); + SysTryReturn(NID_SYS, pBuffer != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory"); + + pEncodingPointer = pBuffer; + pSrcPointer = const_cast(pInputData); + + for (i = 0; i < (byte) inputSize; i += 5) + { + pEncodingPointer[0] = BASE32_CHAR_SET[(pSrcPointer[0] >> 3)]; + pEncodingPointer[1] = BASE32_CHAR_SET[((pSrcPointer[0] & 0x07) << 2) | ((pSrcPointer[1] & 0xc0) >> 6)]; + pEncodingPointer[2] = (i + 1 < (byte) inputSize) ? BASE32_CHAR_SET[((pSrcPointer[1] & 0x3e) >> 1)] : '\0'; + pEncodingPointer[3] = (i + 1 < (byte) inputSize) ? BASE32_CHAR_SET[((pSrcPointer[1] & 0x01) << 4) | ((pSrcPointer[2] & 0xf0) >> 4)] : '\0'; + pEncodingPointer[4] = (i + 2 < (byte) inputSize) ? BASE32_CHAR_SET[((pSrcPointer[2] & 0x0f) << 1) | ((pSrcPointer[3] & 0x80) >> 7)] : '\0'; + pEncodingPointer[5] = (i + 3 < (byte) inputSize) ? BASE32_CHAR_SET[((pSrcPointer[3] & 0x3e) >> 2)] : '\0'; + pEncodingPointer[6] = (i + 3 < (byte) inputSize) ? BASE32_CHAR_SET[((pSrcPointer[3] & 0x03) << 3) | ((pSrcPointer[4] & 0xe0) >> 5)] : '\0'; + pEncodingPointer[7] = (i + 4 < (byte) inputSize) ? BASE32_CHAR_SET[((pSrcPointer[4] & 0x1f))] : '\0'; + + pSrcPointer += 5; + pEncodingPointer += 8; + } + + r = output.Construct(bufferLength); + SysTryCatch(NID_SYS, !IsFailed(r), r = E_SYSTEM, r, "[%s] Failed to construct ByteBuffer."); + r = output.SetArray(pBuffer, 0, bufferLength); + SysTryCatch(NID_SYS, !IsFailed(r), r = E_SYSTEM, r, "[%s] Failed to set array to ByteBuffer."); + output.Flip(); + +CATCH: + if (pBuffer != null) + { + delete[] pBuffer; + } + + return r; +} + +}} // Tizen::System + diff --git a/src/system/FSys_DeviceId.h b/src/system/FSys_DeviceId.h new file mode 100644 index 0000000..777257f --- /dev/null +++ b/src/system/FSys_DeviceId.h @@ -0,0 +1,73 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_DeviceId.h + * @brief This is the header file for _DeviceId class. + */ + + +#ifndef _FSYS_INTERNAL_DEVICE_ID_H_ +#define _FSYS_INTERNAL_DEVICE_ID_H_ + + +#include + +namespace Tizen { namespace Base +{ +class String; +class ByteBuffer; +}} + +namespace Tizen { namespace System +{ + + +class _DeviceId +{ +public: + /** + * Gets device unique ID. + * + * @since 1.0 + * @return An error code + * @param[out] deviceId The device unique ID. + * @exception E_SUCCESS The method is successful. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * @exception E_SYSTEM A system error has occurred. + */ + static result GetId(Tizen::Base::String& deviceId); + +private: + /** + * This is the default constructor for this class. + */ + _DeviceId(void); + + /** + * This is the destructor for this class. + */ + ~_DeviceId(void); + + static result GenerateCrc64(Tizen::Base::ByteBuffer& input, unsigned long long int& value); + static result Base32Encode(Tizen::Base::ByteBuffer& input, Tizen::Base::ByteBuffer& output); + static Tizen::Base::String __deviceId; +}; //_DeviceId + +}} + +#endif // _FSYS_INTERNAL_DEVICE_ID_H_ diff --git a/src/system/FSys_DeviceManagerEventProvider.cpp b/src/system/FSys_DeviceManagerEventProvider.cpp new file mode 100644 index 0000000..340c655 --- /dev/null +++ b/src/system/FSys_DeviceManagerEventProvider.cpp @@ -0,0 +1,62 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_DeviceManagerEventProvider.cpp + * @brief This is the implementation file for _DeviceManagerEventProvider class. + */ + +#include +#include +#include + +using namespace Tizen::System; + +_DeviceManagerEventProvider* _DeviceManagerEventProvider::__pDeviceManagerEventProvider = null; + +_DeviceManagerEventProvider::_DeviceManagerEventProvider() + : __pListener(null) +{ +} + +_DeviceManagerEventProvider::~_DeviceManagerEventProvider() +{ +} + +void +_DeviceManagerEventProvider::InitDeviceManagerEventProvider() +{ + static _DeviceManagerEventProvider deviceManagerEventProvider; + __pDeviceManagerEventProvider = &deviceManagerEventProvider; +} + +_DeviceManagerEventProvider* +_DeviceManagerEventProvider::GetInstance() +{ + static pthread_once_t once_block = PTHREAD_ONCE_INIT; + if (__pDeviceManagerEventProvider == null) + { + pthread_once(&once_block, InitDeviceManagerEventProvider); + } + return __pDeviceManagerEventProvider; +} + +void +_DeviceManagerEventProvider::SetIDeviceManageEventProvider(_IDeviceManagerEventProvider* listener) +{ + __pListener = listener; +} diff --git a/src/system/FSys_DeviceManagerImpl.cpp b/src/system/FSys_DeviceManagerImpl.cpp new file mode 100644 index 0000000..a602917 --- /dev/null +++ b/src/system/FSys_DeviceManagerImpl.cpp @@ -0,0 +1,1468 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_DeviceManagerImpl.cpp + * @brief This is the implementation file for _DeviceManagerImpl class. + */ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "FSys_DeviceManagerImpl.h" + +#define VCONFKEY_APPSERVICE_MMC_STATUS "memory/appservice/mmc" + +using namespace Tizen::App; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Io; + +namespace Tizen { namespace System +{ + +static const wchar_t* _COMMUNICATION_DISPATCHER_IPC_ID = L"osp.app.ipcserver.communicationdispatcher"; +static const wchar_t* _DEVICE_MANAGER_SERVICE_ID = L"osp.devicemanager.service"; +static const wchar_t* _DEVICE_MANAGER_COMMAND_OPEN = L"osp.devicemanager.command.open"; +static const wchar_t* _DEVICE_MANAGER_COMMAND_CLOSE = L"osp.devicemanager.command.close"; +static const wchar_t* _DEVICE_MANAGER_COMMAND_STATUS = L"osp.devicemanager.command.status"; +static const wchar_t* _DEVICE_MANAGER_COMMAND_EVENT = L"osp.devicemanager.command.event"; +static const wchar_t* _DEVICE_MANAGER_BLUETOOTH = L"osp.devicemanager.bluetooth"; + +const int _OSP_APP_SERVICE_IPC_MESSAGE_HEAD_SERVICE_ID = 0; +const int _OSP_APP_SERVICE_IPC_MESSAGE_HEAD_COMMAND_ID = 1; +const int _OSP_APP_SERVICE_IPC_MESSAGE_HEAD_DEVICE_ID = 2; +const int _OSP_APP_SERVICE_IPC_MESSAGE_DATA = 3; + +const int _DEVICE_MANAGER_BLUETOOTH_HEADSET = 0x01; +const int _DEVICE_MANAGER_CHARGER = 0x02; +const int _DEVICE_MANAGER_USB_CLIENT = 0x04; +const int _DEVICE_MANAGER_TV_OUT = 0x08; +const int _DEVICE_MANAGER_WIRED_HEADSET = 0x10; +const int _DEVICE_MANAGER_WIRED_HEADPHONE = 0x20; +const int _DEVICE_MANAGER_STORAGECARD = 0x40; +const int _DEVICE_MANAGER_KEYBOARD = 0x80; + +static const wchar_t* _DEVICE_MANAGER_STATE_INSERTED = L"Inserted"; +static const wchar_t* _DEVICE_MANAGER_STATE_REMOVED = L"Removed"; +static const wchar_t* _DEVICE_MANAGER_STATE_MOUNTED = L"Mounted"; +static const wchar_t* _DEVICE_MANAGER_STATE_UNMOUNTED = L"Unmounted"; +static const wchar_t* _DEVICE_MANAGER_STATE_OPENED = L"Opened"; +static const wchar_t* _DEVICE_MANAGER_STATE_CLOSED = L"Closed"; + +static const wchar_t* _SYSTEM_INFO_INPUT_KEYBOARD = L"http://tizen.org/feature/input.keyboard"; +static const wchar_t* _SYSTEM_INFO_TVOUT_SUPPORTED = L"http://tizen.org/feature/screen.output.rca"; + +_DeviceManagerImpl* _DeviceManagerImpl::__pDeviceManagerImpl = null; + + +class _DeviceManagerEventArg : public IEventArg +{ +public: + _DeviceManagerEventArg() + { + } + DeviceType deviceType; + String state; +}; + +class _DeviceManagerEvent : public Event +{ +protected: + virtual void FireImpl(IEventListener& listener, const IEventArg& arg) + { + IDeviceEventListener* pListener = dynamic_cast (&listener); + const _DeviceManagerEventArg* pArg = dynamic_cast(&arg); + + if(pListener == null || pArg == null) + { + SysLogException(NID_SYS, E_SYSTEM, "listener or arg is null."); + return; + } + + pListener->OnDeviceStateChanged(pArg->deviceType, pArg->state); + } +}; + + +void +_DeviceManagerImpl::OnDeviceStateChanged(runtime_info_key_e key, void* pData) +{ + if (__pDeviceManagerImpl != null) + { + __pDeviceManagerImpl->SendEvent(key); + } +} + +void +_DeviceManagerImpl::InitDeviceManagerImpl(void) +{ + static _DeviceManagerImpl deviceManagerImpl; + __pDeviceManagerImpl = &deviceManagerImpl; +} +_DeviceManagerImpl* +_DeviceManagerImpl::GetInstance(void) +{ + static pthread_once_t once_block = PTHREAD_ONCE_INIT; + if(__pDeviceManagerImpl == null) + { + pthread_once(&once_block, InitDeviceManagerImpl); + } + return __pDeviceManagerImpl; +} + +_DeviceManagerImpl::_DeviceManagerImpl() + : __pIpcClient(null) + , __headSetType(DEVICE_TYPE_WIRED_HEADPHONE) + , __bluetoothReferenceCount(0) +{ + result r = E_SUCCESS; + int headsetState = 0; + int ret = 0; + + __pIpcClient = new (std::nothrow) _IpcClient(); + SysTryCatch(NID_SYS, __pIpcClient != null, , r, "Fail to create IPC client"); + + r = __pIpcClient->Construct(_COMMUNICATION_DISPATCHER_IPC_ID, this); + SysTryCatch(NID_SYS, r == E_SUCCESS, , r, "Propagated. [%s]", GetErrorMessage(r)); + + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_USB_CONNECTED, OnDeviceStateChanged, null); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to register USB event"); + + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_CHARGER_CONNECTED, OnDeviceStateChanged, null); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to register DEVICE_TYPE_CHARGER event"); + + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_TV_OUT_CONNECTED, OnDeviceStateChanged, null); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to register TV out event"); + + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, OnDeviceStateChanged, null); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to register audio jack event"); + + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_SLIDING_KEYBOARD_OPENED, OnDeviceStateChanged, null); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to register sliding keyboard event"); + + ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, &headsetState); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to get audio jack status"); + + if (headsetState == RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_3WIRE) + { + __headSetType = DEVICE_TYPE_WIRED_HEADPHONE; + } + else if (headsetState == RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_4WIRE) + { + __headSetType = DEVICE_TYPE_WIRED_HEADSET; + } + + if (!_AppInfo::IsOspCompat()) + { + ret = vconf_notify_key_changed(VCONFKEY_SYSMAN_MMC_STATUS, DeviceEventVConfCallBack, null); + } + else + { + ret = vconf_notify_key_changed(VCONFKEY_APPSERVICE_MMC_STATUS, MmcEventVconfCallback, null); + } + SysTryCatch(NID_SYS, ret == 0, r = E_SYSTEM, r, "Failed to register MMC event callback."); + + ret = vconf_notify_key_changed(VCONFKEY_SYSMAN_HDMI, DeviceEventVConfCallBack, null); + SysTryCatch(NID_SYS, ret == 0, r = E_SYSTEM, r, "Failed to register HDMI event"); + + __deviceEventList.Construct(); + +CATCH: + SetLastResult(r); +} + +_DeviceManagerImpl::~_DeviceManagerImpl() +{ + result r = E_SUCCESS; + int ret = 0; + + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_USB_CONNECTED); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to unregister USB event"); + + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_TV_OUT_CONNECTED); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to unregister TV out event"); + + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to unregister audio jack event"); + + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_SLIDING_KEYBOARD_OPENED); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to unregister sliding keyboard event"); + + if (!_AppInfo::IsOspCompat()) + { + ret = vconf_ignore_key_changed(VCONFKEY_SYSMAN_MMC_STATUS, DeviceEventVConfCallBack); + } + else + { + ret = vconf_ignore_key_changed(VCONFKEY_APPSERVICE_MMC_STATUS, MmcEventVconfCallback); + } + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to unregister MMC event"); + + ret = vconf_ignore_key_changed(VCONFKEY_SYSMAN_HDMI, DeviceEventVConfCallBack); + SysTryCatch(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, r = E_SYSTEM, r, "Failed to unregister HDMI event"); + +CATCH: + delete __pIpcClient; + SetLastResult(r); +} + +_IpcClient* +_DeviceManagerImpl::GetIpcClient(void) +{ + if (__pDeviceManagerImpl != null) + { + return __pDeviceManagerImpl->__pIpcClient; + } + + SysLogException(NID_SYS, E_SYSTEM, "IPC component is not ready"); + + return null; +} + +void +_DeviceManagerImpl::DeviceEventVConfCallBack(keynode_t* node, void* userData) +{ + int ret = 0; + int value = 0; + String event; + + if (strcmp(VCONFKEY_SYSMAN_MMC_STATUS, vconf_keynode_get_name(node)) == 0) + { + SysLog(NID_SYS, "MMC callback is occured"); + if (__pDeviceManagerImpl != null) + { + ret = vconf_get_int(VCONFKEY_SYSMAN_MMC_STATUS, &value); + if (value == 1) + { + event = _DEVICE_MANAGER_STATE_MOUNTED; + } + else + { + event = _DEVICE_MANAGER_STATE_UNMOUNTED; + } + __pDeviceManagerImpl->SendEvent(DEVICE_TYPE_STORAGE_CARD, event); + } + } + else if(strcmp(VCONFKEY_SYSMAN_HDMI, vconf_keynode_get_name(node)) == 0) + { + if (__pDeviceManagerImpl != null) + { + ret = vconf_get_int(VCONFKEY_SYSMAN_HDMI, &value); + if (value == 1) + { + event = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + event = _DEVICE_MANAGER_STATE_REMOVED; + } + __pDeviceManagerImpl->SendEvent(DEVICE_TYPE_HDMI, event); + } + + } +} + +void +_DeviceManagerImpl::MmcEventVconfCallback(keynode_t* node, void* userData) +{ + if (strcmp(VCONFKEY_APPSERVICE_MMC_STATUS, vconf_keynode_get_name(node)) == 0) + { + SysLog(NID_SYS, "MMC event callback is called."); + if (__pDeviceManagerImpl != NULL) + { + String event; + int value = 0; + int ret = vconf_get_int(VCONFKEY_APPSERVICE_MMC_STATUS, &value); + if(ret == -1) + { + SysLogException(NID_SYS, E_SYSTEM, "VCONFKEY_APPSERVICE_MMC_STATUS is error"); + } + if (value == 1) + { + event = _DEVICE_MANAGER_STATE_MOUNTED; + } + else + { + event = _DEVICE_MANAGER_STATE_UNMOUNTED; + } + __pDeviceManagerImpl->SendEvent(DEVICE_TYPE_STORAGE_CARD, event); + } + } +} + +void +_DeviceManagerImpl::SendEvent(DeviceType deviceType, String& state) +{ + std::unique_ptr< IEnumeratorT<_DeviceEventListenerContainer*> > pEnumerator(null); + + if(__deviceEventList.GetCount() > 0) + { + pEnumerator.reset(__deviceEventList.GetEnumeratorN()); + SysTryReturnVoidResult(NID_SYS, pEnumerator != null, E_SYSTEM, "Enumerator is empty."); + + while(pEnumerator->MoveNext() == E_SUCCESS) + { + _DeviceEventListenerContainer* pDeviceEventListenerContainer = null; + pEnumerator->GetCurrent(pDeviceEventListenerContainer); + SysTryReturnVoidResult(NID_SYS, pDeviceEventListenerContainer != null,E_SYSTEM, "Container is empty"); + + switch(deviceType) + { + case DEVICE_TYPE_BLUETOOTH_HEADSET: + { + if(pDeviceEventListenerContainer->__bluetoothHeadset == false) + { + return; + } + break; + } + case DEVICE_TYPE_CHARGER: + { + if(pDeviceEventListenerContainer->__charger == false) + { + return; + } + break; + } + case DEVICE_TYPE_USB_CLIENT: + { + if(pDeviceEventListenerContainer->__usbClient == false) + { + return; + } + break; + } + case DEVICE_TYPE_TV_OUT: + { + if(pDeviceEventListenerContainer->__tvOut == false) + { + return; + } + break; + } + case DEVICE_TYPE_WIRED_HEADSET: + { + if(pDeviceEventListenerContainer->__wiredHeadset == false) + { + return; + } + break; + } + case DEVICE_TYPE_WIRED_HEADPHONE: + { + if(pDeviceEventListenerContainer->__wiredHeadphone == false) + { + return; + } + break; + } + case DEVICE_TYPE_STORAGE_CARD: + { + if(pDeviceEventListenerContainer->__storageCard == false) + { + return; + } + break; + } + case DEVICE_TYPE_KEYBOARD: + { + if(pDeviceEventListenerContainer->__keyboard == false) + { + return; + } + break; + } + case DEVICE_TYPE_HDMI: + { + if(pDeviceEventListenerContainer->__hdmi == false) + { + return; + } + break; + } + default: + return; + } + std::unique_ptr<_DeviceManagerEventArg> pDeviceManagerEventArg(new (std::nothrow) _DeviceManagerEventArg()); + if(pDeviceManagerEventArg == null) + { + SysLogException(NID_SYS, E_OUT_OF_MEMORY, "It is failed to create instance of DeviceManagerEventArg"); + return; + } + pDeviceManagerEventArg->deviceType = deviceType; + pDeviceManagerEventArg->state = state; + + if(pDeviceEventListenerContainer->__pEvent != null) + { + pDeviceEventListenerContainer->__pEvent->Fire(*(pDeviceManagerEventArg.release())); + } + } + } +} + +result +_DeviceManagerImpl::RequireBluetoothEvent(void) +{ + result r = E_SUCCESS; + std::unique_ptr pRequest(null); + + SysTryReturnResult(NID_SYS, __pIpcClient != null, E_SYSTEM, "Ipc Client is not ready"); + + __bluetoothReferenceCount ++; + + if(__bluetoothReferenceCount == 1) + { + ArrayList requestMessages; + ArrayList responseMessages; + + r = requestMessages.Construct(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to create request instance"); + r = responseMessages.Construct(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to create response instance"); + + String serviceId = _DEVICE_MANAGER_SERVICE_ID; + String commandId = _DEVICE_MANAGER_COMMAND_OPEN; + String deviceId = _DEVICE_MANAGER_BLUETOOTH; + + r = requestMessages.Add(serviceId); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add service id"); + r = requestMessages.Add(commandId); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add command id"); + r = requestMessages.Add(deviceId); + + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add device id (bluetooth)"); + + pRequest.reset(new (std::nothrow) IoService_Request(requestMessages, &responseMessages)); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to send bluetooth event subscribe by IPC"); + + r = __pIpcClient->SendRequest(pRequest.get()); + SysTryReturnResult(NID_SYS, r == E_SUCCESS,E_SYSTEM, "Failed to add bluetooth id"); + } + return r; +} + +result +_DeviceManagerImpl::ReleaseBluetoothEvent(void) +{ + result r = E_SUCCESS; + std::unique_ptr pRequest(null); + SysTryReturnResult(NID_SYS, __pIpcClient != null, E_SYSTEM, "Ipc Client is not ready"); + + __bluetoothReferenceCount --; + SysTryReturnResult(NID_SYS, __bluetoothReferenceCount >= 0, E_SYSTEM, "Fail to manage reference count"); + + if(__bluetoothReferenceCount == 0) + { + ArrayList requestMessages; + ArrayList responseMessages; + + r = requestMessages.Construct(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to create request instance"); + r = responseMessages.Construct(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to create response instance"); + + String serviceId = _DEVICE_MANAGER_SERVICE_ID; + String commandId = _DEVICE_MANAGER_COMMAND_CLOSE; + String deviceId = _DEVICE_MANAGER_BLUETOOTH; + + r = requestMessages.Add(serviceId); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add service id"); + r = requestMessages.Add(commandId); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add command id"); + r = requestMessages.Add(deviceId); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add bluetooth id"); + + pRequest.reset(new (std::nothrow) IoService_Request(requestMessages, &responseMessages)); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to send bluetooth event subscribe by IPC"); + + r = __pIpcClient->SendRequest(pRequest.get()); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to add bluetooth id"); + } + return r; +} + +result +_DeviceManagerImpl::AddOnExistedListener(DeviceType deviceType, const IDeviceEventListener* pListener) +{ + result r = E_OBJ_NOT_FOUND; + std::unique_ptr< IEnumeratorT<_DeviceEventListenerContainer*> > pEnumerator(null); + + if(__deviceEventList.GetCount() > 0) + { + pEnumerator.reset(__deviceEventList.GetEnumeratorN()); + SysTryReturnResult(NID_SYS, pEnumerator != null, E_SYSTEM, "Enumerator is empty."); + + while(pEnumerator->MoveNext() == E_SUCCESS) + { + _DeviceEventListenerContainer* pDeviceEventListenerContainer = null; + pEnumerator->GetCurrent(pDeviceEventListenerContainer); + SysTryReturnResult(NID_SYS, pDeviceEventListenerContainer != null, E_SYSTEM, "[E_SYSTEM] Device Event Container is empty."); + if(pDeviceEventListenerContainer->__pListener == pListener) + { + switch(deviceType) + { + case DEVICE_TYPE_BLUETOOTH_HEADSET: + { + if(pDeviceEventListenerContainer->__bluetoothHeadset == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__bluetoothHeadset = true; + RequireBluetoothEvent(); + r = E_SUCCESS; + } + break; + } + case DEVICE_TYPE_CHARGER: + { + if(pDeviceEventListenerContainer->__charger == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__charger = true; + r = E_SUCCESS; + } + break; + } + case DEVICE_TYPE_USB_CLIENT: + { + if(pDeviceEventListenerContainer->__usbClient == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__usbClient = true; + r = E_SUCCESS; + } + break; + } + case DEVICE_TYPE_TV_OUT: + { + bool tvOut = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_TVOUT_SUPPORTED, tvOut); + + if (tvOut == false) + { + if(!_AppInfo::IsOspCompat()) + { + r = E_UNSUPPORTED_OPERATION; + } + else + { + r = E_DEVICE_UNAVAILABLE; + } + break; + } + + if(pDeviceEventListenerContainer->__tvOut == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__tvOut = true; + r = E_SUCCESS; + } + break; + } + case DEVICE_TYPE_WIRED_HEADSET: + { + if(pDeviceEventListenerContainer->__wiredHeadset == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__wiredHeadset = true; + r = E_SUCCESS; + } + break; + } + case DEVICE_TYPE_WIRED_HEADPHONE: + { + if(pDeviceEventListenerContainer->__wiredHeadphone == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__wiredHeadphone = true; + r = E_SUCCESS; + } + break; + } + case DEVICE_TYPE_STORAGE_CARD: + { + if(pDeviceEventListenerContainer->__storageCard == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__storageCard = true; + r = E_SUCCESS; + } + break; + } + case DEVICE_TYPE_KEYBOARD: + { + bool keyboard = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_INPUT_KEYBOARD, keyboard); + + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get keyboard option"); + + if (keyboard == false) + { + if(!_AppInfo::IsOspCompat()) + { + return E_UNSUPPORTED_OPERATION; + } + else + { + return E_DEVICE_UNAVAILABLE; + } + } + + if(pDeviceEventListenerContainer->__keyboard == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__keyboard = true; + r = E_SUCCESS; + } + break; + } + case DEVICE_TYPE_HDMI: + { + int value = 0; + int ret = 0; + ret = vconf_get_int(VCONFKEY_SYSMAN_HDMI, &value); + SysTryReturnResult(NID_SYS, !(ret < 0), E_SYSTEM, "vconf_get_int failed Output value is %d", value); + if(value < 0) + { + return E_UNSUPPORTED_OPERATION; + } + if(pDeviceEventListenerContainer->__hdmi == true) + { + r = E_OBJ_ALREADY_EXIST; + } + else + { + pDeviceEventListenerContainer->__hdmi = true; + r = E_SUCCESS; + } + break; + } + } + } + } + } + return r; +} + +result +_DeviceManagerImpl::AddDeviceEventListener(DeviceType deviceType, IDeviceEventListener* pListener) +{ + SysTryReturnResult(NID_SYS, pListener != null, E_INVALID_ARG, "There is no listener isntance."); + SysTryReturnResult(NID_SYS, (deviceType >= DEVICE_TYPE_BLUETOOTH_HEADSET && deviceType <= DEVICE_TYPE_HDMI), E_INVALID_ARG, "There is no listener isntance."); + result r = E_SUCCESS; + + if(deviceType == DEVICE_TYPE_TV_OUT) + { + bool tvOut = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_TVOUT_SUPPORTED, tvOut); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get tvout option."); + + if (tvOut == false) + { + if(!_AppInfo::IsOspCompat()) + { + r = E_UNSUPPORTED_OPERATION; + } + else + { + r = E_DEVICE_UNAVAILABLE; + } + return r; + } + } + else if(deviceType == DEVICE_TYPE_KEYBOARD) + { + bool keyboard = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_INPUT_KEYBOARD, keyboard); + + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get keyboard option"); + + if (keyboard == false) + { + if(!_AppInfo::IsOspCompat()) + { + r = E_UNSUPPORTED_OPERATION; + } + else + { + r = E_DEVICE_UNAVAILABLE; + } + return r; + } + } + else if(deviceType == DEVICE_TYPE_HDMI) + { + int value = 0; + int ret = 0; + ret = vconf_get_int(VCONFKEY_SYSMAN_HDMI, &value); + SysTryReturnResult(NID_SYS, !(ret < 0), E_SYSTEM, "vconf_get_int failed Output value is %d", value); + if(value < 0) + { + return E_UNSUPPORTED_OPERATION; + } + } + + r = AddOnExistedListener(deviceType, pListener); + + if(r == E_OBJ_NOT_FOUND) + { + std::unique_ptr<_DeviceEventListenerContainer> pDeviceEventContainer(new (std::nothrow) _DeviceEventListenerContainer()); + SysTryReturnResult(NID_SYS, pDeviceEventContainer != null, E_OUT_OF_MEMORY, "It is failed to create instance of _DeviceEventListenerContainer"); + + std::unique_ptr<_DeviceManagerEvent> pDeviceManagerEvent(new (std::nothrow) _DeviceManagerEvent()); + SysTryReturnResult(NID_SYS, pDeviceManagerEvent != null, E_OUT_OF_MEMORY, "It is failed to create instance of _DeviceManagerEvent"); + + pDeviceManagerEvent->AddListener(*pListener); + pDeviceEventContainer->__pListener = pListener; + pDeviceEventContainer->__pEvent = pDeviceManagerEvent.release(); + + switch(deviceType) + { + case DEVICE_TYPE_BLUETOOTH_HEADSET: + { + pDeviceEventContainer->__bluetoothHeadset = true; + RequireBluetoothEvent(); + break; + } + case DEVICE_TYPE_CHARGER: + { + pDeviceEventContainer->__charger = true; + break; + } + case DEVICE_TYPE_USB_CLIENT: + { + pDeviceEventContainer->__usbClient = true; + break; + } + case DEVICE_TYPE_TV_OUT: + { + bool tvOut = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_TVOUT_SUPPORTED, tvOut); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get tvout option."); + + if (tvOut == false) + { + if(!_AppInfo::IsOspCompat()) + { + return E_UNSUPPORTED_OPERATION; + } + else + { + return E_DEVICE_UNAVAILABLE; + } + } + + pDeviceEventContainer->__tvOut = true; + break; + } + case DEVICE_TYPE_WIRED_HEADSET: + { + pDeviceEventContainer->__wiredHeadset = true; + break; + } + case DEVICE_TYPE_WIRED_HEADPHONE: + { + pDeviceEventContainer->__wiredHeadphone = true; + break; + } + case DEVICE_TYPE_STORAGE_CARD: + { + pDeviceEventContainer->__storageCard = true; + break; + } + case DEVICE_TYPE_KEYBOARD: + { + bool keyboard = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_INPUT_KEYBOARD, keyboard); + + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get keyboard option"); + + if (keyboard == false) + { + if(!_AppInfo::IsOspCompat()) + { + return E_UNSUPPORTED_OPERATION; + } + else + { + return E_DEVICE_UNAVAILABLE; + } + } + + pDeviceEventContainer->__keyboard = true; + break; + } + case DEVICE_TYPE_HDMI: + { + int value = 0; + int ret = 0; + ret = vconf_get_int(VCONFKEY_SYSMAN_HDMI, &value); + SysTryReturnResult(NID_SYS, !(ret < 0), E_SYSTEM, "vconf_get_int failed Output value is %d", value); + if(value < 0) + { + return E_UNSUPPORTED_OPERATION; + } + pDeviceEventContainer->__hdmi = true; + break; + } + } + r = E_SUCCESS; + __deviceEventList.Add(pDeviceEventContainer.release()); + } + + return r; +} + +result +_DeviceManagerImpl::RemoveDeviceEventListener(DeviceType deviceType, IDeviceEventListener* pListener) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SYS, pListener != null, E_INVALID_ARG, "There is no listener isntance."); + SysTryReturnResult(NID_SYS, (deviceType >= DEVICE_TYPE_BLUETOOTH_HEADSET && deviceType <= DEVICE_TYPE_HDMI), E_INVALID_ARG, "There is no listener isntance."); + SysTryReturnResult(NID_SYS, __deviceEventList.GetCount() > 0, E_INVALID_ARG, "There is no registered listener."); + + std::unique_ptr< IEnumeratorT<_DeviceEventListenerContainer*> > pEnumerator(__deviceEventList.GetEnumeratorN()); + + SysTryReturnResult(NID_SYS, pEnumerator != null, E_SYSTEM, "Enumerator is empty."); + + if(deviceType == DEVICE_TYPE_TV_OUT) + { + bool tvOut = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_TVOUT_SUPPORTED, tvOut); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get tvout option."); + + if (tvOut == false) + { + if(!_AppInfo::IsOspCompat()) + { + r = E_UNSUPPORTED_OPERATION; + } + else + { + r = E_DEVICE_UNAVAILABLE; + } + } + return r; + } + else if(deviceType == DEVICE_TYPE_KEYBOARD) + { + bool keyboard = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_INPUT_KEYBOARD, keyboard); + + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get keyboard option"); + + if (keyboard == false) + { + if(!_AppInfo::IsOspCompat()) + { + r = E_UNSUPPORTED_OPERATION; + } + else + { + r = E_DEVICE_UNAVAILABLE; + } + } + } + else if(deviceType == DEVICE_TYPE_HDMI) + { + int value = 0; + int ret = 0; + ret = vconf_get_int(VCONFKEY_SYSMAN_HDMI, &value); + SysTryReturnResult(NID_SYS, !(ret < 0), E_SYSTEM, "vconf_get_int failed Output value is %d", value); + if(value < 0) + { + return E_UNSUPPORTED_OPERATION; + } + } + + while(pEnumerator->MoveNext() == E_SUCCESS) + { + _DeviceEventListenerContainer* pDeviceEventListenerContainer = null; + pEnumerator->GetCurrent(pDeviceEventListenerContainer); + SysTryReturnResult(NID_SYS, pDeviceEventListenerContainer != null, E_SYSTEM, "[E_SYSTEM] Device Event Container is empty."); + + if(pDeviceEventListenerContainer->__pListener == pListener) + { + switch(deviceType) + { + case DEVICE_TYPE_BLUETOOTH_HEADSET: + { + if(pDeviceEventListenerContainer->__bluetoothHeadset == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__bluetoothHeadset = false; + ReleaseBluetoothEvent(); + break; + } + case DEVICE_TYPE_CHARGER: + { + if(pDeviceEventListenerContainer->__charger == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__charger = false; + break; + } + case DEVICE_TYPE_USB_CLIENT: + { + if(pDeviceEventListenerContainer->__usbClient == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__usbClient = false; + break; + } + case DEVICE_TYPE_TV_OUT: + { + if(pDeviceEventListenerContainer->__tvOut == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__tvOut = false; + break; + } + case DEVICE_TYPE_WIRED_HEADSET: + { + if(pDeviceEventListenerContainer->__wiredHeadset == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__wiredHeadset = false; + break; + } + case DEVICE_TYPE_WIRED_HEADPHONE: + { + if(pDeviceEventListenerContainer->__wiredHeadphone == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__wiredHeadphone = false; + break; + } + case DEVICE_TYPE_STORAGE_CARD: + { + if(pDeviceEventListenerContainer->__storageCard == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__storageCard = false; + break; + } + case DEVICE_TYPE_KEYBOARD: + { + if(pDeviceEventListenerContainer->__keyboard == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__keyboard = false; + break; + } + case DEVICE_TYPE_HDMI: + { + if(pDeviceEventListenerContainer->__hdmi == false) + { + return E_OBJ_NOT_FOUND; + } + pDeviceEventListenerContainer->__hdmi = false; + break; + } + } + + if(pDeviceEventListenerContainer->IsInvalid() == true) + { + __deviceEventList.Remove(pDeviceEventListenerContainer); + delete pDeviceEventListenerContainer; + } + return E_SUCCESS; + } + } + return E_OBJ_NOT_FOUND; +} + +result +_DeviceManagerImpl::RemoveAllDeviceEventListeners(void) +{ + result r = E_SUCCESS; + + IEnumeratorT<_DeviceEventListenerContainer*>* pEnumerator = __deviceEventList.GetEnumeratorN(); + SysTryReturnResult(NID_SYS, pEnumerator != null, E_SYSTEM, "Enumerator is empty."); + + while(pEnumerator->MoveNext() == E_SUCCESS) + { + _DeviceEventListenerContainer* pDeviceEventListenerContainer = null; + pEnumerator->GetCurrent(pDeviceEventListenerContainer); + SysTryReturnResult(NID_SYS, pDeviceEventListenerContainer != null, E_SYSTEM, "[E_SYSTEM] Device Event Container is empty."); + __deviceEventList.Remove(pDeviceEventListenerContainer); + delete pDeviceEventListenerContainer; + } + delete pEnumerator; + + __bluetoothReferenceCount = 1; + + ReleaseBluetoothEvent(); + return r; +} + +void +_DeviceManagerImpl::SendEvent(runtime_info_key_e key) +{ + DeviceType type = DEVICE_TYPE_USB_CLIENT; + String value; + int flag = 0; + int ret = 0; + + switch (key) + { + case RUNTIME_INFO_KEY_USB_CONNECTED: + { + flag = _DEVICE_MANAGER_USB_CLIENT; + type = DEVICE_TYPE_USB_CLIENT; + + bool state = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_USB_CONNECTED, &state); + if (ret != RUNTIME_INFO_ERROR_NONE) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to get usb state"); + return; + } + + if (state == true) + { + value = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + value = _DEVICE_MANAGER_STATE_REMOVED; + } + break; + } + case RUNTIME_INFO_KEY_CHARGER_CONNECTED: + { + flag = _DEVICE_MANAGER_CHARGER; + type = DEVICE_TYPE_CHARGER; + + bool state = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_CHARGER_CONNECTED, &state); + if (ret != RUNTIME_INFO_ERROR_NONE) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to get charger state"); + return; + } + + if (state == true) + { + value = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + value = _DEVICE_MANAGER_STATE_REMOVED; + } + break; + } + case RUNTIME_INFO_KEY_TV_OUT_CONNECTED: + { + flag = _DEVICE_MANAGER_TV_OUT; + type = DEVICE_TYPE_TV_OUT; + + bool state = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_TV_OUT_CONNECTED, &state); + if (ret != RUNTIME_INFO_ERROR_NONE) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to get tv connect state"); + return; + } + + if (state == true) + { + value = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + value = _DEVICE_MANAGER_STATE_REMOVED; + } + break; + } + case RUNTIME_INFO_KEY_AUDIO_JACK_STATUS: + { + int state = 0; + ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, &state); + if (ret != RUNTIME_INFO_ERROR_NONE) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to get audion jack state"); + return; + } + + if (state == RUNTIME_INFO_AUDIO_JACK_STATUS_UNCONNECTED) + { + if (__headSetType == DEVICE_TYPE_WIRED_HEADPHONE) + { + flag = _DEVICE_MANAGER_WIRED_HEADPHONE; + type = DEVICE_TYPE_WIRED_HEADPHONE; + } + else + { + flag = _DEVICE_MANAGER_WIRED_HEADSET; + type = DEVICE_TYPE_WIRED_HEADSET; + } + + value = _DEVICE_MANAGER_STATE_REMOVED; + } + else + { + if (state == RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_3WIRE) + { + __headSetType = DEVICE_TYPE_WIRED_HEADPHONE; + flag = _DEVICE_MANAGER_WIRED_HEADPHONE; + type = DEVICE_TYPE_WIRED_HEADPHONE; + } + else + { + __headSetType = DEVICE_TYPE_WIRED_HEADSET; + flag = _DEVICE_MANAGER_WIRED_HEADSET; + type = DEVICE_TYPE_WIRED_HEADSET; + } + value = _DEVICE_MANAGER_STATE_INSERTED; + + } + break; + } + case RUNTIME_INFO_KEY_SLIDING_KEYBOARD_OPENED: + { + flag = _DEVICE_MANAGER_KEYBOARD; + type = DEVICE_TYPE_KEYBOARD; + + bool state = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_SLIDING_KEYBOARD_OPENED, &state); + if (ret != RUNTIME_INFO_ERROR_NONE) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to get keyboard state"); + return; + } + + if (state == true) + { + value = _DEVICE_MANAGER_STATE_OPENED; + } + else + { + value = _DEVICE_MANAGER_STATE_CLOSED; + } + break; + } + default: + break; + } + + __pDeviceManagerImpl->SendEvent(type, value); + +} + +result +_DeviceManagerImpl::GetState(DeviceType deviceType, String& state) +{ + result r = E_SUCCESS; + int value = 0; + int ret = 0; + + SysTryReturnResult(NID_SYS, __pIpcClient != null, E_SYSTEM, "GetDeviceState Failed"); + + switch (deviceType) + { + + case DEVICE_TYPE_BLUETOOTH_HEADSET: + { + ArrayList requestMessages; + ArrayList responseMessages; + + requestMessages.Construct(); + responseMessages.Construct(); + + String serviceId = _DEVICE_MANAGER_SERVICE_ID; + String commandId = _DEVICE_MANAGER_COMMAND_STATUS; + String deviceId = _DEVICE_MANAGER_BLUETOOTH; + + requestMessages.Add(serviceId); + requestMessages.Add(commandId); + requestMessages.Add(deviceId); + + IoService_Request* pMsg = new (std::nothrow) IoService_Request(requestMessages, &responseMessages); + + r = __pIpcClient->SendRequest(*pMsg); + + String* pMessageData = (String*)responseMessages.GetAt(_OSP_APP_SERVICE_IPC_MESSAGE_DATA); + if (pMessageData != null) + { + state = *pMessageData; + } + delete pMsg; + break; + } + + case DEVICE_TYPE_CHARGER: + { + bool chargerState = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_CHARGER_CONNECTED, &chargerState); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get charger state"); + + if (chargerState == true) + { + state = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + state = _DEVICE_MANAGER_STATE_REMOVED; + } + break; + } + + case DEVICE_TYPE_USB_CLIENT: + { + bool cableState = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_USB_CONNECTED, &cableState); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get usb state"); + + if (cableState == true) + { + state = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + state = _DEVICE_MANAGER_STATE_REMOVED; + } + break; + } + + case DEVICE_TYPE_TV_OUT: + { + bool tvOut = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_TVOUT_SUPPORTED, tvOut); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get tvout option."); + + if (tvOut == false) + { + if(!_AppInfo::IsOspCompat()) + { + return E_UNSUPPORTED_OPERATION; + } + else + { + return E_DEVICE_UNAVAILABLE; + } + } + + bool tvState = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_TV_OUT_CONNECTED, &tvState); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get tv state"); + if (tvState == true) + { + state = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + state = _DEVICE_MANAGER_STATE_REMOVED; + } + break; + } + + case DEVICE_TYPE_WIRED_HEADSET: + { + int audioState = 0; + ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, &audioState); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get audio state"); + + if (audioState == RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_4WIRE) + { + state = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + state = _DEVICE_MANAGER_STATE_REMOVED; + } + break; + } + + case DEVICE_TYPE_WIRED_HEADPHONE: + { + int audioState = 0; + ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, &audioState); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get audio state"); + + if (audioState == RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_3WIRE) + { + state = _DEVICE_MANAGER_STATE_INSERTED; + } + else + { + state = _DEVICE_MANAGER_STATE_REMOVED; + } + break; + } + + case DEVICE_TYPE_STORAGE_CARD: + { + int ret = 0; + if (!_AppInfo::IsOspCompat()) + { + ret = vconf_get_int(VCONFKEY_SYSMAN_MMC_STATUS, &value); + } + else + { + ret = vconf_get_int(VCONFKEY_APPSERVICE_MMC_STATUS, &value); + } + SysTryReturnResult(NID_SYS, !(ret < 0), E_SYSTEM, "vconf_get_int failed Output value is %d", value); + if (value == 1) + { + state = _DEVICE_MANAGER_STATE_MOUNTED; + } + else + { + state = _DEVICE_MANAGER_STATE_UNMOUNTED; + } + break; + } + + case DEVICE_TYPE_KEYBOARD: + { + bool keyboard = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_INFO_INPUT_KEYBOARD, keyboard); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Fail to get keyboard option."); + if (keyboard == false) + { + if(!_AppInfo::IsOspCompat()) + { + return E_UNSUPPORTED_OPERATION; + } + else + { + return E_DEVICE_UNAVAILABLE; + } + } + break; + } + case DEVICE_TYPE_HDMI: + { + int ret = 0; + ret = vconf_get_int(VCONFKEY_SYSMAN_HDMI, &value); + SysTryReturnResult(NID_SYS, !(ret < 0), E_SYSTEM, "vconf_get_int failed Output value is %d", value); + if (value == 1) + { + state = _DEVICE_MANAGER_STATE_INSERTED; + } + else if(value == 0) + { + state = _DEVICE_MANAGER_STATE_REMOVED; + } + else + { + return E_UNSUPPORTED_OPERATION; + } + + break; + } + + default: + return E_INVALID_ARG; + } + return E_SUCCESS; +} + +void +_DeviceManagerImpl::OnIpcResponseReceived(_IpcClient& client, const IPC::Message& message) +{ + SysLog(NID_SYS, "Enter."); + IPC_BEGIN_MESSAGE_MAP(_DeviceManagerImpl, message) + IPC_MESSAGE_HANDLER_EX(IoService_Data, &client, OnDataReceived) + IPC_END_MESSAGE_MAP_EX() + SysLog(NID_SYS, "Exit."); +} + +void +_DeviceManagerImpl::OnDataReceived(const ArrayList& data) +{ + StringComparer stringComparer; + + int cmp = 0; + String* pServiceId = (String*) data.GetAt(_OSP_APP_SERVICE_IPC_MESSAGE_HEAD_SERVICE_ID); + String* pCommandId = (String*) data.GetAt(_OSP_APP_SERVICE_IPC_MESSAGE_HEAD_COMMAND_ID); + String* pDeviceId = (String*) data.GetAt(_OSP_APP_SERVICE_IPC_MESSAGE_HEAD_DEVICE_ID); + String* pEventId = (String*) data.GetAt(_OSP_APP_SERVICE_IPC_MESSAGE_DATA); + + String serviceId = _DEVICE_MANAGER_SERVICE_ID; + String commandId = _DEVICE_MANAGER_COMMAND_EVENT; + String deviceId = _DEVICE_MANAGER_BLUETOOTH; + + SysTryReturnVoidResult(NID_SYS, pServiceId != null && pCommandId != null && pDeviceId != null && pEventId != null, E_SYSTEM, "There is no device data."); + + stringComparer.Compare(*pServiceId, serviceId, cmp); + if (cmp == 0) + { + stringComparer.Compare(*pCommandId, commandId, cmp); + if (cmp == 0) + { + stringComparer.Compare(*pDeviceId, deviceId, cmp); + if (cmp == 0) + { + __pDeviceManagerImpl->SendEvent(DEVICE_TYPE_BLUETOOTH_HEADSET, *pEventId); + } + } + } +} + +} } // Tizen::System diff --git a/src/system/FSys_DeviceManagerImpl.h b/src/system/FSys_DeviceManagerImpl.h new file mode 100644 index 0000000..1836173 --- /dev/null +++ b/src/system/FSys_DeviceManagerImpl.h @@ -0,0 +1,116 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_DeviceManagerImpl.h + * @brief This is the header file for the _DeviceManagerImpl class. + */ + +#ifndef _FSYS_INTERNAL_DEVICE_MANAGER_IMPL_H_ +#define _FSYS_INTERNAL_DEVICE_MANAGER_IMPL_H_ + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace Tizen { namespace Base +{ +namespace Collection { +class ArrayList; +} +}} + +namespace Tizen { namespace Io +{ +class _IpcClient; +}} + +namespace Tizen { namespace System +{ + +class _DeviceManagerImpl + : public Tizen::Io::_IIpcClientEventListener +{ +private: + _DeviceManagerImpl(); + + virtual ~_DeviceManagerImpl(); + +public: + result GetState(DeviceType deviceType, Tizen::Base::String& state); + + result AddDeviceEventListener(DeviceType deviceType, IDeviceEventListener* pListener); + + result RemoveDeviceEventListener(DeviceType deviceType, IDeviceEventListener* pListener); + + result RemoveAllDeviceEventListeners(void); + + void OnIpcResponseReceived(Tizen::Io::_IpcClient& client, const IPC::Message& message); + + void OnDataReceived(const Tizen::Base::Collection::ArrayList& data); + + void SendEvent(runtime_info_key_e key); + + void SendEvent(DeviceType deviceType, Tizen::Base::String& state); + + static _DeviceManagerImpl* GetInstance(void); + + static Tizen::Io::_IpcClient* GetIpcClient(void); + +private: + _DeviceManagerImpl(const _DeviceManagerImpl& deviceManagerImpl); + + _DeviceManagerImpl& operator =(const _DeviceManagerImpl& deviceManagerImpl); + + result AddOnExistedListener(DeviceType deviceType, const IDeviceEventListener* pListener); + + result RequireBluetoothEvent(void); + + result ReleaseBluetoothEvent(void); + + static void OnDeviceStateChanged(runtime_info_key_e key, void* pData); + + static void DeviceEventVConfCallBack(keynode_t* node, void* userData); + + static void MmcEventVconfCallback(keynode_t* node, void* userData); + + static void InitDeviceManagerImpl(void); + +private: + Tizen::Io::_IpcClient* __pIpcClient; + + DeviceType __headSetType; + + int __bluetoothReferenceCount; + + Tizen::Base::Collection::ArrayListT<_DeviceEventListenerContainer*> __deviceEventList; + + static _DeviceManagerImpl* __pDeviceManagerImpl; +}; + +}} // Tizen::System + +#endif // _FSYS_INTERNAL_DEVICE_MANAGER_IMPL_H_ diff --git a/src/system/FSys_EnvironmentImpl.cpp b/src/system/FSys_EnvironmentImpl.cpp new file mode 100644 index 0000000..9dc8012 --- /dev/null +++ b/src/system/FSys_EnvironmentImpl.cpp @@ -0,0 +1,170 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_EnvironmentImpl.cpp + * @brief This is the implementation file for %_EnvironmentImpl class. + */ + +#include + +#include "FSys_EnvironmentImpl.h" + +using namespace Tizen::Base; + +namespace Tizen { namespace System +{ + +static const wchar_t _MEDIA_PATH[] = L"/opt/usr/media/"; +static const wchar_t _MEDIA_IMAGES_PATH[] = L"/opt/usr/media/Images/"; +static const wchar_t _MEDIA_SOUNDS_PATH[] = L"/opt/usr/media/Sounds/"; +static const wchar_t _MEDIA_VIDEOS_PATH[] = L"/opt/usr/media/Videos/"; +static const wchar_t _MEDIA_CAMERA_PATH[] = L"/opt/usr/media/Camera/"; +static const wchar_t _MEDIA_DOWNLOADS_PATH[] = L"/opt/usr/media/Downloads/"; +static const wchar_t _MEDIA_OTHERS_PATH[] = L"/opt/usr/media/Others/"; + +static const wchar_t _EXTERNAL_MMC_PATH[] = L"/opt/storage/sdcard/"; +static const wchar_t _EXTERNAL_MMC_IMAGES_PATH[] = L"/opt/storage/sdcard/Images/"; +static const wchar_t _EXTERNAL_MMC_SOUNDS_PATH[] = L"/opt/storage/sdcard/Sounds/"; +static const wchar_t _EXTERNAL_MMC_VIDEOS_PATH[] = L"/opt/storage/sdcard/Videos/"; +static const wchar_t _EXTERNAL_MMC_CAMERA_PATH[] = L"/opt/storage/sdcard/Camera/"; +static const wchar_t _EXTERNAL_MMC_DOWNLOADS_PATH[] = L"/opt/storage/sdcard/Downloads/"; +static const wchar_t _EXTERNAL_MMC_OTHERS_PATH[] = L"/opt/storage/sdcard/Others/"; + +static const wchar_t _APPLICATIONS_PATH[] = L"/opt/usr/apps/"; +static const wchar_t _EXTERNAL_APPLICATIONS_PATH[] = L"/opt/storage/sdcard/app2sd/"; + +static const wchar_t _COMPAT_SHARED_PATH[] = L"/opt/usr/share/.osp-compat/"; + +_EnvironmentImpl::_EnvironmentImpl(void) +{ +} + +_EnvironmentImpl::~_EnvironmentImpl(void) +{ +} + +String +_EnvironmentImpl::GetMediaPath(void) +{ + static String mediaPath(_MEDIA_PATH); + return mediaPath; +} + +String +_EnvironmentImpl::GetDefaultDownloadPath(void) +{ + static String downloadPath(_MEDIA_DOWNLOADS_PATH); + return downloadPath; +} + +String +_EnvironmentImpl::GetExternalStoragePath(void) +{ + static String externalStoragePath(_EXTERNAL_MMC_PATH); + return externalStoragePath; +} + +String +_EnvironmentImpl::GetOspCompatSharedPath(void) +{ + static String ospCompatSharedPath(_COMPAT_SHARED_PATH); + return ospCompatSharedPath; +} + +String +_EnvironmentImpl::GetPredefinedPath(PredefinedDirectoryType dirType) +{ + switch (dirType) + { + case PREDEFINED_DIRECTORY_IMAGES: + { + String path(_MEDIA_IMAGES_PATH); + return path; + } + case PREDEFINED_DIRECTORY_SOUNDS: + { + static String path(_MEDIA_SOUNDS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_VIDEOS: + { + static String path(_MEDIA_VIDEOS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_CAMERA: + { + static String path(_MEDIA_CAMERA_PATH); + return path; + } + case PREDEFINED_DIRECTORY_DOWNLOADS: + { + static String path(_MEDIA_DOWNLOADS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_OTHERS: + { + static String path(_MEDIA_OTHERS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_EXTERNAL_IMAGES: + { + static String path(_EXTERNAL_MMC_IMAGES_PATH); + return path; + } + case PREDEFINED_DIRECTORY_EXTERNAL_SOUNDS: + { + static String path(_EXTERNAL_MMC_SOUNDS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_EXTERNAL_VIDEOS: + { + static String path(_EXTERNAL_MMC_VIDEOS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_EXTERNAL_CAMERA: + { + static String path(_EXTERNAL_MMC_CAMERA_PATH); + return path; + } + case PREDEFINED_DIRECTORY_EXTERNAL_DOWNLOADS: + { + static String path(_EXTERNAL_MMC_DOWNLOADS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_EXTERNAL_OTHERS: + { + static String path(_EXTERNAL_MMC_OTHERS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_APPLICATIONS: + { + static String path(_APPLICATIONS_PATH); + return path; + } + case PREDEFINED_DIRECTORY_EXTERNAL_APPLICATIONS: + { + static String path(_EXTERNAL_APPLICATIONS_PATH); + return path; + } + default: + return String(L""); + } +} + +}} // Tizen::System + diff --git a/src/system/FSys_PowerManagerImpl.cpp b/src/system/FSys_PowerManagerImpl.cpp new file mode 100644 index 0000000..efa1cb9 --- /dev/null +++ b/src/system/FSys_PowerManagerImpl.cpp @@ -0,0 +1,736 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_PowerManagerImpl.cpp + * @brief This is the implementation file for _PowerManagerImpl class. + */ + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +using namespace Tizen::App; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +namespace Tizen { namespace System +{ + +static const int _DEVICE_CPU = 1; +static const int _DEVICE_POWER_LEVEL_ON = 1; +static const int _DEVICE_POWER_LEVEL_OFF = 0; +static const int _APPID_LENGTH = 10; +static const int _DEACTIVATED_BRIGHTNESS_CONTROL = -1; +static const float _BRIGHTNESS_RESOLUTION = 10.0; + +bool _activeApp = false; +bool _deviceCpuPowerOn = false; +bool _keepCpuAwake = false; +bool _keepScreenOnState = false; + +IBatteryEventListener* pIBatteryEventListener = null; +IChargingEventListener* pIChargingEventListener = null; +IScreenEventListener* pIScreenEventListener = null; + +ArrayListT<_IPowerManagerEventListener*> __powerEventList; + +bool _PowerManagerImpl::_InitPowerManager = false; + + +class _ActiveEventListener + : public IActiveAppEventListener +{ +public: + virtual void OnActiveAppChanged(const Tizen::App::AppId& appId); +}; + +void +_ActiveEventListener::OnActiveAppChanged(const Tizen::App::AppId& appId) +{ + int ret = 0; + String activeAppId; + appId.SubString(0, _APPID_LENGTH, activeAppId); + if(activeAppId == _AppInfo::GetAppId()) + { + _activeApp = true; + } + else + { + _activeApp = false; + + if (_keepScreenOnState == true) //In case of Screen power control, it has to be released automatically, when application goes deactive state. + { + ret = pm_unlock_state(LCD_NORMAL, GOTO_STATE_NOW); + SysTryReturnVoidResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] Failed to unlock the power state"); + _keepScreenOnState = false; + } + + if (_keepCpuAwake == true || _deviceCpuPowerOn == true) //In case of CPU power control, it has to be keep despite of deactive state. + { + ret = power_lock_state(POWER_STATE_SCREEN_OFF, 0); + SysTryReturnVoidResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] Failed to lock the power state"); + } + } +} + + _ActiveEventListener* pActiveEventListener = null; + +void +DeviceBatteryWarnCallback(device_battery_warn_e status, void* userData) +{ + SysLog(NID_SYS, "Battery Warn Level is called %d", status); + BatteryLevel batteryLevel; + + switch(status) + { + case DEVICE_BATTERY_WARN_EMPTY: + { + batteryLevel = BATTERY_EMPTY; + break; + } + case DEVICE_BATTERY_WARN_CRITICAL: + { + batteryLevel = BATTERY_CRITICAL; + break; + } + case DEVICE_BATTERY_WARN_LOW: + { + batteryLevel = BATTERY_LOW; + break; + } + case DEVICE_BATTERY_WARN_NORMAL: + { + batteryLevel = BATTERY_HIGH; + break; + } + case DEVICE_BATTERY_WARN_FULL: + { + batteryLevel = BATTERY_FULL; + break; + } + default: + return; + } + _AppImpl* pAppImpl = _AppImpl::GetInstance(); + if(pAppImpl != null) + { + SysLog(NID_SYS, "Battery Level event is forwarded"); + pAppImpl->OnBatteryLevelChanged(batteryLevel); + } + +} + +void +DeviceBatteryCallback(int percent, void* userData) +{ + SysLog(NID_SYS, "Battery Level is called %d", percent); + + if (pIBatteryEventListener != null) + { + pIBatteryEventListener->OnBatteryLevelChangedInPercentage(percent); + } +} + +void +RuntimeInfoChangedCallback(runtime_info_key_e key, void* userData) +{ + int ret = 0; + + if(_AppInfo::GetAppState() == RUNNING) + { + if (pIChargingEventListener != null) + { + bool charging = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_BATTERY_IS_CHARGING, &charging); + if (ret == 0) + { + pIChargingEventListener->OnChargingStateChanged(charging); + } + } + } +} + +void +PowerChangedCallback(power_state_e state, void* userData) +{ + std::unique_ptr< IEnumeratorT<_IPowerManagerEventListener*> > pEnumerator(__powerEventList.GetEnumeratorN()); + _IPowerManagerEventListener* pIPowerManagerEventListener = null; + if (pIScreenEventListener != null) + { + if (state == POWER_STATE_SCREEN_OFF) + { + pIScreenEventListener->OnScreenOff(); + + if(pEnumerator != null) + { + while(pEnumerator->MoveNext() == E_SUCCESS) + { + + pEnumerator->GetCurrent(pIPowerManagerEventListener); + if(pIPowerManagerEventListener != null) + { + pIPowerManagerEventListener->OnScreenStateChanged(false); + } + } + } + } + else + { + pIScreenEventListener->OnScreenOn(); + + if(pEnumerator != null) + { + while(pEnumerator->MoveNext() == E_SUCCESS) + { + pEnumerator->GetCurrent(pIPowerManagerEventListener); + if(pIPowerManagerEventListener != null) + { + pIPowerManagerEventListener->OnScreenStateChanged(true); + } + } + } + } + } +} + +_PowerManagerImpl::_PowerManagerImpl(void) +{ +} + +_PowerManagerImpl::~_PowerManagerImpl(void) +{ +} + +void +_PowerManagerImpl::Init() +{ + if(_InitPowerManager == false) + { + __powerEventList.Construct(); + _InitPowerManager = true; + } +} + +void +_PowerManagerImpl::Term() +{ + if(_InitPowerManager == true) + { + _InitPowerManager = false; + } +} + +bool +_PowerManagerImpl::IsActive(void) +{ + AppId activeExcutable; + String activeAppId; + result r = E_SUCCESS; + _AppManagerImpl* pAppManagerImpl = _AppManagerImpl::GetInstance(); + + if(pAppManagerImpl == null) + { + _activeApp = false; + } + else + { + r = pAppManagerImpl->GetActiveApp(activeExcutable); + activeExcutable.SubString(0, _APPID_LENGTH, activeAppId); + + if(r == E_SUCCESS) + { + if(activeAppId == _AppInfo::GetAppId()) + { + _activeApp = true; + } + else + { + _activeApp = false; + } + } + else + { + _activeApp = false; + } + } + return _activeApp; +} + +result +_PowerManagerImpl::KeepScreenOnState(bool keepOn, bool dimming) +{ + int ret = -1; + unsigned int state = LCD_DIM; + + if (keepOn == true && IsActive() == true) + { + if (dimming) + { + state = LCD_DIM; + } + else + { + state = LCD_NORMAL; + } + ret = pm_lock_state(state, GOTO_STATE_NOW, 0); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] Failed to lock the screen state"); + _keepScreenOnState = true; + } + else + { + ret = pm_unlock_state(LCD_NORMAL, GOTO_STATE_NOW); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] Failed to unlock the screen state"); + _keepScreenOnState = false; + } + + SysLog(NID_SYS, "change screen power policy: keepOn(%d) and dimming(%d)", keepOn, dimming); + + return E_SUCCESS; +} + +result +_PowerManagerImpl::KeepCpuAwake(bool enable) +{ + int ret = 0; + if (enable) + { + ret = power_lock_state(POWER_STATE_SCREEN_OFF, 0); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] Failed to lock the power state"); + _keepCpuAwake = true; + } + else + { + if(_deviceCpuPowerOn == false) + { + ret = power_unlock_state(POWER_STATE_SCREEN_OFF); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] Failed to unlock the power state"); + } + _keepCpuAwake = false; + } + + SysLog(NID_SYS, "change cpu power policy: keepAwake(%s)", enable ? "true" : "false"); + return E_SUCCESS; +} + +result +_PowerManagerImpl::InitBatteryEvent(void) +{ + int ret = 0; + ret = device_battery_warning_set_cb(DeviceBatteryWarnCallback, null); + + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set the battery event"); + + return E_SUCCESS; +} + +result +_PowerManagerImpl::OnForeground(void) +{ + return E_SUCCESS; +} + +result +_PowerManagerImpl::OnBackground(void) +{ + return E_SUCCESS; +} + +result +_PowerManagerImpl::RestoreScreenBrightness(void) +{ + result r = E_SUCCESS; + + ArrayList requestMessage; + ArrayList responseMessage; + + SysTryReturn(NID_SYS, IsActive() == true, E_SUCCESS, r, "It is not active app."); + + unique_ptr<_IpcClient> pIpcClient (new (std::nothrow) _IpcClient()); + SysTryReturn(NID_SYS, pIpcClient != null, E_OUT_OF_MEMORY, r, "It is failed to create IPC instance."); + + r = pIpcClient->Construct(_COMMUNICATION_DISPATCHER_IPC_ID); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] Fail to create IpcClient", GetErrorMessage(r)); + + requestMessage.Construct(); + responseMessage.Construct(); + + String serviceId = _SYSTEM_SERVICE_ID; + String commandId = _SYSTEM_COMMAND_RESTORE_BRIGHTNESS; + + requestMessage.Add(serviceId); + requestMessage.Add(commandId); + + unique_ptr pMsg(new (std::nothrow) IoService_Request(requestMessage, &responseMessage)); + SysTryReturnResult(NID_SYS, pMsg != null, E_OUT_OF_MEMORY, "It is failed to create Ipc message"); + + r = pIpcClient->SendRequest(pMsg.get()); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] Fail to ipc message", GetErrorMessage(r)); + + unique_ptr pResult((String*)responseMessage.GetAt(_SYSTEM_RESPONSE_DATA)); + + SysTryReturnResult(NID_SYS, pResult != null, E_SYSTEM, "It is failed to receive Ipc response."); + SysTryReturnResult(NID_SYS, *pResult == _SYSTEM_RESULT_OK, E_SYSTEM, "It is failed to set brightness."); + + return E_SUCCESS; +} + +result +_PowerManagerImpl::SetScreenBrightness(int brightness) +{ + int ret = 0; + int maxBrightness = 0; + int actualBrightness = 0; + result r = E_SUCCESS; + + SysTryReturn(NID_SYS, IsActive() == true, E_SUCCESS, r, "It is not active app."); + SysTryReturnResult(NID_SYS, (brightness > 0 && brightness < 11), E_OUT_OF_RANGE, + "[E_OUT_OF_RANGE] The specified brightness is out of range."); + + SysLog(NID_SYS, "Set brightness (%d)", brightness); + + ret = device_get_max_brightness(0, &maxBrightness); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the device max brightness"); + + actualBrightness = maxBrightness * brightness / _BRIGHTNESS_RESOLUTION; + + ArrayList requestMessage; + ArrayList responseMessage; + + unique_ptr<_IpcClient> pIpcClient (new (std::nothrow) _IpcClient()); + SysTryReturn(NID_SYS, pIpcClient != null, E_OUT_OF_MEMORY, r, "It is failed to create IPC instance."); + + r = pIpcClient->Construct(_COMMUNICATION_DISPATCHER_IPC_ID); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] Fail to create IpcClient", GetErrorMessage(r)); + + requestMessage.Construct(); + responseMessage.Construct(); + + String serviceId = _SYSTEM_SERVICE_ID; + String commandId = _SYSTEM_COMMAND_CHANGE_BRIGHTNESS; + String brightnessValue; + brightnessValue.Append(actualBrightness); + + requestMessage.Add(serviceId); + requestMessage.Add(commandId); + requestMessage.Add(brightnessValue); + + unique_ptr pMsg(new (std::nothrow) IoService_Request(requestMessage, &responseMessage)); + SysTryReturnResult(NID_SYS, pMsg != null, E_OUT_OF_MEMORY, "It is failed to create Ipc message"); + + r = pIpcClient->SendRequest(pMsg.get()); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] Fail to ipc message", GetErrorMessage(r)); + + unique_ptr pResult((String*)responseMessage.GetAt(_SYSTEM_RESPONSE_DATA)); + + SysTryReturnResult(NID_SYS, pResult != null, E_SYSTEM, "It is failed to receive Ipc response."); + SysTryReturnResult(NID_SYS, *pResult == _SYSTEM_RESULT_OK, E_SYSTEM, "It is failed to set brightness."); + + return E_SUCCESS; +} + +int +_PowerManagerImpl::GetScreenBrightness(void) +{ + int ret = 0; + int brightness = -1; + int maxBrightness = -1; + + ClearLastResult(); + + ret = device_get_brightness(0, &brightness); + if (ret != 0) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to get the device brightness"); + SetLastResult(E_SYSTEM); + return _DEACTIVATED_BRIGHTNESS_CONTROL; + } + + if (brightness == 0) + { + brightness = 1; + } + + SysLog(NID_SYS, "System Brightness is %d", brightness); + ret = device_get_max_brightness(0, &maxBrightness); + if (ret != 0) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to get the device max brightness"); + SetLastResult(E_SYSTEM); + return _DEACTIVATED_BRIGHTNESS_CONTROL; + } + return ceil(((_BRIGHTNESS_RESOLUTION / (float) maxBrightness)) * brightness); +} + +bool +_PowerManagerImpl::IsScreenOn(void) +{ + power_state_e powerState = power_get_state(); + + if (powerState == POWER_STATE_SCREEN_OFF) + { + return false; + } + else + { + return true; + } +} + +result +_PowerManagerImpl::TurnScreenOn(void) +{ + result r = E_SUCCESS; + int ret = power_wakeup(true); + + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unlock the normal screen state"); + + return r; +} + +result +_PowerManagerImpl::TurnScreenOff(void) +{ + result r = E_SUCCESS; + int ret = pm_change_state(LCD_OFF); + + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unlock the screen off screen state"); + + return r; +} + +void +_PowerManagerImpl::SetScreenEventListener(IScreenEventListener& listener) +{ + int ret = 0; + + if(pIScreenEventListener == null) + { + ret = power_set_changed_cb(PowerChangedCallback, null); + + if (ret == 0) + { + pIScreenEventListener = &listener; + } + } + else + { + pIScreenEventListener = &listener; + } + +} + +void +_PowerManagerImpl::SetChargingEventListener(IChargingEventListener& listener) +{ + int ret = 0; + + if(pIChargingEventListener == null) + { + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_BATTERY_IS_CHARGING, RuntimeInfoChangedCallback, null); + if (ret != 0) + { + SysLog(NID_SYS, "Failed to register battery charging event"); + } + } + pIChargingEventListener = &listener; +} + +result +_PowerManagerImpl::SetBatteryEventListener(IBatteryEventListener* pListener) +{ + int ret = 0; + + if (pListener != null) + { + + if(pIBatteryEventListener == null) + { + ret = device_battery_set_cb(DeviceBatteryCallback, null); + if (ret != 0) + { + SysLog(NID_SYS, "Failed to register battery event"); + } + } + pIBatteryEventListener = pListener; + } + else + { + pIBatteryEventListener = null; + ret = device_battery_unset_cb(); + if (ret != 0) + { + SysLog(NID_SYS, "Failed to unregister battery event"); + } + + } + return E_SUCCESS; +} + +result +_PowerManagerImpl::PowerControl(int deviceId, int level) +{ + int ret = 0; + if(deviceId == _DEVICE_CPU) + { + if(level == _DEVICE_POWER_LEVEL_ON) + { + ret = power_lock_state(POWER_STATE_SCREEN_OFF, 0); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] Failed to lock the power state"); + _deviceCpuPowerOn = true; + + return E_SUCCESS; + } + else if(level == _DEVICE_POWER_LEVEL_OFF) + { + if(_keepScreenOnState == false) + { + ret = power_unlock_state(POWER_STATE_SCREEN_OFF); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] Failed to unlock the power state"); + } + _deviceCpuPowerOn = false; + return E_SUCCESS; + } + } + return E_SYSTEM; +} + +int +_PowerManagerImpl::GetCurrentBatteryLevelInPercentage(void) +{ + int ret = 0; + int batteryLevel = 0; + + ret = device_battery_get_percent(&batteryLevel); + if(ret != 0) + { + SetLastResult(E_SYSTEM); + } + + return batteryLevel; +} + +BatteryLevel +_PowerManagerImpl::GetCurrentBatteryLevel(void) +{ + int ret = 0; + int batteryLevel = 0; + BatteryLevel level = BATTERY_FULL; + device_battery_warn_e batteryStatus = DEVICE_BATTERY_WARN_EMPTY; + + ret = device_battery_get_warning_status(&batteryStatus); + if(ret != 0) + { + SetLastResult(E_SYSTEM); + return level; + } + + switch (batteryStatus) + { + case DEVICE_BATTERY_WARN_FULL: + level = BATTERY_LEVEL_FULL; + break; + case DEVICE_BATTERY_WARN_NORMAL: + level = BATTERY_LEVEL_HIGH; + break; + case DEVICE_BATTERY_WARN_LOW: + level = BATTERY_LEVEL_LOW; + break; + case DEVICE_BATTERY_WARN_CRITICAL: + level = BATTERY_LEVEL_CRITICAL; + break; + case DEVICE_BATTERY_WARN_EMPTY: + level = BATTERY_LEVEL_EMPTY; + break; + default: + SysLogException(NID_SYS, E_SYSTEM, "There is a system error occured."); + SetLastResult(E_SYSTEM); + return level; + } + SetLastResult(E_SUCCESS); + return level; +} + +bool +_PowerManagerImpl::IsCharging(void) +{ + bool chargeState = false; + int ret = 0; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_BATTERY_IS_CHARGING, &chargeState); + if(ret != 0) + { + SetLastResult(E_SYSTEM); + return chargeState; + } + + return chargeState; +} + +result +_PowerManagerImpl::Add_IPowerManagerEventListener(_IPowerManagerEventListener* listener) +{ + _PowerManagerImpl::Init(); + __powerEventList.Add(listener); + return E_SUCCESS; +} + +result +_PowerManagerImpl::Remove_IPowerManagerEventListener(_IPowerManagerEventListener* listener) +{ + _PowerManagerImpl::Init(); + __powerEventList.Remove(listener); + return E_SUCCESS; +} + +_PowerManagerImpl* +_PowerManagerImpl::GetInstance(PowerManager& powerManager) +{ + return powerManager.__pPowerManagerImpl; +} + +const _PowerManagerImpl* +_PowerManagerImpl::GetInstance(const PowerManager& powerManager) +{ + return powerManager.__pPowerManagerImpl; +} +} } //Tizen::System diff --git a/src/system/FSys_RuntimeInfoImpl.cpp b/src/system/FSys_RuntimeInfoImpl.cpp new file mode 100644 index 0000000..68f2441 --- /dev/null +++ b/src/system/FSys_RuntimeInfoImpl.cpp @@ -0,0 +1,748 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSysRuntimeInfo.cpp + * @brief This is the implementation file for _RuntimeInfoImpl class. + * + * + * This file contains the implementation of _RuntimeInfoImpl class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::App; +using namespace Tizen::Base; +using namespace Tizen::Base::Runtime; + +using namespace std; + +namespace Tizen { namespace System +{ + +static const wchar_t* _ALLOCATED_MEMORY = L"AllocatedMemory"; +static const wchar_t* _MEMORY_ALLOCATED = L"http://tizen.org/runtime/memory.allocated"; + +static const wchar_t* _AVAILABLE_EXTERNAL_STORAGE = L"AvailableExternalStorage"; +static const wchar_t* _STORAGE_AVAILABLE_EXTERNAL = L"http://tizen.org/runtime/storage.available.external"; + +static const wchar_t* _AVAILABLE_INTERNAL_STORAGE = L"AvailableInternalStorage"; +static const wchar_t* _STORAGE_AVAILABLE_INTERNAL = L"http://tizen.org/runtime/storage.available.internal"; + +static const wchar_t* _AVAILABLE_MEDIA_STORAGE = L"AvailableMediaStorage"; +static const wchar_t* _STORAGE_AVAILABLE_INTERNAL_MEDIA = L"http://tizen.org/runtime/storage.available.internal.media"; + +static const wchar_t* _BATTERY_LEVEL = L"BatteryLevel"; +static const wchar_t* _CHARGING = L"IsCharging"; + +static const wchar_t* _CPU_CORE_ALL_USAGE = L"http://tizen.org/runtime/cpu.core.all.usage"; + +static const wchar_t* _MAX_ALLOCATABLE_MEMORY = L"MaxAllocatableMemory"; +static const wchar_t* _AVAILABLE_VIDEO_MEMORY = L"AvailableVideoMemory"; +static const wchar_t* _ALLOCATED_VIDEO_MEMORY = L"AllocatedVideoMemory"; +static const wchar_t* _AVAILABLE_MEMORY = L"AvailableMemory"; +static const wchar_t* _MEMORY_AVAILABLE = L"http://tizen.org/runtime/memory.available"; +static const wchar_t* _MEMORY_AVAILABLE_VIDEO = L"http://tizen.org/runtime/memory.available.video"; +static const wchar_t* _MEMORY_ALLOCATED_VIDEO = L"http://tizen.org/runtime/memory.allocated.video"; + +static const wchar_t* _STORAGE_ALLOCATED_INTERNAL_APPLICATION = L"http://tizen.org/runtime/storage.allocated.internal.application"; +static const wchar_t* _STORAGE_ALLOCATED_INTERNAL_AUDIO = L"http://tizen.org/runtime/storage.allocated.internal.audio"; +static const wchar_t* _STORAGE_ALLOCATED_INTERNAL_VIDEO = L"http://tizen.org/runtime/storage.allocated.internal.video"; +static const wchar_t* _STORAGE_ALLOCATED_INTERNAL_IMAGE = L"http://tizen.org/runtime/storage.allocated.internal.image"; +static const wchar_t* _STORAGE_ALLOCATED_INTERNAL_DOWNLOAD = L"http://tizen.org/runtime/storage.allocated.internal.download"; +static const wchar_t* _STORAGE_ALLOCATED_EXTERNAL_APPLICATION = L"http://tizen.org/runtime/storage.allocated.external.application"; +static const wchar_t* _STORAGE_ALLOCATED_EXTERNAL_AUDIO = L"http://tizen.org/runtime/storage.allocated.external.audio"; +static const wchar_t* _STORAGE_ALLOCATED_EXTERNAL_VIDEO = L"http://tizen.org/runtime/storage.allocated.external.video"; +static const wchar_t* _STORAGE_ALLOCATED_EXTERNAL_IMAGE = L"http://tizen.org/runtime/storage.allocated.external.image"; +static const wchar_t* _STORAGE_ALLOCATED_EXTERNAL_DOWNLOAD = L"http://tizen.org/runtime/storage.allocated.external.download"; + +static const int _RUNTIME_INFO_EVENT_TYPE_INT = 101; +static const int _RUNTIME_INFO_EVENT_TYPE_LONGLONG = 102; + + +static const char* const _PROC_SYSTEM_MEMORY_INFO = "/proc/meminfo"; +static const char* const _PROC_PROCESS_MEMORY_INFO = "/proc/self/status"; +static const char* const _PROC_STAT = "/proc/stat"; + +static const char* const _PROC_KEY_SYSTEM_MEMORY_TOTAL = "MemTotal"; +static const char* const _PROC_KEY_SYSTEM_MEMORY_FREE = "MemFree"; +static const char* const _PROC_KEY_PROCESS_MEMORY = "VmSize"; + +static const char* const _ROOT_PATH = "/"; +static const char* const _STORAGE_PATH = "/opt/storage/sdcard"; +static const char* const _MEDIA_PATH = "/opt/usr/media"; +static const char* const _INTERNAL_PATH = "/opt"; + +static const int _MAX_BUFFER_LENGTH = 1024; + +static const int _CPU_USAGE_EVALUATION_INTERVAL = 1000000; //1 sec + +typedef struct { + char cpu[20]; + unsigned long long user; + unsigned long long system; + unsigned long long nice; + unsigned long long idle; + unsigned long long wait; + unsigned long long hi; + unsigned long long si; + unsigned long long zero; +} procstat_t; + +bool read_proc_stat(procstat_t *p) +{ + FILE *fp = null; + int ret = 0; + + fp = fopen(_PROC_STAT, "r"); + if(fp == null) + { + return false; + } + + ret = fscanf(fp, "%s %llu %llu %llu %llu %llu %llu %llu %llu", + p->cpu, + &p->user, + &p->system, + &p->nice, + &p->idle, + &p->wait, + &p->hi, + &p->si, + &p->zero); + + if(ret < 1) + { + if(fp != null) + { + fclose(fp); + } + return false; + } + + if(fp != null) + { + fclose(fp); + } + + return true; +} + +void diff_proc_stat(procstat_t *a, procstat_t *b, procstat_t *d) +{ + d->user = a->user - b->user; + d->system = a->system - b->system; + d->nice = a->nice - b->nice; + d->idle = a->idle - b->idle; + d->wait = a->wait - b->wait; + d->hi = a->hi - b->hi; + d->si = a->si - b->si; + d->zero = a->zero - b->zero; +} + +class _RuntimeInfoEventArg : public IEventArg +{ +public: + _RuntimeInfoEventArg() + : Type(0) + , intValue(0) + , longLongValue(0) + , errorCode(E_SUCCESS) + , DirectoryPath(null) + , pListener(null) + { + } + + ~_RuntimeInfoEventArg() + { + if(DirectoryPath != null) + { + delete [] DirectoryPath; + } + } + + int Type; + int intValue; + long long longLongValue; + result errorCode; + char* DirectoryPath; + IEventListener* pListener; +}; + +class _RuntimeInfoEvent : public Event +{ +protected: + void FireImpl(IEventListener& listener, const IEventArg& arg) + { + const _RuntimeInfoEventArg* runtimeArg = dynamic_cast (&arg); + + if(runtimeArg == null) + { + SysLogException(NID_SYS, E_SYSTEM, "Argument is null."); + return; + } + + switch(runtimeArg->Type) + { + case _RUNTIME_INFO_EVENT_TYPE_INT: + { + IRuntimeInfoGetIntAsyncResultListener* pIntListener = dynamic_cast(&listener); + + if(pIntListener == runtimeArg->pListener) + { + pIntListener->OnResultReceivedForGetValueAsync(runtimeArg->intValue, runtimeArg->errorCode); + RemoveListener(listener); + delete pIntListener; + } + } + break; + case _RUNTIME_INFO_EVENT_TYPE_LONGLONG: + { + IRuntimeInfoGetLonglongAsyncResultListener* pLonglongListener = dynamic_cast(&listener); + if(pLonglongListener == runtimeArg->pListener) + { + pLonglongListener->OnResultReceivedForGetValueAsync(runtimeArg->longLongValue, runtimeArg->errorCode); + RemoveListener(listener); + delete pLonglongListener; + } + } + break; + } + } +}; + +_RuntimeInfoEvent runtimeInfoEvent; + +_RuntimeInfoImpl::_RuntimeInfoImpl(void) +{ +} + +_RuntimeInfoImpl::~_RuntimeInfoImpl(void) +{ +} + +result +_RuntimeInfoImpl::GetValue(const String& key, String& value) +{ + return E_OBJ_NOT_FOUND; +} + +result +_RuntimeInfoImpl::GetValue(const String& key, int& value) +{ + int total_size = 0; + int free_size =0; + result r = E_OBJ_NOT_FOUND; + + if (key == _BATTERY_LEVEL) + { + return GetBatteryLevel(value); + } + else if (key == _ALLOCATED_MEMORY || key == _ALLOCATED_VIDEO_MEMORY) + { + r = GetFromProc(_PROC_PROCESS_MEMORY_INFO, _PROC_KEY_PROCESS_MEMORY, free_size); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to get memory size."); + value = free_size * 1024; + } + else if (key == _AVAILABLE_MEMORY || key == _AVAILABLE_VIDEO_MEMORY || key == _MAX_ALLOCATABLE_MEMORY || key == _MEMORY_AVAILABLE || key == _MEMORY_AVAILABLE_VIDEO) + { + r = GetFromProc(_PROC_SYSTEM_MEMORY_INFO, _PROC_KEY_SYSTEM_MEMORY_FREE, free_size); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to get memory size."); + value = free_size * 1024; + } + else if (key == _MEMORY_ALLOCATED || key == _MEMORY_ALLOCATED_VIDEO) + { + r = GetFromProc(_PROC_SYSTEM_MEMORY_INFO, _PROC_KEY_SYSTEM_MEMORY_TOTAL, total_size); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to get memory size."); + r = GetFromProc(_PROC_SYSTEM_MEMORY_INFO, _PROC_KEY_SYSTEM_MEMORY_FREE, free_size); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to get memory size."); + value = (total_size - free_size) * 1024; + } + return r; +} + +long long +_RuntimeInfoImpl::GetDirectorySize(const char* path) +{ + if(path == null) + { + return 0; + } + + char command[512] = {0,}; + long long size = 0; + int ret = 0; + + sprintf(command, "du -sk -P %s >> /tmp/size_of_directory.tmp", path); + + system("rm -rf /tmp/size_of_directory.tmp"); + system(command); + + FILE* pFile = null; + pFile = fopen("/tmp/size_of_directory.tmp", "r"); + if(pFile == null) + { + return 0; + } + ret = fscanf(pFile, "%lld", &size); + + if(ret < 1) + { + if(pFile != null) + { + fclose(pFile); + } + + return false; + } + + if(pFile != null) + { + fclose(pFile); + } + system("rm -rf /tmp/size_of_directory.tmp"); + return size; +} + +result +_RuntimeInfoImpl::GetValue(const String& key, long long& value) +{ + + long long total_size = 0; + long long free_size =0; + result r = E_OBJ_NOT_FOUND; + + if (key == _MEMORY_AVAILABLE || key == _MEMORY_AVAILABLE_VIDEO) + { + r = GetFromProcLonglong(_PROC_SYSTEM_MEMORY_INFO, _PROC_KEY_SYSTEM_MEMORY_FREE, free_size); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to get memory size."); + value = free_size * 1024; + } + else if (key == _MEMORY_ALLOCATED || key == _MEMORY_ALLOCATED_VIDEO) + { + r = GetFromProcLonglong(_PROC_SYSTEM_MEMORY_INFO, _PROC_KEY_SYSTEM_MEMORY_TOTAL, total_size); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to get memory size."); + r = GetFromProcLonglong(_PROC_SYSTEM_MEMORY_INFO, _PROC_KEY_SYSTEM_MEMORY_FREE, free_size); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to get memory size."); + value = (total_size - free_size) * 1024; + } + else if (key == _AVAILABLE_INTERNAL_STORAGE) + { + return GetAvailableInternalStorage(value); + } + else if (key == _AVAILABLE_EXTERNAL_STORAGE) + { + return GetAvailableExternalStorage(value); + } + else if (key == _AVAILABLE_MEDIA_STORAGE) + { + return GetAvailableMediaStorage(value); + } + else if(key == _STORAGE_AVAILABLE_INTERNAL) + { + return GetAvailableInternalStorage(value); + } + else if(key == _STORAGE_AVAILABLE_EXTERNAL) + { + return GetAvailableExternalStorage(value); + } + else if(key == _STORAGE_AVAILABLE_INTERNAL_MEDIA) + { + return GetAvailableMediaStorage(value); + } + return r; +} + +result +_RuntimeInfoImpl::GetValue(const String& key, double& value) +{ + return E_OBJ_NOT_FOUND; +} + +result +_RuntimeInfoImpl::GetValue(const String& key, bool& value) +{ + if (key == _CHARGING) + { + return IsChargingMode(value); + } + else + { + return E_OBJ_NOT_FOUND; + } +} + +result +_RuntimeInfoImpl::GetValue(const String& key, UuId& value) +{ + return E_OBJ_NOT_FOUND; +} + +result +_RuntimeInfoImpl::GetBatteryLevel(int& value) +{ + int batteryValue = -1; + batteryValue = device_get_battery_pct(); + SysTryReturnResult(NID_SYS, !(batteryValue < 0 || value > 100), E_SYSTEM, "[E_SYSTEM] device_get_battery_pct return %d", batteryValue); + value = batteryValue; + + return E_SUCCESS; +} + +result +_RuntimeInfoImpl::IsChargingMode(bool& value) +{ + bool chargeState = false; + int ret = 0; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_BATTERY_IS_CHARGING, &chargeState); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "[E_SYSTEM] runtime_info_get_value_bool returns %d.", ret); + value = chargeState; + return E_SUCCESS; + +} + +result +_RuntimeInfoImpl::GetAvailableInternalStorage(long long& value) +{ + long long temp = 0; + long long total = 0; + result r = E_SUCCESS; + + r = GetCapacity(_ROOT_PATH, total, temp); + SysTryReturn(NID_SYS, !IsFailed(r), E_SYSTEM, r, "[E_SYSTEM] system error has occurred. "); + + value += temp; + + r = GetCapacity(_INTERNAL_PATH, total, temp); + SysTryReturn(NID_SYS, !IsFailed(r), E_SYSTEM, r, "[E_SYSTEM] system error has occurred. "); + + value += temp; + + return E_SUCCESS; +} +result +_RuntimeInfoImpl::GetAvailableExternalStorage(long long& value) +{ + int sdCardStatus = 0; + int ret = -1; + long long total = 0; + + ret = vconf_get_int(VCONFKEY_SYSMAN_MMC_STATUS, &sdCardStatus); + SysTryReturn(NID_SYS, !(ret < 0), E_SYSTEM, E_SYSTEM, "[E_SYSTEM] vconf_get_int VCONFKEY_SYSMAN_MMC_STATUS failed"); + + if(sdCardStatus == 0) + { + value = 0; + return E_SUCCESS; + } + + return GetCapacity(_STORAGE_PATH, total, value); +} + +result +_RuntimeInfoImpl::GetAvailableMediaStorage(long long& value) +{ + long long total = 0; + return GetCapacity(_MEDIA_PATH, total, value); +} + +result +_RuntimeInfoImpl::GetCapacity(const char* path, long long& totalSize, long long& availableSize) +{ + struct statfs fs; + if (statfs(path, &fs) < 0) + { + SysLogException(NID_SYS, E_SYSTEM, "[E_SYSTEM] statfs() failed"); + return E_SYSTEM; + } + + totalSize = static_cast< long long >(fs.f_bsize) * static_cast< long long >(fs.f_blocks); + availableSize = static_cast< long long >(fs.f_bsize) * static_cast< long long >(fs.f_bavail); + + return E_SUCCESS; +} + +result +_RuntimeInfoImpl::GetFromProcLonglong(const char* path, const char* key, long long& value) +{ + FILE* pStream = null; + char line[_MAX_BUFFER_LENGTH] = {0, }; + char fieldName[_MAX_BUFFER_LENGTH] = {0, }; + long long keyValue = 0; + pStream = fopen(path, "r"); + SysTryReturnResult(NID_SYS, pStream != null, E_SYSTEM, "%s open is failed.", path); + + while (fgets(line, sizeof(line), pStream)) + { + if (sscanf(line, "%s %lld %*s", fieldName, &keyValue) == 2) + { + if (strncmp(fieldName, key, static_cast< int >(strlen(key))) == 0) + { + value = keyValue; + fclose(pStream); + return E_SUCCESS; + } + } + } + fclose(pStream); + + SysLogException(NID_SYS, E_OBJ_NOT_FOUND, "it can't find %s field", key); + return E_OBJ_NOT_FOUND; +} + +result +_RuntimeInfoImpl::GetFromProc(const char* path, const char* key, int& value) +{ + FILE* pStream = null; + char line[_MAX_BUFFER_LENGTH] = {0, }; + char fieldName[_MAX_BUFFER_LENGTH] = {0, }; + int keyValue = 0; + pStream = fopen(path, "r"); + SysTryReturnResult(NID_SYS, pStream != null, E_SYSTEM, "%s open is failed.", path); + + while (fgets(line, sizeof(line), pStream)) + { + if (sscanf(line, "%s %d %*s", fieldName, &keyValue) == 2) + { + if (strncmp(fieldName, key, static_cast< int >(strlen(key))) == 0) + { + value = keyValue; + fclose(pStream); + return E_SUCCESS; + } + } + } + fclose(pStream); + + SysLogException(NID_SYS, E_OBJ_NOT_FOUND, "it can't find %s field", key); + return E_OBJ_NOT_FOUND; +} + +void* +_RuntimeInfoImpl::GetDirectorySizeAsync(void* data) +{ + if(data == null) + { + return null; + } + _RuntimeInfoEventArg* pEventArg = (_RuntimeInfoEventArg*)data; + long long size = _RuntimeInfoImpl::GetDirectorySize(pEventArg->DirectoryPath); + + if(pEventArg == null) + { + SysLogException(NID_SYS, E_OUT_OF_MEMORY, "It is failed to create instance of _RuntimeInfoEventArg"); + return null; + } + pEventArg->Type = _RUNTIME_INFO_EVENT_TYPE_LONGLONG; + pEventArg->longLongValue = size; + SysLog(NID_SYS, "Fire event %x %s %lld", pEventArg, pEventArg->DirectoryPath, size); + runtimeInfoEvent.Fire(*pEventArg); + + return null; +} + +void* +_RuntimeInfoImpl::GetCpuUsageAsync(void* data) +{ + result r = E_SUCCESS; + + int value = 0; + procstat_t first, second, diffrence; + unsigned long long total, usage; + + if(read_proc_stat(&first) != false) + { + usleep(_CPU_USAGE_EVALUATION_INTERVAL); + if(read_proc_stat(&second) != false) + { + diff_proc_stat(&second, &first, &diffrence); + total = diffrence.user + diffrence.system + + diffrence.nice + diffrence.idle + + diffrence.wait + diffrence.hi + + diffrence.si; + usage = 10000 - (diffrence.idle * 10000 / total); + value = usage/100; + r = E_SUCCESS; + } + else + { + r = E_SYSTEM; + } + } + else + { + r = E_SYSTEM; + } + + _RuntimeInfoEventArg* pEventArg = (_RuntimeInfoEventArg*) data; + if(pEventArg == null) + { + SysLogException(NID_SYS, E_OUT_OF_MEMORY, "It is failed to create instance of _RuntimeInfoEventArg"); + return null; + } + pEventArg->errorCode = r; + pEventArg->Type = _RUNTIME_INFO_EVENT_TYPE_INT; + pEventArg->intValue = value; + + runtimeInfoEvent.Fire(*pEventArg); + + return null; +} + +result +_RuntimeInfoImpl::GetValueAsync(const String& key, IRuntimeInfoGetIntAsyncResultListener* listener) +{ + result r = E_SUCCESS; + + SysTryReturnResult(NID_SYS, listener != null, E_INVALID_ARG, "listener is null"); + + if (key == _CPU_CORE_ALL_USAGE) + { + if(listener != null) + { + SysLog(NID_SYS, "%x", listener); + runtimeInfoEvent.AddListener(*listener, false); + } + + int thr_id = 0; + pthread_t p_thread; + _RuntimeInfoEventArg* pEventArg = new (std::nothrow) _RuntimeInfoEventArg(); + pEventArg->pListener = listener; + thr_id = pthread_create(&p_thread, null, GetCpuUsageAsync, pEventArg); + pthread_detach(p_thread); + } + else + { + SysLogException(NID_SYS, E_INVALID_ARG, "Required key[%ls] is not valid", key.GetPointer()); + r = E_INVALID_ARG; + } + return r; +} + +result +_RuntimeInfoImpl::GetValueAsync(const String& key, IRuntimeInfoGetLonglongAsyncResultListener* listener) +{ + int thr_id = 0; + pthread_t p_thread; + result r = E_SUCCESS; + char* directoryPath = null; + + SysTryReturnResult(NID_SYS, listener != null, E_INVALID_ARG, "listener is null"); + + if(key == _STORAGE_ALLOCATED_INTERNAL_APPLICATION) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_APPLICATIONS)); + } + else if (key == _STORAGE_ALLOCATED_INTERNAL_AUDIO) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_SOUNDS)); + } + else if (key == _STORAGE_ALLOCATED_INTERNAL_VIDEO) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_VIDEOS)); + } + else if (key == _STORAGE_ALLOCATED_INTERNAL_IMAGE) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_IMAGES)); + } + else if (key == _STORAGE_ALLOCATED_INTERNAL_DOWNLOAD) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_DOWNLOADS)); + } + else if (key == _STORAGE_ALLOCATED_EXTERNAL_APPLICATION) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_EXTERNAL_APPLICATIONS)); + } + else if (key == _STORAGE_ALLOCATED_EXTERNAL_AUDIO) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_EXTERNAL_SOUNDS)); + } + else if (key == _STORAGE_ALLOCATED_EXTERNAL_VIDEO) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_EXTERNAL_VIDEOS)); + } + else if (key == _STORAGE_ALLOCATED_EXTERNAL_IMAGE) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_EXTERNAL_IMAGES)); + } + + else if (key == _STORAGE_ALLOCATED_EXTERNAL_DOWNLOAD) + { + directoryPath = _StringConverter::CopyToCharArrayN(_EnvironmentImpl::GetPredefinedPath(PREDEFINED_DIRECTORY_EXTERNAL_DOWNLOADS)); + } + else + { + SysLogException(NID_SYS, E_INVALID_ARG, "Required key[%ls] is not valid", key.GetPointer()); + r = E_INVALID_ARG; + } + + SysLog(NID_SYS, "%s", GetErrorMessage(r)); + SysLog(NID_SYS, "%s", directoryPath); + if(r == E_SUCCESS) + { + if(listener != null) + { + SysLog(NID_SYS, "test %x", listener); + runtimeInfoEvent.AddListener(*listener); + } + + _RuntimeInfoEventArg* pEventArg = new (std::nothrow) _RuntimeInfoEventArg(); + pEventArg->pListener = listener; + pEventArg->DirectoryPath = directoryPath; + + thr_id = pthread_create(&p_thread, null, GetDirectorySizeAsync, pEventArg); + SysLog(NID_SYS, "%d", thr_id); + pthread_detach(p_thread); + } + + return r; +} + +_RuntimeInfoImpl* +_RuntimeInfoImpl::GetInstance(RuntimeInfo& runtimeinfo) +{ + return runtimeinfo.__pRuntimeInfoImpl; +} + +const _RuntimeInfoImpl* +_RuntimeInfoImpl::GetInstance(const RuntimeInfo& runtimeinfo) +{ + return runtimeinfo.__pRuntimeInfoImpl; +} + +} } //Tizen::System + diff --git a/src/system/FSys_SettingIcu.cpp b/src/system/FSys_SettingIcu.cpp new file mode 100644 index 0000000..bea4545 --- /dev/null +++ b/src/system/FSys_SettingIcu.cpp @@ -0,0 +1,118 @@ + +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SettingIcu.cpp + * @brief This is the implementation file for _SettingIcu class. + */ + +#include +#include +#include + +#include +#include +#include "FSys_SettingIcu.h" + +namespace Tizen { namespace System +{ + +static const int _MAX_COUNTRY_LENTH = 2; +static const int _LANGUAGE_START_INDEX = 0; +static const int _MAX_LANGUAGE_LENTH = 2; + +_SettingIcu::_SettingIcu() +{ +} + +_SettingIcu::~_SettingIcu() +{ +} + +char* +_SettingIcu::GetIcuPatternN(const char* pLocale, UChar* pCustomSkeleton) +{ + UErrorCode status = U_ZERO_ERROR; + UDateTimePatternGenerator* pGenerator = null; + UChar bestPattern[64] = {0,}; + + if(pLocale == null || pCustomSkeleton == null) + { + return null; + } + + char* pBestPatternString = null; + int32_t bestPatternCapacity = 0; + int32_t bestPatternLength = 0; + + pGenerator = udatpg_open(pLocale, &status); + + if (U_FAILURE(status) == true) + { + return null; + } + + status = U_ZERO_ERROR; + + bestPatternCapacity = (int32_t)(sizeof(bestPattern)/sizeof((bestPattern)[0])); + bestPatternLength = udatpg_getBestPattern(pGenerator, pCustomSkeleton, u_strlen(pCustomSkeleton), bestPattern, bestPatternCapacity, &status); + if (U_FAILURE(status) == true) + { + return null; + } + + status = U_ZERO_ERROR; + pBestPatternString = (char*)malloc(128); + if (pBestPatternString == null) + { + return null; + } + memset(pBestPatternString, 0, 128); + u_austrncpy(pBestPatternString, bestPattern, 128); + udatpg_close(pGenerator); + SysLog(NID_SYS, "Format is [%s] \n", pBestPatternString); + return pBestPatternString; +} + +char* +_SettingIcu::GetDateTimeFormatN(const char* pIcuFormat) +{ + char* pFormatString = null; + char* pLangset = null; + char* pDateTimeFormat = null; + + if (pIcuFormat == null) + { + return null; + } + + UChar customSkeleton[256] = {0, }; + int res = 0; + const char* pLocaleDefault = uloc_getDefault(); + + res = runtime_info_get_value_string(RUNTIME_INFO_KEY_REGION, &pLangset); + pDateTimeFormat = const_cast< char* > (pLocaleDefault); + + u_uastrncpy(customSkeleton, pIcuFormat, sizeof(customSkeleton)); + pFormatString = GetIcuPatternN(pDateTimeFormat, customSkeleton); + + free(pLangset); + return pFormatString; +} + +} } // Tizen::System diff --git a/src/system/FSys_SettingIcu.h b/src/system/FSys_SettingIcu.h new file mode 100644 index 0000000..b414b76 --- /dev/null +++ b/src/system/FSys_SettingIcu.h @@ -0,0 +1,40 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SettingIcu.cpp + * @brief This is the header file for _SettingIcu class. + */ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace System +{ + +class _SettingIcu +{ +public: + _SettingIcu(); + virtual ~_SettingIcu(); + char* GetIcuPatternN(const char* pLocale, UChar* pCustomSkeleton); + char* GetDateTimeFormatN(const char* pIcuFormat); +}; +} } // Tizen::System diff --git a/src/system/FSys_SettingInfoImpl.cpp b/src/system/FSys_SettingInfoImpl.cpp new file mode 100644 index 0000000..6d5418f --- /dev/null +++ b/src/system/FSys_SettingInfoImpl.cpp @@ -0,0 +1,291 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SettingInfoImpl.cpp + * @brief This is the implementation file for _SysSettingInfoImpl class. + */ + +#include +#include +#include +#include + +#include +#include +#include "FSys_SettingManager.h" + +using namespace Tizen::App; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; + +namespace Tizen { namespace System +{ +//IDs for IPC +static const int _SYSTEM_RESPONSE_DATA = 2; + +//Reserved key +static const wchar_t* _SETTING_SCREEN_WALLPAPER = L"http://tizen.org/setting/screen.wallpaper"; +static const wchar_t* _SETTING_SYSTEM_SOUND_VOLUME = L"SystemSoundVolume"; +static const wchar_t* _SETTING_SOUND_SYSTEM_VOLUME= L"http://tizen.org/setting/sound.system.volume"; +static const wchar_t* _SETTING_MEDIA_SOUND_VOLUME = L"MediaSoundVolume"; +static const wchar_t* _SETTING_SOUND_MEDIA_VOLUME = L"http://tizen.org/setting/sound.media.volume"; +static const wchar_t* _SETTING_RINGTONE_SOUND_VOLUME = L"RingtoneSoundVolume"; +static const wchar_t* _SETTING_SOUND_RINGTONE = L"http://tizen.org/setting/sound.ringtone"; +static const wchar_t* _SETTING_SOUND_RINGTONE_VOLUME = L"http://tizen.org/setting/sound.ringtone.volume"; +static const wchar_t* _SETTING_NOTIFICATION_SOUND_VOLUME = L"NotificationSoundVolume"; +static const wchar_t* _SETTING_SOUND_NOTIFICATION_VOLUME = L"http://tizen.org/setting/sound.notification.volume"; + +static _SettingManager* pSettingManager = null; + +void +_SettingInfoImpl::InitSettingManager(void) +{ + if(pSettingManager == null) + { + pSettingManager = _SettingManager::GetInstance(); + } +} +result +_SettingInfoImpl::GetValue(const Tizen::Base::String& key, Tizen::Base::String& value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->GetValue(key, value); +} + +result +_SettingInfoImpl::GetValue(const Tizen::Base::String& key, int& value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->GetValue(key, value); +} + +result +_SettingInfoImpl::GetValue(const Tizen::Base::String& key, long long& value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->GetValue(key, value); +} + +result +_SettingInfoImpl::GetValue(const Tizen::Base::String& key, double& value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->GetValue(key, value); +} + +result +_SettingInfoImpl::GetValue(const Tizen::Base::String& key, bool& value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->GetValue(key, value); +} + +result +_SettingInfoImpl::GetValue(const Tizen::Base::String& key, Tizen::Base::UuId& value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->GetValue(key, value); +} + +result +_SettingInfoImpl::SetWallpaper(const Tizen::Base::String& filePath) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetValue(_SETTING_SCREEN_WALLPAPER, filePath); +} + +result +_SettingInfoImpl::GetValueForPrivilegedKey(const String& key, bool& value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->GetValueForPrivilegedKey(key, value); +} + +result +_SettingInfoImpl::SetValue(const String& key, bool value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetValue(key, value); +} + +result +_SettingInfoImpl::SetValue(const String& key, int value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetValue(key, value); +} + + +result +_SettingInfoImpl::SetValue(const String& key, String value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetValue(key, value); +} + +result +_SettingInfoImpl::SetValueForPrivilegedKey(const String& key, bool value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetValueForPrivilegedKey(key, value); +} + +result +_SettingInfoImpl::SetValueForPrivilegedKey(const String& key, String value) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetValueForPrivilegedKey(key, value); +} + +bool +_SettingInfoImpl::HasKey(const String& key) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->HasKey(key); +} +result +_SettingInfoImpl::ResetToFactoryDefault(void) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->ResetToFactoryDefault(); +} + +result +_SettingInfoImpl::SetRingtone(const Tizen::Base::String& filePath) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetValue(_SETTING_SOUND_RINGTONE, filePath); +} + +result +_SettingInfoImpl::SetVolume(const Tizen::Base::String& soundCategory, int level) +{ + result r = E_SUCCESS; + String key; + + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + + if (soundCategory == _SETTING_SYSTEM_SOUND_VOLUME) + { + key = _SETTING_SOUND_SYSTEM_VOLUME; + } + else if (soundCategory == _SETTING_MEDIA_SOUND_VOLUME) + { + key = _SETTING_SOUND_MEDIA_VOLUME; + } + else if (soundCategory == _SETTING_RINGTONE_SOUND_VOLUME) + { + key = _SETTING_SOUND_RINGTONE_VOLUME; + } + else if (soundCategory == _SETTING_NOTIFICATION_SOUND_VOLUME) + { + key = _SETTING_SOUND_NOTIFICATION_VOLUME; + } + else + { + key = soundCategory; + } + + r = pSettingManager->SetValue(key, level); + + if (r == E_OBJ_NOT_FOUND) + { + r = E_INVALID_ARG; + } + return r; +} + +result +_SettingInfoImpl::AddSettingEventListener(ISettingEventListener& listener) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->AddSettingEventListener(listener); +} + +result +_SettingInfoImpl::RemoveSettingEventListener(ISettingEventListener& listener) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->RemoveSettingEventListener(listener); +} + +result +_SettingInfoImpl::AddSettingEventListenerForInternal(ISettingEventListener& listener) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->AddSettingEventListenerForInternal(listener); +} + +result +_SettingInfoImpl::RemoveSettingEventListenerForInternal(ISettingEventListener& listener) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->RemoveSettingEventListenerForInternal(listener); +} + +result +_SettingInfoImpl::SetSettingEventListener(ISettingEventListener* pListener) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetSettingEventListener(pListener); +} + +result +_SettingInfoImpl::SetValueAsyncForPrivilegedKey(const Tizen::Base::String& key, bool value, ISettingInfoSetValueAsyncResultListener* listener) +{ + InitSettingManager(); + SysTryReturnResult(NID_SYS, pSettingManager != null, E_SYSTEM, "It is failed to intialize setting manager"); + return pSettingManager->SetValueAsyncForPrivilegedKey(key, value, listener); +} + +_SettingInfoImpl* +_SettingInfoImpl::GetInstance(SettingInfo& settinginfo) +{ + return settinginfo.__pSettingInfoImpl; +} + +const _SettingInfoImpl* +_SettingInfoImpl::GetInstance(const SettingInfo& settinginfo) +{ + return settinginfo.__pSettingInfoImpl; +} + +} } // Tizen::System diff --git a/src/system/FSys_SettingManager.cpp b/src/system/FSys_SettingManager.cpp new file mode 100644 index 0000000..0296feb --- /dev/null +++ b/src/system/FSys_SettingManager.cpp @@ -0,0 +1,3488 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SettingManager.cpp + * @brief This is the implementation file for _SettingManager class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Tizen::App; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Runtime; +using namespace Tizen::Base::Utility; +using namespace Tizen::Io; +using namespace Tizen::Locales; + +namespace Tizen { namespace System +{ + +//Battery +static const wchar_t* _BATTERY_FORMAT_PERCENTAGE = L"http://tizen.org/setting/battery.format.percentage"; + +static const wchar_t* _ENABLE_MOTION = L"EnableMotion"; + +//Font +static const wchar_t* _FONT_SIZE = L"http://tizen.org/setting/font.size"; +static const wchar_t* _FONT_SIZE_GIANT = L"Giant"; +static const wchar_t* _FONT_SIZE_HUGE = L"Huge"; +static const wchar_t* _FONT_SIZE_LARGE = L"Large"; +static const wchar_t* _FONT_SIZE_MEDIUM = L"Medium"; +static const wchar_t* _FONT_SIZE_SMALL = L"Small"; +static const wchar_t* _FONT_SIZE_GIANT_LOWERCASE = L"giant"; +static const wchar_t* _FONT_SIZE_HUGE_LOWERCASE = L"huge"; +static const wchar_t* _FONT_SIZE_LARGE_LOWERCASE = L"large"; +static const wchar_t* _FONT_SIZE_MEDIUM_LOWERCASE = L"medium"; +static const wchar_t* _FONT_SIZE_SMALL_LOWERCASE = L"small"; +static const int _FONT_SIZE_GIANT_VCONF = 4; +static const int _FONT_SIZE_HUGE_VCONF = 3; +static const int _FONT_SIZE_LARGE_VCONF = 2; +static const int _FONT_SIZE_MEDIUM_VCONF = 1; +static const int _FONT_SIZE_SMALL_VCONF = 0; +static const wchar_t* _FONTSIZE = L"FontSize"; +static const wchar_t* _FONTTYPE = L"FontType"; +static const wchar_t* _FONT_TYPE = L"http://tizen.org/setting/font.type"; +static const wchar_t* _GPS_ENABLED = L"GPSEnabled"; +static const wchar_t* _HOUR_FORMAT_SELECTED = L"24HourFormatSelected"; + +//Locale +//Locale Country +static const wchar_t* _LOCALE_COUNTRY = L"http://tizen.org/setting/locale.country"; +static const wchar_t* _LOCALE_COUNTRY_LATIN_AMERICA = L"419"; +static const wchar_t* _COUNTRY = L"Country"; + +//Locale Format +static const wchar_t* _LOCALE_DATE_FORMAT = L"http://tizen.org/setting/locale.date.format"; +static const wchar_t* _LOCALE_DATETIME_FORMAT = L"http://tizen.org/setting/locale.date_time.format"; +static const wchar_t* _LOCALE_TIME_FORMAT = L"http://tizen.org/setting/locale.time.format"; +static const wchar_t* _LOCALE_TIME_FORMAT_24HOUR = L"http://tizen.org/setting/locale.time.format.24hour"; +static const wchar_t* _DATE_FORMAT = L"DateFormat"; +static const wchar_t* _TIME_FORMAT = L"TimeFormat"; + +//Locale Language +static const wchar_t* _LOCALE_LANGUAGE = L"http://tizen.org/setting/locale.language"; +static const wchar_t* _LANGUAGE = L"Language"; + +//Locale Time +static const wchar_t* _LOCALE_TIMEZONE = L"http://tizen.org/setting/locale.time_zone"; +static const wchar_t* _LOCALE_UPDATE_AUTO= L"http://tizen.org/setting/locale.update.auto"; +static const char* _LOCALE_TIMEZONE_ROOT_PATH = "/usr/share/zoneinfo/"; +static const char* _LOCALE_TIMEZONE_LINK = "/opt/etc/localtime"; +static const int _LOCALE_TIMEZONE_ROOT_PATH_LENGTH = 20; +static const wchar_t* _LOCALE_WEEK_FORMAT_FIRSTDAY = L"http://tizen.org/setting/locale.week.format.firstday"; +static const wchar_t* _LOCALE_WEEK_FORMAT_FIRSTDAY_MONDAY = L"Monday"; +static const wchar_t* _LOCALE_WEEK_FORMAT_FIRSTDAY_SUNDAY = L"Sunday"; +static const int _LOCALE_WEEK_FORMAT_VCONF_SUNDAY = 0; +static const int _LOCALE_WEEK_FORMAT_VCONF_MONDAY = 1; +static const wchar_t* _DATE_TIME_FORMAT = L"DateTimeFormat"; + +static const wchar_t* _LOCALE_DATE = L"http://tizen.org/setting/locale.date"; +static const wchar_t* _LOCALE_TIME = L"http://tizen.org/setting/locale.time"; +static const wchar_t* _LOCALE_DATETIME = L"http://tizen.org/setting/locale.date_time"; + +//Location +static const wchar_t* _LOCATION_GPS = L"http://tizen.org/setting/location.gps"; +static const wchar_t* _LOCATION_GPS_ADVANCED = L"http://tizen.org/setting/location.gps.advanced"; +static const wchar_t* _LOCATION_WPS = L"http://tizen.org/setting/location.wps"; +static const wchar_t* _MEDIA_SOUND_VOLUME = L"MediaSoundVolume"; +static const wchar_t* _WPS_ENABLED = L"WPSEnabled"; + +//Network +static const wchar_t* _NETWORK_FLIGHTMODE = L"http://tizen.org/setting/network.flight_mode"; +static const wchar_t* _FLIGHT_MODE_ENABLED = L"FlightModeEnabled"; + +//Network Telephony +static const wchar_t* _NETWORK_TELEPHONY_MODE = L"http://tizen.org/setting/network.telephony.mode"; +String _tmpNetworkTelephonyMode = L"UMTS"; +static const wchar_t* _NETWORK_TELEPHONY_PACKETSERVICE = L"http://tizen.org/setting/network.telephony.packet_service"; +static const wchar_t* _NETWORK_TELEPHONY_PROVIDER = L"http://tizen.org/setting/network.telephony.provider"; +String _tmpNetworkTelephonyProvider = L"Tizen"; +static const wchar_t* _NETWORK_TELEPHONY_ROAMING = L"http://tizen.org/setting/network.telephony.roaming"; +static const wchar_t* _DATA_ROAMING_ENABLED = L"DataRoamingEnabled"; +static const wchar_t* _SYSTEM_NETWORK_TELEPHONY = L"http://tizen.org/feature/network.telephony"; + +//Network Wifi +static const wchar_t* _NETWORK_WIFI = L"http://tizen.org/setting/network.wifi"; +static const wchar_t* _NETWORK_WIFI_NOTIFICATION = L"http://tizen.org/setting/network.wifi.notification"; +static const wchar_t* _NETWORK_WIFI_TETHERING = L"http://tizen.org/setting/network.wifi.tethering"; +static const wchar_t* _NETWORK_WIFI_TETHERING_HIDE = L"http://tizen.org/setting/network.wifi.tethering.hide"; +static const wchar_t* _NETWORK_WIFI_TETHERING_SECURITY = L"http://tizen.org/setting/network.wifi.tethering.security"; +static const wchar_t* _NETWORK_WIFI_TETHERING_SECURITY_PASSWORD = L"http://tizen.org/setting/network.wifi.tethering.security.password"; +static const wchar_t* _NETWORK_WIFI_DIRECT = L"http://tizen.org/setting/network.wifi.direct"; +static const wchar_t* _SYSTEM_NETWORK_WIFI_DIRECT = L"http://tizen.org/feature/network.wifi.direct"; +static const wchar_t* _SYSTEM_NETWORK_WIFI = L"http://tizen.org/feature/network.wifi"; + +//Network Bluetooth +static const wchar_t* _NETWORK_BLUETOOTH = L"http://tizen.org/setting/network.bluetooth"; +static const wchar_t* _NETWORK_BLUETOOTH_TETHERING = L"http://tizen.org/setting/network.bluetooth.tethering"; +static const wchar_t* _SYSTEM_NETWORK_BLUETOOTH = L"http://tizen.org/feature/network.bluetooth"; + +//Sound +static const wchar_t* _NOTIFICATION_SOUND_VOLUME = L"NotificationSoundVolume"; +static const wchar_t* _PACKET_SERVICE_ALLOWED = L"PacketServiceAllowed"; +static const wchar_t* _RINGTONE = L"Ringtone"; +static const wchar_t* _RINGTONE_SOUND_VOLUME = L"RingtoneSoundVolume"; +static const wchar_t* _SILENT_MODE = L"SilentMode"; +static const wchar_t* _SOUND_MEDIA_VOLUME = L"http://tizen.org/setting/sound.media.volume"; +static const wchar_t* _SOUND_NOTIFICATION_VOLUME = L"http://tizen.org/setting/sound.notification.volume"; +static const wchar_t* _SOUND_RINGTONE = L"http://tizen.org/setting/sound.ringtone"; +static const wchar_t* _SOUND_RINGTONE_VOLUME = L"http://tizen.org/setting/sound.ringtone.volume"; +static const wchar_t* _SOUND_SILENTMODE = L"http://tizen.org/setting/sound.silent_mode"; +static const wchar_t* _SOUND_SYSTEM_VOLUME = L"http://tizen.org/setting/sound.system.volume"; +static const wchar_t* _SOUND_TOUCH = L"http://tizen.org/setting/sound.touch"; +static const wchar_t* _SOUND_LOCK = L"http://tizen.org/setting/sound.lock"; + +//Screen +static const wchar_t* _SCREEN_WALLPAPER = L"http://tizen.org/setting/screen.wallpaper"; +static const wchar_t* _SCREEN_WALLPAPER_LOCK = L"http://tizen.org/setting/screen.wallpaper.lock"; +static const wchar_t* _WALLPAPER = L"Wallpaper"; +static const wchar_t* _SCREEN_BRIGHTNESS = L"http://tizen.org/setting/screen.brightness"; +static const wchar_t* _SCREEN_BRIGHTNESS_AUTO = L"http://tizen.org/setting/screen.brightness.auto"; +static const wchar_t* _SCREEN_BACKLIGHT_TIME = L"http://tizen.org/setting/screen.backlight.time"; +static const wchar_t* _SCREEN_ROTATION_AUTO = L"http://tizen.org/setting/screen.rotation.auto"; +static const wchar_t* _SCREEN_MODE = L"http://tizen.org/setting/screen.mode"; +static const wchar_t* _SCREEN_MODE_DYNAMIC = L"Dynamic"; +static const wchar_t* _SCREEN_MODE_STANDARD = L"Standard"; +static const wchar_t* _SCREEN_MODE_NATURAL = L"Natural"; +static const wchar_t* _SCREEN_MODE_MOVIE = L"Movie"; +static const char* _SCREEN_MODE_VCONFKEY = VCONFKEY_SETAPPL_PREFIX"/screenmode/selected_name"; + +//Directory +static const wchar_t* _STORAGE_DIRECTORY_WAP_DOWNLOAD = L"http://tizen.org/setting/storage.directory.wap.download"; +String _tmpStorageDirectoryWapDownload = L""; +static const wchar_t* _STORAGE_DIRECTORY_BLUETOOTH_DOWNLOAD = L"http://tizen.org/setting/storage.directory.bluetooth.download"; +String _tmpStorageDirectoryBluetoothDownload = L""; +static const wchar_t* _STORAGE_DIRECTORY_CAMERA_RECORD = L"http://tizen.org/setting/storage.directory.camera.record"; +String _tmpStorageDirectoryCameraRecord = L""; +static const wchar_t* _STORAGE_DIRECTORY_VOICE_RECORD = L"http://tizen.org/setting/storage.directory.voice.record"; +String _tmpStorageDirectoryVoiceRecord = L""; +static const wchar_t* _STORAGE_DIRECTORY_RADIO_BROADCAST = L"http://tizen.org/setting/storage.directory.radio.broadcast"; +String _tmpStorageDirectoryRadioBroadcast = L""; +static const wchar_t* _STORAGE_DIRECTORY_VIDEO_BROADCAST = L"http://tizen.org/setting/storage.directory.video.broadcast"; +String _tmpStorageDirectoryVideoBroadcast = L""; +static const wchar_t* _SYSTEM_SOUND_VOLUME = L"SystemSoundVolume"; + +//Device Name +static const wchar_t* _DEVICE_NAME = L"http://tizen.org/setting/device_name"; + +//Vibration +static const wchar_t* _TOUCH_VIBRATION_LEVEL = L"TouchVibrationLevel"; +static const wchar_t* _VIBRATOR = L"http://tizen.org/setting/vibrator"; +static const wchar_t* _VIBRATOR_LEVEL = L"http://tizen.org/setting/vibrator.level"; + +static const wchar_t* _VIBRATOR_LEVEL_NOTIFICATION = L"http://tizen.org/setting/vibrator.level.notification"; + +//USB +static const wchar_t* _USBMODE = L"UsbMode"; +static const wchar_t* _USBMODE_MTP = L"MTP"; +static const wchar_t* _USB_TETHERING = L"http://tizen.org/setting/usb.tethering"; + +//WEB +static const wchar_t* _WEB_APPLICATION_COOKIE_SHARE = L"http://tizen.org/setting/web.application.cookie.share"; +bool _tmpWebApplicationCookieShare = false; + +//Motion UI +static const wchar_t* _MOTION_UI = L"http://tizen.org/setting/motion.ui"; + +//Contact Order +static const wchar_t* _CONTACT_ORDER_FIRSTNAME = L"http://tizen.org/setting/contacts.order.firstname"; +static const int _CONTACT_ORDER_FIRSTNAME_FIRSTLAST = 0; +static const int _CONTACT_ORDER_FIRSTNAME_LASTFIRST = 1; + +//Privileged key +static const wchar_t* _DEVELOPER_USBDEBUGGING = L"http://tizen.org/setting/developer.usb_debugging"; + +static const int _MAX_COUNTRY_LENTH = 2; +static const int _LANGUAGE_START_INDEX = 0; +static const int _MAX_LANGUAGE_LENTH = 2; +static const int _TOUCH_FEEDBACK_RESOLUTION = 20; + +static const int _OSP_USB_DEFAULT_MODE = 0; + +// ICU +static const char* _ICU_DATE_FORMAT = "yMMMMEEEEd"; +static const char* _ICU_TIME_24_FORMAT = "Hms"; +static const char* _ICU_TIME_12_FORMAT = "hms"; + +static const int _DEVELOPER_USBDEBUGGING_ON = 1; +static const int _DEVELOPER_USBDEBUGGING_OFF = 0; + +// wifi direct +static const char* _WIFI_DIRECT_LIBRARY_NAME = "libosp-wifi.so"; +static const char* _BLUETOOTH_LIBRARY_NAME = "libosp-bluetooth.so"; + +static result (*pWifiDirectDeviceImpl_Activate)(void) = null; +static result (*pWifiDirectDeviceImpl_Deactivate)(void) = null; +static bool (*pWifiDirectDeviceImpl_IsActivated)(void) = null; +static result (*pWifiManagerImpl_Activate)(void) = null; +static result (*pWifiManagerImpl_Deactivate)(void) = null; +static result (*pBluetoothManagerImpl_Activate)(void) = null; +static result (*pBluetoothManagerImpl_Deactivate)(void) = null; + +_SettingManager* _SettingManager::__pSettingManager = null; + +class _SettingEventArg : public IEventArg +{ +public: + String KeyName; +}; + +class _SettingEvent : public Event +{ +protected: + virtual void FireImpl(IEventListener& listener, const IEventArg& arg) + { + ISettingEventListener* pListener = dynamic_cast (&listener); + const _SettingEventArg* pArg = dynamic_cast(&arg); + + if(pListener == null || pArg == null) + { + SysLogException(NID_SYS, E_SYSTEM, "It is failed to get listner or arguemnt"); + return; + } + + String value =pArg->KeyName; + pListener->OnSettingChanged(value); + } +}; + +class _SettingAsyncEventArg : public IEventArg +{ +public: + String Key; + result errorCode; +}; + +class _SettingAsyncEvent : public Event +{ +protected: + virtual void FireImpl(IEventListener& listener, const IEventArg& arg) + { + ISettingInfoSetValueAsyncResultListener* pListener = dynamic_cast (&listener); + const _SettingAsyncEventArg* pArg = dynamic_cast(&arg); + + if(pListener == null || pArg == null) + { + SysLogException(NID_SYS, E_SYSTEM, "It is failed to get listner or arguemnt"); + return; + } + + result r = pArg->errorCode; + pListener->OnResultReceivedForSetValueAsync(pArg->Key, r); + RemoveListener(listener); + delete pListener; + } +}; + +void +_SettingManager::InitSettingManager(void) +{ + static _SettingManager settingManager; + __pSettingManager = &settingManager; +} + +_SettingManager* +_SettingManager::GetInstance(void) +{ + static pthread_once_t once_block = PTHREAD_ONCE_INIT; + if(__pSettingManager == null) + { + pthread_once(&once_block, InitSettingManager); + } + return __pSettingManager; +} + +_SettingManager::_SettingManager() + : __pSettingEventListener(null) + , __pSettingEvent(null) + , __listenerCount(0) + , __registeredSettingEvents(false) + , __tapiHandle(null) + , __pSettingAsyncEvent(null) + , __pSettingEventForInternal(null) + , __listenerInternalCount(0) + , __registeredSettingEventsForInternal(false) + , __pWifiDllHandle(null) +{ + __pSettingEvent = new (std::nothrow) _SettingEvent(); + __pSettingEventForInternal = new (std::nothrow) _SettingEvent(); + + tethering_create(&__tetheringHandle); +} + +_SettingManager::~_SettingManager() +{ + + if(__registeredSettingEvents == true) + { + __listenerCount = 0; + StopSettingEventListen(); + } + + delete __pSettingEvent; + + if(__tetheringHandle != null) + { + tethering_destroy(__tetheringHandle); + } + + if(__pSettingAsyncEvent != null) + { + delete __pSettingAsyncEvent; + } + __pSettingManager = null; +} + +result +_SettingManager::GetValue(const String& key, String& value) +{ + result r = E_SUCCESS; + + if (key == _COUNTRY) + { + int ret = 0; + char* pCountry = null; + String countryValue; + + ret = runtime_info_get_value_string(RUNTIME_INFO_KEY_REGION, &pCountry); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE && pCountry != null, E_SYSTEM, "[E_SYSTEM] runtime_info_get_value_string RUNTIME_INFO_KEY_LANGUAGE failed"); + + Tizen::Locales::Locale ospLoc = _LocaleImpl(pCountry).GetOspLocale(); + value = ospLoc.GetCountryCodeString(); + free (pCountry); + } + else if (key == _LOCALE_COUNTRY) + { + int ret = 0; + char* pCountry = null; + String countryValue; + + ret = runtime_info_get_value_string(RUNTIME_INFO_KEY_REGION, &pCountry); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE && pCountry != null, E_SYSTEM, "[E_SYSTEM] runtime_info_get_value_string RUNTIME_INFO_KEY_LANGUAGE failed"); + + Tizen::Locales::Locale ospLoc = _LocaleImpl(pCountry).GetOspLocale(); + value = ospLoc.GetLocaleCodeString(); + free (pCountry); + } + else if (key == _DEVICE_NAME) + { + std::unique_ptr pDeviceName (vconf_get_str(VCONFKEY_SETAPPL_DEVICE_NAME_STR)); + String deviceName; + r = StringUtil::Utf8ToString(pDeviceName.get(), deviceName); + SysTryReturn(NID_SYS, !IsFailed(r), E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + + value = deviceName; + } + else if (key == _LOCALE_DATE) + { + DateTime currentTime; + SystemTime::GetCurrentTime(TIME_MODE_WALL, currentTime); + String currentFormat; + GetValue(_LOCALE_DATE_FORMAT, currentFormat); + + std::unique_ptr pFormatter(DateTimeFormatter::CreateTimeFormatterN()); + SysTryReturnResult(NID_SYS, pFormatter != null, E_OUT_OF_MEMORY, "Failed to create DateTimeFomatter"); + pFormatter->ApplyPattern(currentFormat); + value.Clear(); + pFormatter->Format(currentTime, value); + } + else if (key == _LANGUAGE) + { + int ret = 0; + char* pLanguage = null; + String langValue; + LanguageCode langCode = LANGUAGE_ENG; + + ret = runtime_info_get_value_string(RUNTIME_INFO_KEY_LANGUAGE, &pLanguage); + + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE && pLanguage != null, E_SYSTEM, "[E_SYSTEM] runtime_info_get_value_string RUNTIME_INFO_KEY_LANGUAGE failed"); + + r = StringUtil::Utf8ToString(pLanguage, langValue); + free(pLanguage); + SysTryReturn(NID_SYS, !IsFailed(r), E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + + if (langValue.GetLength() > 2) + { + langValue.SubString(0, 2, langValue); + } + + langCode = Tizen::Locales::Locale::TwoLetterLanguageCodeStringToLanguageCode(langValue); + langValue = Tizen::Locales::Locale::LanguageCodeToString(langCode); + SysTryReturnResult(NID_SYS, langValue.GetLength() == 3, E_SYSTEM, "[E_SYSTEM] _LANGUAGEcode transform failed. value is \"%ls\"", langValue.GetPointer()); + + value = langValue; + } + else if (key == _LOCALE_LANGUAGE) + { + int ret = 0; + char* pCountry = null; + String countryValue; + String langValue; + LanguageCode langCode = LANGUAGE_ENG; + + ret = runtime_info_get_value_string(RUNTIME_INFO_KEY_LANGUAGE, &pCountry); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE && pCountry != null, E_SYSTEM, "[E_SYSTEM] runtime_info_get_value_string RUNTIME_INFO_KEY_LANGUAGE failed"); + + r = StringUtil::Utf8ToString(pCountry, countryValue); + SysTryReturn(NID_SYS, !IsFailed(r), E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + + free(pCountry); + + countryValue.SubString(0, 2, langValue); + countryValue.SubString(3, 2, countryValue); + + langCode = Tizen::Locales::Locale::TwoLetterLanguageCodeStringToLanguageCode(langValue); + langValue = Tizen::Locales::Locale::LanguageCodeToString(langCode); + SysTryReturnResult(NID_SYS, langValue.GetLength() == 3, E_SYSTEM, "[E_SYSTEM] _LANGUAGEcode transform failed. value is \"%ls\"", langValue.GetPointer()); + value.Clear(); + value.Append(langValue); + value.Append("_"); + value.Append(countryValue); + } + else if (key == _DATE_FORMAT || key == _LOCALE_DATE_FORMAT) + { + char* pDateFormat = __settingIcu.GetDateTimeFormatN(_ICU_DATE_FORMAT); + SysTryReturnResult(NID_SYS, pDateFormat != null, E_SYSTEM, "Failed to get date format"); + r = StringUtil::Utf8ToString(pDateFormat, value); + free(pDateFormat); + } + else if (key == _LOCALE_DATETIME) + { + DateTime currentTime; + SystemTime::GetCurrentTime(TIME_MODE_WALL, currentTime); + String currentFormat; + GetValue(_LOCALE_DATETIME_FORMAT, currentFormat); + + std::unique_ptr pFormatter(DateTimeFormatter::CreateTimeFormatterN()); + pFormatter->ApplyPattern(currentFormat); + value.Clear(); + pFormatter->Format(currentTime, value); + } + else if (key == _DATE_TIME_FORMAT || key == _LOCALE_DATETIME_FORMAT) + { + char* pDateFormat = __settingIcu.GetDateTimeFormatN(_ICU_DATE_FORMAT); + char* pTimeFormat = null; + String timeFormat; + bool selected24Format = false; + + SysLog(NID_SYS, "Date Time format"); + SysTryReturnResult(NID_SYS, pDateFormat != null, E_SYSTEM, "Failed to get date format"); + + r = GetValue(_HOUR_FORMAT_SELECTED, selected24Format); + if(r != E_SUCCESS) + { + free(pDateFormat); + SysLogException(NID_SYS, E_SYSTEM, "Failed to get 24 hour select state"); + return E_SYSTEM; + } + SysLog(NID_SYS, "24hour format, %d", selected24Format); + SysLog(NID_SYS, "%s", pDateFormat); + + if (selected24Format == true) + { + pTimeFormat = __settingIcu.GetDateTimeFormatN(_ICU_TIME_24_FORMAT); + } + else + { + pTimeFormat = __settingIcu.GetDateTimeFormatN(_ICU_TIME_12_FORMAT); + } + + if(pTimeFormat == null) + { + free(pDateFormat); + SysLogException(NID_SYS, E_SYSTEM, "Failed to get date time format"); + return E_SYSTEM; + } + + r = StringUtil::Utf8ToString(pDateFormat, value); + r = StringUtil::Utf8ToString(pTimeFormat, timeFormat); + + value.Append(" "); + value.Append(timeFormat); + free(pDateFormat); + free(pTimeFormat); + } + else if (key == _LOCALE_TIME) + { + DateTime currentTime; + SystemTime::GetCurrentTime(TIME_MODE_WALL, currentTime); + String currentFormat; + GetValue(_LOCALE_TIME_FORMAT, currentFormat); + + std::unique_ptr pFormatter(DateTimeFormatter::CreateTimeFormatterN()); + pFormatter->ApplyPattern(currentFormat); + value.Clear(); + pFormatter->Format(currentTime, value); + } + else if (key == _LOCALE_TIMEZONE) + { + char pTZPath[256] = {0,}; + ssize_t nLen = readlink(_LOCALE_TIMEZONE_LINK, pTZPath, sizeof(pTZPath)-1); + if (nLen != -1) + { + pTZPath[nLen] = '\0'; + } + else + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to get timezone"); + } + value.Clear(); + value.Append(&pTZPath[_LOCALE_TIMEZONE_ROOT_PATH_LENGTH]); + } + else if (key == _LOCALE_WEEK_FORMAT_FIRSTDAY) + { + int firstDay = 0; + int ret = -1; + + ret = vconf_get_int(VCONFKEY_SETAPPL_WEEKOFDAY_FORMAT_INT, &firstDay); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_WEEKOFDAY_FORMAT_INT vconf"); + + if (firstDay == _LOCALE_WEEK_FORMAT_VCONF_SUNDAY) + { + value = _LOCALE_WEEK_FORMAT_FIRSTDAY_SUNDAY; + } + else if (firstDay == _LOCALE_WEEK_FORMAT_VCONF_MONDAY) + { + value = _LOCALE_WEEK_FORMAT_FIRSTDAY_MONDAY; + } + else + { + r = E_SYSTEM; + } + } + else if (key == _NETWORK_TELEPHONY_MODE) + { + value = _tmpNetworkTelephonyMode; + } + else if (key == _NETWORK_TELEPHONY_PROVIDER) + { + value = _tmpNetworkTelephonyProvider; + } + else if (key == _NETWORK_WIFI_TETHERING_SECURITY_PASSWORD) + { + int ret = 0; + char* password = null; + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + ret = tethering_wifi_get_passphrase(__tetheringHandle, &password); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "It is failed to get password"); + + value.Clear(); + value.Append(password); + free(password); + } + else if (key == _SCREEN_MODE) + { + std::unique_ptr curmode(vconf_get_str(_SCREEN_MODE_VCONFKEY)); + value.Clear(); + value.Append(curmode.get()); + } + else if (key == _STORAGE_DIRECTORY_WAP_DOWNLOAD) + { + value = _tmpStorageDirectoryWapDownload; + } + else if (key == _STORAGE_DIRECTORY_BLUETOOTH_DOWNLOAD) + { + value = _tmpStorageDirectoryBluetoothDownload; + } + else if (key == _STORAGE_DIRECTORY_CAMERA_RECORD) + { + value = _tmpStorageDirectoryCameraRecord; + } + else if (key == _STORAGE_DIRECTORY_VOICE_RECORD) + { + value = _tmpStorageDirectoryVoiceRecord; + } + else if (key == _STORAGE_DIRECTORY_RADIO_BROADCAST) + { + value = _tmpStorageDirectoryRadioBroadcast; + } + else if (key == _STORAGE_DIRECTORY_VIDEO_BROADCAST) + { + value = _tmpStorageDirectoryVideoBroadcast; + } + else if (key == _FONTTYPE || key == _FONT_TYPE) + { + char* pFontType = null; + int res = 0; + res = system_settings_get_value_string(SYSTEM_SETTINGS_KEY_FONT_TYPE, &pFontType); + SysTryReturnResult(NID_SYS, res == SYSTEM_SETTINGS_ERROR_NONE, E_SYSTEM, "Failed to get font type"); + r = StringUtil::Utf8ToString(pFontType, value); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + free(pFontType); + } + else if (key == _FONT_SIZE || key == _FONTSIZE) + { + int fontSize = 0; + int res = 0; + res = system_settings_get_value_int(SYSTEM_SETTINGS_KEY_FONT_SIZE, &fontSize); + SysTryReturnResult(NID_SYS, res == SYSTEM_SETTINGS_ERROR_NONE, E_SYSTEM, "Failed to get font size"); + value.Clear(); + switch (fontSize) + { + case _FONT_SIZE_GIANT_VCONF: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + value.Append(_FONT_SIZE_GIANT); + break; + } + case _FONT_SIZE_HUGE_VCONF: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + value.Append(_FONT_SIZE_HUGE); + break; + } + case _FONT_SIZE_LARGE_VCONF: + value.Append(_FONT_SIZE_LARGE); + break; + case _FONT_SIZE_MEDIUM_VCONF: + value.Append(_FONT_SIZE_MEDIUM); + break; + case _FONT_SIZE_SMALL_VCONF: + value.Append(_FONT_SIZE_SMALL); + break; + default: + r = E_SYSTEM; + break; + } + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + value.ToLowerCase(); + } + } + else if (key == _RINGTONE || key == _SOUND_RINGTONE) + { + char* pRingtone = null; + int res = 0; + res = system_settings_get_value_string(SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE, &pRingtone); + SysTryReturnResult(NID_SYS, res == SYSTEM_SETTINGS_ERROR_NONE, E_SYSTEM, "Failed to get ringtone"); + + r = StringUtil::Utf8ToString(pRingtone, value); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + + free(pRingtone); + + } + else if (key == _TIME_FORMAT || key == _LOCALE_TIME_FORMAT) + { + char* pTimeFormat = null; + bool selected24Format = false; + + r = GetValue(_HOUR_FORMAT_SELECTED, selected24Format); + + if (selected24Format == true) + { + pTimeFormat = __settingIcu.GetDateTimeFormatN(_ICU_TIME_24_FORMAT); + } + else + { + pTimeFormat = __settingIcu.GetDateTimeFormatN(_ICU_TIME_12_FORMAT); + } + SysTryReturnResult(NID_SYS, pTimeFormat != null, E_SYSTEM, "Failed to get time format"); + r = StringUtil::Utf8ToString(pTimeFormat, value); + free(pTimeFormat); + } + else if (key == _WALLPAPER || key == _SCREEN_WALLPAPER) + { + int ret = 0; + char* pWallpaper = null; + + ret = system_settings_get_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN, &pWallpaper); + SysTryReturn(NID_SYS, ret == 0, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get wallpaper of home screen"); + + r = StringUtil::Utf8ToString(pWallpaper, value); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + + free(pWallpaper); + } + else if (key == _SCREEN_WALLPAPER_LOCK) + { + int ret = 0; + char* pWallpaper = null; + + ret = system_settings_get_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN, &pWallpaper); + SysTryReturn(NID_SYS, ret == 0, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get wallpaper of lock screen"); + + r = StringUtil::Utf8ToString(pWallpaper, value); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + + free(pWallpaper); + } + else if (key == _USBMODE) + { + value = _USBMODE_MTP; + } + else + { + r = E_OBJ_NOT_FOUND; + } + return r; +} + +result +_SettingManager::GetValue(const String& key, int& value) +{ + result r = E_SUCCESS; + if (key == _TOUCH_VIBRATION_LEVEL || key == _VIBRATOR_LEVEL) + { + int vibLevel = -1; + int ret = 0; + ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_VIBRATION_LEVEL_HAPTIC_FEEDBACK, &vibLevel); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "runtime_info_get_value_int(RUNTIME_INFO_KEY_VIBRATION_LEVEL_HAPTIC_FEEDBACK) is Failed"); + + value = vibLevel * _TOUCH_FEEDBACK_RESOLUTION; + } + else if (key == _MEDIA_SOUND_VOLUME || key == _SOUND_MEDIA_VOLUME) + { + int volume = 0; + int maxVolume = 0; + + int ret = sound_manager_get_max_volume(SOUND_TYPE_MEDIA, &maxVolume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "sound_manager_get_max_volume Failed"); + + ret = sound_manager_get_volume(SOUND_TYPE_MEDIA, &volume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "sound_manager_get_volume Failed"); + + value = volume; + } + else if (key == _NOTIFICATION_SOUND_VOLUME || key == _SOUND_NOTIFICATION_VOLUME) + { + int volume = 0; + int maxVolume = 0; + + int ret = sound_manager_get_max_volume(SOUND_TYPE_NOTIFICATION, &maxVolume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "sound_manager_get_max_volume Failed"); + + ret = sound_manager_get_volume(SOUND_TYPE_NOTIFICATION, &volume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "sound_manager_get_volume Failed"); + + value = volume; + } + else if (key == _RINGTONE_SOUND_VOLUME || key == _SOUND_RINGTONE_VOLUME) + { + int volume = 0; + int maxVolume = 0; + + int ret = sound_manager_get_max_volume(SOUND_TYPE_RINGTONE, &maxVolume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "sound_manager_get_max_volume Failed"); + + ret = sound_manager_get_volume(SOUND_TYPE_RINGTONE, &volume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "sound_manager_get_volume Failed"); + + value = volume; + } + else if (key == _SYSTEM_SOUND_VOLUME || key == _SOUND_SYSTEM_VOLUME) + { + int volume = 0; + int maxVolume = 0; + + int ret = sound_manager_get_max_volume(SOUND_TYPE_SYSTEM, &maxVolume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "sound_manager_get_max_volume Failed"); + + ret = sound_manager_get_volume(SOUND_TYPE_SYSTEM, &volume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "sound_manager_get_volume Failed"); + + value = volume; + } + else if (key == _SCREEN_BRIGHTNESS) + { + int brightness = 0; + int ret = vconf_get_int(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, &brightness); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_LCD_BRIGHTNESS vconf"); + value = brightness; + } + else if (key == _SCREEN_BACKLIGHT_TIME) + { + int timeout = 0; + int ret = vconf_get_int(VCONFKEY_SETAPPL_LCD_TIMEOUT_NORMAL, &timeout); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_TIMEOUT_NORMAL vconf"); + value = timeout; + } + else if (key == _VIBRATOR_LEVEL_NOTIFICATION) + { + int level = 0; + int ret = vconf_get_int(VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT, &level); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT vconf"); + value = level; + } + else + { + r = E_OBJ_NOT_FOUND; + } + return r; +} + +result +_SettingManager::GetValue(const String& originalKey, long long& value) +{ + return E_OBJ_NOT_FOUND; +} + +result +_SettingManager::GetValue(const String& originalKey, double& value) +{ + return E_OBJ_NOT_FOUND; +} + +result +_SettingManager::GetValue(const String& key, bool& value) +{ + result r = E_SUCCESS; + int vconf_bool = 0; + int ret = -1; + + if (key == _BATTERY_FORMAT_PERCENTAGE) + { + ret = vconf_get_bool(VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL, &vconf_bool); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL vconf"); + + if(vconf_bool == 0) + { + value = false; + } + else + { + value = true; + } + } + else if (key == _LOCALE_UPDATE_AUTO) + { + ret = vconf_get_bool(VCONFKEY_SETAPPL_STATE_AUTOMATIC_TIME_UPDATE_BOOL, &vconf_bool); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_STATE_AUTOMATIC_TIME_UPDATE_BOOL vconf"); + value = vconf_bool ? true : false; + } + else if (key == _NETWORK_WIFI) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + int wifiState = 0; + ret = vconf_get_int(VCONFKEY_WIFI_STATE, &wifiState); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_WIFI_STATE vconf"); + if(wifiState== VCONFKEY_WIFI_OFF) + { + value = false; + } + else + { + value = true; + } + return r; + } + else if (key == _NETWORK_WIFI_NOTIFICATION) + { + int wifiQSState = 0; + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + ret = vconf_get_int(VCONFKEY_WIFI_ENABLE_QS, &wifiQSState); + SysTryReturnResult(NID_SYS, ret != -1, E_UNSUPPORTED_OPERATION, "Current device does not support %ls key.", key.GetPointer()); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_WIFI_ENABLE_QS vconf"); + + if(wifiQSState == VCONFKEY_WIFI_QS_DISABLE) + { + value = false; + } + else + { + value = true; + } + return r; + } + else if (key == _NETWORK_WIFI_TETHERING) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + value = tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_WIFI); + return r; + } + else if (key == _NETWORK_WIFI_TETHERING_HIDE) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + ret = tethering_wifi_get_ssid_visibility(__tetheringHandle, &value); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to get wifi tethering visibility state"); + return r; + } + else if (key == _NETWORK_WIFI_TETHERING_SECURITY) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + tethering_wifi_security_type_e securityType; + ret = tethering_wifi_get_security_type(__tetheringHandle, &securityType); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to get wifi tethering securiy state"); + if(securityType == TETHERING_WIFI_SECURITY_TYPE_NONE) + { + value = false; + } + else + { + value = true; + } + return r; + } + else if (key == _NETWORK_WIFI_DIRECT) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI_DIRECT, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support WiFi direct feature"); + SysTryReturnResult(NID_SYS, LoadWifiDll() == E_SUCCESS, E_SYSTEM, "Failed to open wifi so"); + + bool isActivated = false; + isActivated = pWifiDirectDeviceImpl_IsActivated(); + + UnloadWifiDll(); + SysTryReturnResult(NID_SYS, GetLastResult() == E_SUCCESS, E_SYSTEM, "Failed to get wifi direct state"); + value = isActivated; + return r; + } + else if (key == _NETWORK_BLUETOOTH) + { + int bluetoothStatus = VCONFKEY_BT_STATUS_OFF; + ret = vconf_get_int(VCONFKEY_BT_STATUS, &bluetoothStatus); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "It is failed to read bluetooth status."); + + if(bluetoothStatus == VCONFKEY_BT_STATUS_OFF) + { + value = false; + } + else + { + value = true; + } + + return r; + } + else if (key == _NETWORK_BLUETOOTH_TETHERING) + { + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + value = tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_BT); + return r; + } + else if (key == _SCREEN_BRIGHTNESS_AUTO) + { + int brightnessAuto = 0; + int ret = vconf_get_int(VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT, &brightnessAuto); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL vconf"); + + if(brightnessAuto == 0) + { + value = false; + } + else + { + value = true; + } + return r; + } + else if (key == _SOUND_LOCK) + { + int soundLock = 0; + int ret = vconf_get_bool(VCONFKEY_SETAPPL_SOUND_LOCK_BOOL, &soundLock); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_SOUND_LOCK_BOO vconf"); + if(soundLock == 0) + { + value = false; + } + else + { + value = true; + } + return r; + } + else if (key == _SOUND_TOUCH) + { + int soundTouch = 0; + int ret = vconf_get_bool(VCONFKEY_SETAPPL_TOUCH_SOUNDS_BOOL, &soundTouch); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_TOUCH_SOUNDS_BOOL vconf"); + if(soundTouch == 0) + { + value = false; + } + else + { + value = true; + } + return r; + } + else if (key == _VIBRATOR) + { + ret = vconf_get_bool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, &vconf_bool); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL vconf"); + value = vconf_bool ? true : false; + return r; + } + else if (key == _USB_TETHERING) + { + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + value = tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_USB); + return r; + } + else if (key == _WEB_APPLICATION_COOKIE_SHARE) + { + value = _tmpWebApplicationCookieShare; + return r; + } + else if (key == _LOCATION_GPS_ADVANCED) + { + int agps = 0; + ret = vconf_get_int(VCONFKEY_LOCATION_AGPS_ENABLED, &agps); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL vconf"); + + if(agps == 0) + { + value = false; + } + else + { + value = true; + } + + return r; + } + else if (key == _SCREEN_ROTATION_AUTO) + { + ret = vconf_get_bool(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, &vconf_bool); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL vconf"); + value = vconf_bool; + } + else if (key == _HOUR_FORMAT_SELECTED || key == _LOCALE_TIME_FORMAT_24HOUR) + { + bool is24HoueEnabled = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_24HOUR_CLOCK_FORMAT_ENABLED, &is24HoueEnabled); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__WIFI_SUPPORTED"); + value = is24HoueEnabled; + + return r; + } + else if (key == _ENABLE_MOTION || key == _MOTION_UI) + { + bool enableMotion = false; + ret = system_settings_get_value_bool(SYSTEM_SETTINGS_KEY_MOTION_ACTIVATION, &enableMotion); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the SYSTEM_SETTINGS_KEY_MOTION_ACTIVIATION"); + value = enableMotion; + + return r; + } + else if (key == _DATA_ROAMING_ENABLED || key == _NETWORK_TELEPHONY_ROAMING) + { + bool dataRoamingEnabled = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_DATA_ROAMING_ENABLED, &dataRoamingEnabled); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the RUNTIME_INFO_KEY_DATA_ROAMING_ENABLED"); + value = dataRoamingEnabled; + + return r; + } + else if (key == _GPS_ENABLED || key == _LOCATION_GPS) + { + int gps_value = 0; + ret = vconf_get_int(VCONFKEY_LOCATION_ENABLED, &gps_value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the VCONFKEY_LOCATION_ENABLED"); + if(gps_value == 0) + { + value = false; + } + else + { + value = true; + } + } + else if (key == _PACKET_SERVICE_ALLOWED || key == _NETWORK_TELEPHONY_PACKETSERVICE) + { + bool packetServiceAllowed = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_PACKET_DATA_ENABLED, &packetServiceAllowed); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the RUNTIME_INFO_KEY_PACKET_DATA_ENABLED"); + value = packetServiceAllowed; + + return r; + } + else if (key == _SILENT_MODE || key == _SOUND_SILENTMODE) + { + bool silentModeEnabled = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_SILENT_MODE_ENABLED, &silentModeEnabled); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the RUNTIME_INFO_KEY_SILENT_MODE_ENABLED"); + value = !silentModeEnabled; + + return r; + } + else if (key == _WPS_ENABLED || key == _LOCATION_WPS) + { + int wps_value = 0; + ret = vconf_get_int(VCONFKEY_LOCATION_NETWORK_ENABLED, &wps_value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the VCONFKEY_LOCATION_NETWORK_ENABLED"); + if(wps_value == 0) + { + value = false; + } + else + { + value = true; + } + + } + else if (key == _FLIGHT_MODE_ENABLED || key == _NETWORK_FLIGHTMODE) + { + bool flightModeEnabled = false; + ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_FLIGHT_MODE_ENABLED, &flightModeEnabled); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the RUNTIME_INFO_KEY_FLIGHT_MODE_ENABLED"); + value = flightModeEnabled; + + return r; + } + else if (key == _DEVELOPER_USBDEBUGGING) + { + int usbMode = 0; + ret = vconf_get_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, &usbMode); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL"); + value = usbMode == _DEVELOPER_USBDEBUGGING_ON; + } + else if (key == _NETWORK_TELEPHONY_ROAMING) + { + ret = vconf_get_bool(VCONFKEY_SETAPPL_STATE_DATA_ROAMING_BOOL, &vconf_bool); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the VCONFKEY_SETAPPL_STATE_DATA_ROAMING_BOOL"); + value = vconf_bool ? true : false; + } + else if (key == _CONTACT_ORDER_FIRSTNAME) + { + int contactOrder = 0; + ret = vconf_get_int(VCONFKEY_CONTACTS_SVC_NAME_DISPLAY_ORDER, &contactOrder); + SysTryReturnResult(NID_SYS, ret == RUNTIME_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the VCONFKEY_CONTACTS_SVC_NAME_DISPLAY_ORDER"); + + if (contactOrder == _CONTACT_ORDER_FIRSTNAME_FIRSTLAST) + { + value = true; + } + else if (contactOrder == _CONTACT_ORDER_FIRSTNAME_LASTFIRST) + { + value = false; + } + else + { + return E_SYSTEM; + } + } + else + { + r = E_OBJ_NOT_FOUND; + } + + return r; +} + +result +_SettingManager::GetValue(const String& originalKey, UuId& value) +{ + return E_OBJ_NOT_FOUND; +} + +result +_SettingManager::GetValueForPrivilegedKey(const String& originalKey, bool& value) +{ + return E_OBJ_NOT_FOUND; +} + +result +_SettingManager::SetValue(const String& key, const bool& value) +{ + int ret = -1; + + if(key == _LOCALE_TIME_FORMAT_24HOUR) + { + ret = vconf_set_int(VCONFKEY_REGIONFORMAT_TIME1224, value ? VCONFKEY_TIME_FORMAT_24 : VCONFKEY_TIME_FORMAT_12); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_REGIONFORMAT_TIME1224 vconf"); + } + else if(key == _BATTERY_FORMAT_PERCENTAGE) + { + ret = vconf_set_bool(VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL vconf"); + } + else if(key == _LOCALE_UPDATE_AUTO) + { + ret = vconf_set_bool(VCONFKEY_SETAPPL_STATE_AUTOMATIC_TIME_UPDATE_BOOL, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_STATE_AUTOMATIC_TIME_UPDATE_BOOL vconf"); + } + else if(key == _NETWORK_WIFI_NOTIFICATION) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + int currentValue = 0; + ret = vconf_get_int(VCONFKEY_WIFI_ENABLE_QS, ¤tValue); + SysTryReturnResult(NID_SYS, ret != -1, E_UNSUPPORTED_OPERATION, "This device does not support %ls key.", key.GetPointer()); + + if(value == true) + { + ret = vconf_set_int(VCONFKEY_WIFI_ENABLE_QS, VCONFKEY_WIFI_QS_ENABLE); + } + else + { + ret = vconf_set_int(VCONFKEY_WIFI_ENABLE_QS, VCONFKEY_WIFI_QS_DISABLE); + } + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_WIFI_ENABLE_QS vconf"); + } + else if(key == _NETWORK_WIFI_TETHERING) + { + result r = E_SUCCESS; + + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + sim_state_e simState; + ret = sim_get_state(&simState); + + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the SIM state"); + SysTryReturnResult(NID_SYS, simState != SIM_STATE_UNAVAILABLE, E_INVALID_STATE, "SIM is not available"); + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + + bool state = false; + r = GetValue(_NETWORK_WIFI, state); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to get the WIFI state"); + SysTryReturnResult(NID_SYS, state == true, E_INVALID_STATE, "WIFI is not activated"); + + if(value == true) + { + if(tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_WIFI) == false) + { + ret = tethering_enable(__tetheringHandle, TETHERING_TYPE_WIFI); + } + } + else + { + if(tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_WIFI) == true) + { + ret = tethering_disable(__tetheringHandle, TETHERING_TYPE_WIFI); + } + } + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to change tethering option"); + } + else if(key == _NETWORK_WIFI_TETHERING_HIDE) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + bool currentState = false; + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + ret = tethering_wifi_get_ssid_visibility(__tetheringHandle, ¤tState); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to current wifi tethering visibility setting"); + + if(value == true && currentState == false) + { + ret = tethering_wifi_set_ssid_visibility(__tetheringHandle, true); + } + else if(value == false && currentState == true) + { + ret = tethering_wifi_set_ssid_visibility(__tetheringHandle, false); + } + + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to change wifi tethering visibility setting"); + } + else if(key == _NETWORK_WIFI_TETHERING_SECURITY) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + tethering_wifi_security_type_e securityType; + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + ret = tethering_wifi_get_security_type(__tetheringHandle, &securityType); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to get wifi tethering securiy state"); + + if(value == true && securityType == TETHERING_WIFI_SECURITY_TYPE_NONE) + { + ret = tethering_wifi_set_security_type(__tetheringHandle, TETHERING_WIFI_SECURITY_TYPE_WPA2_PSK); + } + else if(value == false && securityType == TETHERING_WIFI_SECURITY_TYPE_WPA2_PSK) + { + ret = tethering_wifi_set_security_type(__tetheringHandle, TETHERING_WIFI_SECURITY_TYPE_NONE); + } + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to change wifi tethering visibility setting"); + } + else if(key == _NETWORK_BLUETOOTH) + { + bool supported = false; + int bluetoothStatus = VCONFKEY_BT_STATUS_OFF; + result r = E_SUCCESS; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_BLUETOOTH, supported); + SysTryReturnResult(NID_SYS, supported == true && r == E_SUCCESS, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + SysTryReturnResult(NID_SYS, LoadBluetoothDll() == E_SUCCESS, E_SYSTEM, "It is failed to load bluetooth library."); + + ret = vconf_get_int(VCONFKEY_BT_STATUS, &bluetoothStatus); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "It is failed to read bluetooth status."); + + if(value == true) + { + if(bluetoothStatus == VCONFKEY_BT_STATUS_OFF) + { + r = pBluetoothManagerImpl_Activate(); + } + } + else + { + if(bluetoothStatus != VCONFKEY_BT_STATUS_OFF) + { + r = pBluetoothManagerImpl_Deactivate(); + } + } + + UnloadBluetoothDll(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to change bluetooth state."); + } + else if(key == _NETWORK_BLUETOOTH_TETHERING) + { + result r = E_SUCCESS; + sim_state_e simState; + ret = sim_get_state(&simState); + + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the SIM state"); + SysTryReturnResult(NID_SYS, simState != SIM_STATE_UNAVAILABLE, E_INVALID_STATE, "SIM is not available"); + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + + bool state = false; + r = GetValue(_NETWORK_BLUETOOTH, state); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to get the Bluetooth state"); + SysTryReturnResult(NID_SYS, state == true, E_INVALID_STATE, "Bluetooth is not activated"); + + if(value == true) + { + if(tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_BT) == false) + { + ret = tethering_enable(__tetheringHandle, TETHERING_TYPE_BT); + } + } + else + { + if(tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_BT) == true) + { + ret = tethering_disable(__tetheringHandle, TETHERING_TYPE_BT); + } + } + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to change tethering option"); + } + else if(key == _SCREEN_BRIGHTNESS_AUTO) + { + if(value == true) + { + ret = vconf_set_int(VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT, SETTING_BRIGHTNESS_AUTOMATIC_ON); + } + else + { + ret = vconf_set_int(VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT, SETTING_BRIGHTNESS_AUTOMATIC_OFF); + } + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL vconf"); + } + else if(key == _SOUND_LOCK) + { + ret = vconf_set_bool(VCONFKEY_SETAPPL_SOUND_LOCK_BOOL, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_SOUND_LOCK_BOOL vconf"); + } + else if(key == _SOUND_TOUCH) + { + ret = vconf_set_bool(VCONFKEY_SETAPPL_TOUCH_SOUNDS_BOOL, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_SETAPPL_TOUCH_SOUNDS_BOOL vconf"); + } + else if(key == _USB_TETHERING) + { + sim_state_e simState; + ret = sim_get_state(&simState); + + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the SIM state"); + SysTryReturnResult(NID_SYS, simState != SIM_STATE_UNAVAILABLE, E_INVALID_STATE, "SIM is not available"); + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + + if(value == true) + { + if(tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_USB) == false) + { + ret = tethering_enable(__tetheringHandle, TETHERING_TYPE_USB); + } + } + else + { + if(tethering_is_enabled(__tetheringHandle, TETHERING_TYPE_USB) == true) + { + ret = tethering_disable(__tetheringHandle, TETHERING_TYPE_USB); + } + } + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to change tethering option"); + } + else if(key == _WEB_APPLICATION_COOKIE_SHARE) + { + _tmpWebApplicationCookieShare = value; + } + else if(key == _VIBRATOR) + { + if(!value) + { + ret = haptic_open(HAPTIC_DEVICE_0, &__hapticHandle); + SysTryReturnResult(NID_SYS, ret == HAPTIC_ERROR_NONE, E_SYSTEM, "It is failed to open haptic library"); + haptic_stop_all_effects(__hapticHandle); + ret = haptic_close(__hapticHandle); + SysTryReturnResult(NID_SYS, ret == HAPTIC_ERROR_NONE, E_SYSTEM, "It is failed to close haptic library"); + __hapticHandle = null; + } + ret = vconf_set_bool(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL vconf"); + } + else if(key == _SCREEN_ROTATION_AUTO) + { + ret = vconf_set_bool(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL vconf"); + } + else if(key == _SOUND_SILENTMODE) + { + bool silentMode = !value; + ret = vconf_set_bool(VCONFKEY_SETAPPL_SOUND_STATUS_BOOL, silentMode); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_SOUND_STATUS_BOOL vconf"); + } + else if (key == _CONTACT_ORDER_FIRSTNAME) + { + int contactOrder = 0; + + if (value) + { + contactOrder = _CONTACT_ORDER_FIRSTNAME_FIRSTLAST; + } + else + { + contactOrder = _CONTACT_ORDER_FIRSTNAME_LASTFIRST; + } + ret = vconf_set_int(VCONFKEY_CONTACTS_SVC_NAME_DISPLAY_ORDER, contactOrder); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_CONTACTS_SVC_NAME_DISPLAY_ORDER vconf"); + } + else if(key == _MOTION_UI) + { + ret = system_settings_set_value_bool(SYSTEM_SETTINGS_KEY_MOTION_ACTIVATION, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set the SYSTEM_SETTINGS_KEY_MOTION_ACTIVIATION"); + } + else + { + return E_OBJ_NOT_FOUND; + } + return E_SUCCESS; +} + +result +_SettingManager::SetValue(const String& key, const int& value) +{ + if(key == _VIBRATOR_LEVEL) + { + SysTryReturnResult(NID_SYS, value >= 0 && value <= 100, E_INVALID_ARG, "Speicified value is not valid"); + int ret = vconf_set_int(VCONFKEY_SETAPPL_TOUCH_FEEDBACK_VIBRATION_LEVEL_INT, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_TOUCH_FEEDBACK_VIBRATION_LEVEL_INT vconf"); + } + else if(key == _VIBRATOR_LEVEL_NOTIFICATION) + { + SysTryReturnResult(NID_SYS, value >= 0 && value <= 100, E_INVALID_ARG, "Speicified value is not valid"); + int ret = vconf_set_int(VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT vconf"); + } + else if(key == _SCREEN_BRIGHTNESS) + { + SysTryReturnResult(NID_SYS, value > 0 && value <= 100, E_INVALID_ARG, "Out of range"); + + int ret = vconf_set_int(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_TIMEOUT_NORMAL vconf"); + ret = device_set_brightness(0, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to update on Screen Brightness vconf"); + } + else if(key == _SCREEN_BACKLIGHT_TIME) + { + SysTryReturnResult(NID_SYS, value == 15 || value == 30 || value == 60 || value == 120 || value == 300 || value == 600, E_INVALID_ARG, "Out of range"); + + int ret = vconf_set_int(VCONFKEY_SETAPPL_LCD_TIMEOUT_NORMAL, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_LCD_TIMEOUT_NORMAL vconf"); + } + else if (key == _SOUND_SYSTEM_VOLUME) + { + return SetVolume(_SYSTEM_SOUND_VOLUME, value); + } + else if (key == _SOUND_MEDIA_VOLUME) + { + return SetVolume(_MEDIA_SOUND_VOLUME, value); + } + else if (key ==_SOUND_RINGTONE_VOLUME) + { + return SetVolume(_RINGTONE_SOUND_VOLUME, value); + } + else if (key == _SOUND_NOTIFICATION_VOLUME) + { + return SetVolume(_NOTIFICATION_SOUND_VOLUME, value); + } + else + { + return E_OBJ_NOT_FOUND; + } + return E_SUCCESS; +} + +result +_SettingManager::SetValue(const String& key, const String& value) +{ + result r = E_SUCCESS; + + if (key == _LOCALE_DATE_FORMAT + || key == _LOCALE_DATETIME_FORMAT + || key == _LOCALE_TIME_FORMAT ) + { + } + else if(key == _DEVICE_NAME) + { + char* deviceName = _StringConverter::CopyToCharArrayN(value); + SysTryReturnResult(NID_SYS, deviceName != null, E_SYSTEM, "Failed to convert String to string"); + + int err = vconf_set_str(VCONFKEY_SETAPPL_DEVICE_NAME_STR, deviceName); + delete [] deviceName; + SysTryReturnResult(NID_SYS, err == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_DEVICE_NAME_STR vconf"); + } + else if(key == _LOCALE_COUNTRY) + { + int err = 0; + std::unique_ptr lang (_StringConverter::CopyToCharArrayN(value)); + SysTryReturnResult(NID_SYS, lang != null, E_SYSTEM, "Failed to convert String to string"); + + icu::Locale locale(lang.get()); + err = locale.isBogus(); + SysTryReturnResult(NID_SYS, err == 0, E_INVALID_ARG, "Unknown language format"); + + std::string localeCode(locale.getLanguage()); + localeCode.append("_"); + localeCode.append(locale.getCountry()); + localeCode.append(".utf8"); + + err = vconf_set_str(VCONFKEY_REGIONFORMAT, localeCode.c_str()); + SysTryReturnResult(NID_SYS, err == 0, E_SYSTEM, "Failed to set on VCONFKEY_REGIONFORMAT vconf"); + } + else if(key == _LOCALE_LANGUAGE) + { + int err = 0; + std::unique_ptr lang (_StringConverter::CopyToCharArrayN(value)); + SysTryReturnResult(NID_SYS, lang != null, E_SYSTEM, "Failed to convert String to string"); + + icu::Locale locale(lang.get()); + err = locale.isBogus(); + SysTryReturnResult(NID_SYS, err == 0, E_INVALID_ARG, "Unknown language format"); + + std::string localeCode(locale.getLanguage()); + localeCode.append("_"); + localeCode.append(locale.getCountry()); + localeCode.append(".utf8"); + + err = vconf_set_str(VCONFKEY_LANGSET, localeCode.c_str()); + SysTryReturnResult(NID_SYS, err == 0, E_SYSTEM, "Failed to set on VCONFKEY_LANGSET vconf"); + } + else if(key == _LOCALE_WEEK_FORMAT_FIRSTDAY) + { + int firstDay = 0; + int ret = -1; + + if (value == _LOCALE_WEEK_FORMAT_FIRSTDAY_SUNDAY) + { + firstDay = _LOCALE_WEEK_FORMAT_VCONF_SUNDAY; + } + else if (value == _LOCALE_WEEK_FORMAT_FIRSTDAY_MONDAY) + { + firstDay = _LOCALE_WEEK_FORMAT_VCONF_MONDAY; + } + else + { + return E_INVALID_ARG; + } + + ret = vconf_set_int(VCONFKEY_SETAPPL_WEEKOFDAY_FORMAT_INT, firstDay); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_WEEKOFDAY_FORMAT_INT vconf"); + } + else if (key == _FONT_SIZE) + { + int fontSize = 0; + int res = 0; + + if (value == _FONT_SIZE_GIANT_LOWERCASE) + { + fontSize = _FONT_SIZE_GIANT_VCONF; + } + else if (value == _FONT_SIZE_HUGE_LOWERCASE) + { + fontSize = _FONT_SIZE_HUGE_VCONF; + } + else if (value == _FONT_SIZE_LARGE_LOWERCASE) + { + fontSize = _FONT_SIZE_LARGE_VCONF; + } + else if (value == _FONT_SIZE_MEDIUM_LOWERCASE) + { + fontSize = _FONT_SIZE_MEDIUM_VCONF; + } + else if (value == _FONT_SIZE_SMALL_LOWERCASE) + { + fontSize = _FONT_SIZE_SMALL_VCONF; + } + else + { + return E_UNSUPPORTED_OPERATION; + } + res = system_settings_set_value_int(SYSTEM_SETTINGS_KEY_FONT_SIZE, fontSize); + SysTryReturnResult(NID_SYS, res == SYSTEM_SETTINGS_ERROR_NONE, E_SYSTEM, "Failed to set font size"); + } + else if(key == _LOCALE_TIMEZONE) + { + r = E_SUCCESS; + std::unique_ptr pSupportedTimeZoneList(_LocaleManagerImpl::GetAvailableTimeZonesN()); + + SysTryReturnResult(NID_SYS, pSupportedTimeZoneList != null, E_SYSTEM, "It is failed to get supported timezone list."); + SysTryReturnResult(NID_SYS, pSupportedTimeZoneList->ContainsKey(value) == true, E_INVALID_ARG, "Specified timezone id[%S] is not valid", value.GetPointer()); + + std::unique_ptr tzpath (_StringConverter::CopyToCharArrayN(value)); + SysTryReturnResult(NID_SYS, tzpath != null, E_SYSTEM, "It is failed to convert String to string"); + std::string tzStr(_LOCALE_TIMEZONE_ROOT_PATH); + tzStr.append(tzpath.get()); + std::unique_ptr cstrTzpath (strdup(tzStr.c_str())); + int ret = sysman_set_timezone(cstrTzpath.get()); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "It is failed to set timezone"); + + ret = vconf_set_str(VCONFKEY_SETAPPL_TIMEZONE_ID, cstrTzpath.get()+_LOCALE_TIMEZONE_ROOT_PATH_LENGTH); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "It is failed to set VCONFKEY_SETAPPL_TIMEZONE_ID vconf"); + + ret = vconf_set_int(VCONFKEY_SYSTEM_TIME_CHANGED, -1); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "It is failed to notify to system about time changing"); + } + else if(key == _FONT_TYPE) + { + char* pFontType = null; + int res = 0; + + pFontType = _StringConverter::CopyToCharArrayN(value); + SysTryReturnResult(NID_SYS, pFontType != null, E_SYSTEM, "Failed to convert String to string"); + SysLog(NID_SYS, "Requested font type is %s.", pFontType); + res = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_FONT_TYPE, pFontType); + delete [] pFontType; + SysTryReturnResult(NID_SYS, res == SYSTEM_SETTINGS_ERROR_NONE, E_SYSTEM, "Failed to set font type"); + } + else if(key == _NETWORK_TELEPHONY_MODE) + { + _tmpNetworkTelephonyMode = value; + } + else if(key ==_NETWORK_WIFI_TETHERING_SECURITY_PASSWORD) + { + int ret = 0; + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + SysTryReturnResult(NID_SYS, __tetheringHandle != null, E_UNSUPPORTED_OPERATION, "Current device does not support tethering feature"); + std::unique_ptr password(_StringConverter::CopyToCharArrayN(value)); + SysTryReturnResult(NID_SYS, password != null, E_SYSTEM, "Failed to convert String to string"); + ret = tethering_wifi_set_passphrase(__tetheringHandle, password.get()); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to set password"); + } + else if(key == _SCREEN_MODE) + { + int ret = 0; + + + SysTryReturnResult(NID_SYS, value == _SCREEN_MODE_DYNAMIC || value == _SCREEN_MODE_STANDARD || value == _SCREEN_MODE_NATURAL || value == _SCREEN_MODE_MOVIE, E_INVALID_ARG, "designated value(%ls) is invalid", value.GetPointer()); + char* screenMode = _StringConverter::CopyToCharArrayN(value); + ret = vconf_set_str(_SCREEN_MODE_VCONFKEY, screenMode); + + if(ret == 0) + { + r = E_SYSTEM; + SysLog(NID_SYS, "Failed to change screen mode"); + } + if(screenMode != null) + { + delete [] screenMode; + } + } + else if(key == _SCREEN_WALLPAPER) + { + int ret = 0; + SysTryReturn(NID_SYS, File::IsFileExist(value) == true, E_FILE_NOT_FOUND, E_FILE_NOT_FOUND, "The entry for the specified wallpaper file or the file path cannot be found"); + std::unique_ptr pFilePath(_StringConverter::CopyToCharArrayN(value)); + + SysTryReturn(NID_SYS, pFilePath != null, E_SYSTEM, E_SYSTEM, "Failed to convert type of filePath"); + + ret = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN, pFilePath.get()); + SysTryReturn(NID_SYS, ret == 0, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set wallpaper of home screen"); + } + else if(key == _SCREEN_WALLPAPER_LOCK) + { + int ret = 0; + char* pFilePath = null; + + SysTryReturn(NID_SYS, File::IsFileExist(value) == true, E_FILE_NOT_FOUND, E_FILE_NOT_FOUND, "[E_FILE_NOT_FOUND] The entry for the specified wallpaper file or the file path cannot be found"); + pFilePath = _StringConverter::CopyToCharArrayN(value); + + SysTryReturn(NID_SYS, pFilePath != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to convert type of filePath"); + + ret = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN, const_cast(pFilePath)); + delete [] pFilePath; + SysTryReturn(NID_SYS, ret == 0, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set wallpaper of home screen"); + } + else if(key == _SOUND_RINGTONE) + { + int ret = 0; + char* pFilePath = null; + + SysTryReturn(NID_SYS, File::IsFileExist(value) == true, E_FILE_NOT_FOUND, E_FILE_NOT_FOUND, "[E_FILE_NOT_FOUND] The entry for the specified ringtone file or the file path cannot be found"); + pFilePath = _StringConverter::CopyToCharArrayN(value); + + SysTryReturn(NID_SYS, pFilePath != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to convert type of filePath"); + + ret = system_settings_set_value_string(SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE, const_cast(pFilePath)); + SysTryReturn(NID_SYS, ret == 0, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to set ringtone"); + + delete [] pFilePath; + } + else if(key == _STORAGE_DIRECTORY_WAP_DOWNLOAD) + { + _tmpStorageDirectoryWapDownload = value; + } + else if(key == _STORAGE_DIRECTORY_BLUETOOTH_DOWNLOAD) + { + _tmpStorageDirectoryWapDownload = value; + } + else if(key == _STORAGE_DIRECTORY_CAMERA_RECORD) + { + _tmpStorageDirectoryWapDownload = value; + } + else if(key == _STORAGE_DIRECTORY_VOICE_RECORD) + { + _tmpStorageDirectoryVoiceRecord = value; + } + else if(key == _STORAGE_DIRECTORY_RADIO_BROADCAST) + { + _tmpStorageDirectoryRadioBroadcast = value; + } + else if(key == _STORAGE_DIRECTORY_VIDEO_BROADCAST) + { + _tmpStorageDirectoryVideoBroadcast = value; + } + else + { + SysLog(NID_SYS, "required key(%ls) is not existed", key.GetPointer()); + r = E_OBJ_NOT_FOUND; + } + return r; +} + +result +_SettingManager::SetValueForPrivilegedKey(const String& key, String value) +{ + result r = E_SUCCESS; + if(key == _NETWORK_TELEPHONY_PROVIDER) + { + _tmpNetworkTelephonyProvider = value; + } + else if(key == _NETWORK_TELEPHONY_MODE) + { + _tmpNetworkTelephonyMode= value; + } + else + { + r = E_OBJ_NOT_FOUND; + } + return r; +} + +result +_SettingManager::SetValueAsyncForPrivilegedKey(const String& key, bool value, ISettingInfoSetValueAsyncResultListener* listener) +{ + int ret = -1; + + if(key == _NETWORK_FLIGHTMODE) + { + SysTryReturnResult(NID_SYS, __tapiHandle == null, E_SYSTEM, "Tapi is already ready"); + __tapiHandle = tel_init(null); + SysTryReturnResult(NID_SYS, __tapiHandle != null, E_SYSTEM, "Tapi is not ready."); + + if(__pSettingAsyncEvent == null) + { + _SettingAsyncEvent* pEvent = new (std::nothrow) _SettingAsyncEvent(); + SysTryReturnResult(NID_SYS, pEvent != null, E_OUT_OF_MEMORY, "It is failed to create instance of Event"); + __pSettingAsyncEvent = pEvent; + } + __pSettingAsyncEvent->AddListener(*listener); + + ret = tel_set_flight_mode(__tapiHandle, + value ? TAPI_POWER_FLIGHT_MODE_ENTER : TAPI_POWER_FLIGHT_MODE_LEAVE, + SettingEventFlightMode, (void*)__pSettingAsyncEvent); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "It is failed to set on Network Flight mode"); + } + + return E_SUCCESS; +} + +result +_SettingManager::SetValueForPrivilegedKey(const String& key, bool value) +{ + int ret = -1; + result r = E_SUCCESS; + if(key == _LOCATION_GPS) + { + if(value == true) + { + ret = vconf_set_int(VCONFKEY_LOCATION_ENABLED, 1); + } + else + { + ret = vconf_set_int(VCONFKEY_LOCATION_ENABLED, 0); + } + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_LOCATION_ENABLED vconf"); + } + else if(key == _LOCATION_WPS) + { + if(value == true) + { + ret = vconf_set_int(VCONFKEY_LOCATION_NETWORK_ENABLED, 1); + } + else + { + ret = vconf_set_int(VCONFKEY_LOCATION_NETWORK_ENABLED, 0); + } + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_LOCATION_NETWORK_ENABLED vconf"); + } + else if(key == _LOCATION_GPS_ADVANCED) + { + if(value == true) + { + ret = vconf_set_int(VCONFKEY_LOCATION_AGPS_ENABLED, 1); + } + else + { + ret = vconf_set_int(VCONFKEY_LOCATION_AGPS_ENABLED, 0); + } + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get on VCONFKEY_LOCATION_AGPS_ENABLED vconf"); + } + else if(key == _NETWORK_TELEPHONY_ROAMING) + { + ret = vconf_set_bool(VCONFKEY_SETAPPL_STATE_DATA_ROAMING_BOOL, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_STATE_DATA_ROAMING_BOOL vconf"); + } + else if(key == _NETWORK_TELEPHONY_PACKETSERVICE) + { + ret = vconf_set_bool(VCONFKEY_3G_ENABLE, value); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_3G_ENABLE vconf"); + } + else if(key == _NETWORK_WIFI) + { + int wifiState = 0; + bool supported = false; + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + SysTryReturnResult(NID_SYS, supported == true && r == E_SUCCESS, E_UNSUPPORTED_OPERATION, "Current device does not support Wi-Fi feature."); + + ret = vconf_get_int(VCONFKEY_WIFI_STATE, &wifiState); + SysTryReturnResult(NID_SYS, ret == 0, E_UNSUPPORTED_OPERATION, "Failed to set on VCONFKEY_WIFI_STATE vconf"); + SysTryReturnResult(NID_SYS, LoadWifiDll() == E_SUCCESS , E_SYSTEM,"Failed to get wifi so"); + + if(value == true) + { + if(wifiState == VCONFKEY_WIFI_OFF) + { + r = pWifiManagerImpl_Activate(); + } + } + else + { + if(wifiState != VCONFKEY_WIFI_OFF) + { + r = pWifiManagerImpl_Deactivate(); + } + + } + UnloadWifiDll(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to change wifi state."); + } + else if(key == _NETWORK_WIFI_DIRECT) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI_DIRECT, supported); + SysTryReturnResult(NID_SYS, supported == true, E_UNSUPPORTED_OPERATION, "Current device does not support WiFi direct feature"); + SysTryReturnResult(NID_SYS, LoadWifiDll() == E_SUCCESS , E_SYSTEM,"Failed to get wifi so"); + + bool isActivated = pWifiDirectDeviceImpl_IsActivated(); + + if (isActivated == false && value == true) + { + ret = pWifiDirectDeviceImpl_Activate(); + } + else if (isActivated == true && value == false) + { + ret = pWifiDirectDeviceImpl_Deactivate(); + } + UnloadWifiDll(); + SysTryReturnResult(NID_SYS, ret == E_SUCCESS, E_SYSTEM, "Failed to change Wi-Fi direct state"); + } + else if(key == _DEVELOPER_USBDEBUGGING) + { +#ifndef _OSP_EMUL_ + ret = vconf_set_bool(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, + value ? _DEVELOPER_USBDEBUGGING_ON : _DEVELOPER_USBDEBUGGING_OFF); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to set on VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL vconf"); +#else + r = E_UNSUPPORTED_OPERATION; +#endif + } + else + { + r = E_OBJ_NOT_FOUND; + } + return r; +} + +bool +_SettingManager::HasKey(const String& key) +{ + if(key == _BATTERY_FORMAT_PERCENTAGE) + { + return true; + } + else if(key == _FONT_SIZE) + { + return true; + } + else if(key == _FONT_TYPE) + { + return true; + } + else if(key == _LOCALE_COUNTRY) + { + return true; + } + else if(key == _LOCALE_DATE) + { + return true; + } + else if(key == _LOCALE_DATE_FORMAT) + { + return true; + } + else if(key == _LOCALE_DATETIME) + { + return true; + } + else if(key == _LOCALE_DATETIME_FORMAT) + { + return true; + } + else if(key == _LOCALE_LANGUAGE) + { + return true; + } + else if(key == _LOCALE_TIME) + { + return true; + } + else if(key == _LOCALE_TIME_FORMAT) + { + return true; + } + else if(key == _LOCALE_TIME_FORMAT_24HOUR) + { + return true; + } + else if(key == _LOCALE_TIMEZONE) + { + return true; + } + else if(key == _LOCALE_UPDATE_AUTO) + { + return true; + } + else if(key == _LOCALE_WEEK_FORMAT_FIRSTDAY) + { + return true; + } + else if(key == _LOCATION_GPS) + { + return true; + } + else if(key == _LOCATION_GPS_ADVANCED) + { + return true; + } + else if(key == _LOCATION_WPS) + { + return true; + } + else if(key == _MOTION_UI) + { + return true; + } + else if(key == _NETWORK_FLIGHTMODE) + { + return true; + } + else if(key == _NETWORK_TELEPHONY_MODE || key == _NETWORK_TELEPHONY_PACKETSERVICE || key == _NETWORK_TELEPHONY_PROVIDER || key == _NETWORK_TELEPHONY_ROAMING) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + + return supported; + } + else if(key == _NETWORK_WIFI) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + + return supported; + } + else if(key == _NETWORK_WIFI_NOTIFICATION) + { + int ret = 0; + int currentValue = 0; + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + if(supported == false) + { + return false; + } + ret = vconf_get_int(VCONFKEY_WIFI_ENABLE_QS, ¤tValue); + + if(ret == -1) + { + return false; + } + + return true; + } + else if(key == _NETWORK_WIFI_TETHERING) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + if(supported == false) + { + return false; + } + if(__tetheringHandle == null) + { + return false; + } + return true; + } + else if(key == _NETWORK_WIFI_TETHERING_HIDE) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + if(supported == false) + { + return false; + } + if(__tetheringHandle == null) + { + return false; + } + return true; + } + else if(key == _NETWORK_WIFI_TETHERING_SECURITY) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + if(supported == false) + { + return false; + } + if(__tetheringHandle == null) + { + return false; + } + return true; + } + else if(key == _NETWORK_WIFI_TETHERING_SECURITY_PASSWORD) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI, supported); + if(supported == false) + { + return false; + } + if(__tetheringHandle == null) + { + return false; + } + return true; + } + else if(key == _NETWORK_WIFI_DIRECT) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI_DIRECT, supported); + return supported; + } + else if(key == _NETWORK_BLUETOOTH) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_BLUETOOTH, supported); + return supported; + } + else if(key == _NETWORK_BLUETOOTH_TETHERING) + { + bool supported = false; + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI_DIRECT, supported); + + if(__tetheringHandle == null || supported == false) + { + return false; + } + return true; + } + else if(key == _SCREEN_WALLPAPER) + { + return true; + } + else if(key == _SCREEN_WALLPAPER_LOCK) + { + return true; + } + else if(key == _SCREEN_BRIGHTNESS) + { + return true; + } + else if(key == _SCREEN_BRIGHTNESS_AUTO) + { + return true; + } + else if(key == _SCREEN_MODE) + { + return true; + } + else if(key == _SCREEN_BACKLIGHT_TIME) + { + return true; + } + else if(key == _SOUND_LOCK) + { + return true; + } + else if(key == _SOUND_MEDIA_VOLUME) + { + return true; + } + else if(key == _SOUND_NOTIFICATION_VOLUME) + { + return true; + } + else if(key == _SOUND_RINGTONE) + { + return true; + } + else if(key == _SOUND_RINGTONE_VOLUME) + { + return true; + } + else if(key == _SOUND_SILENTMODE) + { + return true; + } + else if(key == _SOUND_SYSTEM_VOLUME) + { + return true; + } + else if(key == _SOUND_TOUCH) + { + return true; + } + else if(key == _STORAGE_DIRECTORY_WAP_DOWNLOAD) + { + return true; + } + else if(key == _STORAGE_DIRECTORY_BLUETOOTH_DOWNLOAD) + { + return true; + } + else if(key == _STORAGE_DIRECTORY_CAMERA_RECORD) + { + return true; + } + else if(key == _STORAGE_DIRECTORY_VOICE_RECORD) + { + return true; + } + else if(key == _STORAGE_DIRECTORY_RADIO_BROADCAST) + { + return true; + } + else if(key == _STORAGE_DIRECTORY_VIDEO_BROADCAST) + { + return true; + } + else if(key == _VIBRATOR) + { + return true; + } + else if(key == _VIBRATOR_LEVEL) + { + return true; + } + else if(key == _VIBRATOR_LEVEL_NOTIFICATION) + { + return true; + } + else if(key == _USB_TETHERING) + { + if(__tetheringHandle == null) + { + return false; + } + return true; + } + else if(key == _WEB_APPLICATION_COOKIE_SHARE) + { + return true; + } + else if(key == _SCREEN_ROTATION_AUTO) + { + return true; + } + else if(key == _CONTACT_ORDER_FIRSTNAME) + { + return true; + } + else if(key == _DEVELOPER_USBDEBUGGING) + { + return true; + } + return false; +} + +result +_SettingManager::ResetToFactoryDefault(void) +{ + return E_SUCCESS; +} + +result +_SettingManager::SetVolume(const String& soundCategory, int level) +{ + int res = 0; + int maxVolume = 0; + + sound_type_e soundType; + + if (soundCategory == _SYSTEM_SOUND_VOLUME) + { + soundType = SOUND_TYPE_SYSTEM; + } + else if (soundCategory == _MEDIA_SOUND_VOLUME) + { + soundType = SOUND_TYPE_MEDIA; + } + else if (soundCategory == _RINGTONE_SOUND_VOLUME) + { + soundType = SOUND_TYPE_RINGTONE; + } + else if (soundCategory == _NOTIFICATION_SOUND_VOLUME) + { + soundType = SOUND_TYPE_NOTIFICATION; + } + else + { + SysLogException(NID_SYS, E_INVALID_ARG, "The specified soundCategory is invalid"); + return E_INVALID_ARG; + } + + res = sound_manager_get_max_volume(soundType, &maxVolume); + SysTryReturn(NID_SYS, res == 0, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get max volume"); + + SysTryReturn(NID_SYS, maxVolume >= level, E_OUT_OF_RANGE, E_OUT_OF_RANGE, "[E_OUT_OF_RANGE] The specified level is outside the bounds of soundCategory"); + + res = sound_manager_set_volume(soundType, level); + SysTryReturn(NID_SYS, res == 0, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] A sy8stem error has occured."); + + return E_SUCCESS; +} + +//Event Management +result +_SettingManager::AddSettingEventListener(ISettingEventListener& listener) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_SYS, __pSettingEvent != null, E_SYSTEM, "Event system is not ready."); + r = __pSettingEvent->AddListener(listener); + SysTryReturnResult(NID_SYS, r != E_OBJ_ALREADY_EXIST, r, "listener is already registered."); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to add listener"); + __listenerCount++; + return StartSettingEventListen(); +} + +result +_SettingManager::RemoveSettingEventListener(ISettingEventListener& listener) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_SYS, __pSettingEvent != null, E_SYSTEM, "Event system is not ready."); + r = __pSettingEvent->RemoveListener(listener); + SysTryReturnResult(NID_SYS, r != E_OBJ_NOT_FOUND, r, "listener is not registered."); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to remove listener"); + __listenerCount--; + return StopSettingEventListen(); +} + +// Event for internal +result +_SettingManager::AddSettingEventListenerForInternal(ISettingEventListener& listener) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_SYS, __pSettingEventForInternal != null, E_SYSTEM, "Event system is not ready."); + __pSettingEventForInternal->AddListener(listener); + SysTryReturnResult(NID_SYS, r != E_OBJ_ALREADY_EXIST, r, "listener is already registered."); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "The memory is insufficient."); + if(__listenerInternalCount == 0) + { + r = StartSettingEventListenForInternal(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to start internal event."); + } + __listenerInternalCount++; + return r; +} + +result +_SettingManager::RemoveSettingEventListenerForInternal(ISettingEventListener& listener) +{ + result r = E_SUCCESS; + SysTryReturnResult(NID_SYS, __pSettingEventForInternal != null, E_SYSTEM, "Event system is not ready."); + r = __pSettingEventForInternal->RemoveListener(listener); + SysTryReturnResult(NID_SYS, r != E_OBJ_NOT_FOUND, r, "listener is not registered."); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "The listener is not added."); + __listenerInternalCount--; + + if(__listenerInternalCount == 0 && __listenerCount == 0) + { + r = StopSettingEventListenForInternal(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to stop internal event."); + } + return r; +} + +result +_SettingManager::StartSettingEventListenForInternal(void) +{ + if(__registeredSettingEventsForInternal == false) + { + int ret = 0; + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_REGION, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register region event listener"); + + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_LANGUAGE, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register language event listener"); + + ret = system_settings_set_changed_cb(SYSTEM_SETTINGS_KEY_FONT_TYPE, SettingEventSettingInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register font type event listener"); + + ret = system_settings_set_changed_cb(SYSTEM_SETTINGS_KEY_FONT_SIZE, SettingEventSettingInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register font size event listener"); + + __registeredSettingEventsForInternal = true; + } + return E_SUCCESS; +} + +result +_SettingManager::StopSettingEventListenForInternal(void) +{ + if(__registeredSettingEventsForInternal == true) + { + int ret = 0; + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_REGION); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_LANGUAGE); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + + ret = system_settings_unset_changed_cb(SYSTEM_SETTINGS_KEY_FONT_SIZE); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + + ret = system_settings_unset_changed_cb(SYSTEM_SETTINGS_KEY_FONT_TYPE); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + + __registeredSettingEventsForInternal = false; + } + return E_SUCCESS; +} + +result +_SettingManager::StartSettingEventListen(void) +{ + if (__listenerCount > 0 && __registeredSettingEvents == false) + { + int ret = 0; + result r = E_SUCCESS; + int currentIntValue = 0; + bool currentBoolValue = false; + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_24HOUR_CLOCK_FORMAT_ENABLED, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register 24 hour event listener"); + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_DATA_ROAMING_ENABLED, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register roaming event listener"); + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_FLIGHT_MODE_ENABLED, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register flight mode event listener"); + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_LOCATION_SERVICE_ENABLED, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register location service event listener"); + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_LOCATION_NETWORK_POSITION_ENABLED, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register network position event listener"); + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_PACKET_DATA_ENABLED, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register packet data event listener"); + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_SILENT_MODE_ENABLED, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register silent mode event listener"); + ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_VIBRATION_LEVEL_HAPTIC_FEEDBACK, SettingEventRuntimeInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register vibration event listener"); + ret = sound_manager_set_volume_changed_cb(SettingEventSoundManager, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register sound volume event listener"); + + ret = system_settings_set_changed_cb(SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE, SettingEventSettingInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register rington event listener"); + ret = system_settings_set_changed_cb(SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN, SettingEventSettingInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register wallpaper event listener"); + ret = system_settings_set_changed_cb(SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN, SettingEventSettingInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register wallpaper event listener"); + ret = system_settings_set_changed_cb(SYSTEM_SETTINGS_KEY_MOTION_ACTIVATION, SettingEventSettingInfo, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register wallpaper event listener"); + + if(__tetheringHandle != null) + { + ret = tethering_set_enabled_cb(__tetheringHandle, TETHERING_TYPE_USB, SettingEventTetheringEnabled, null); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to register USB Tethering event listener"); + + ret = tethering_set_enabled_cb(__tetheringHandle, TETHERING_TYPE_WIFI, SettingEventTetheringEnabled, null); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to register WIFI Tethering event listener"); + + ret = tethering_set_enabled_cb(__tetheringHandle, TETHERING_TYPE_BT, SettingEventTetheringEnabled, null); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to register BT Tethering event listener"); + + ret = tethering_set_disabled_cb(__tetheringHandle, TETHERING_TYPE_USB, SettingEventTetheringDisabled, null); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to register USB Tethering event listener"); + + ret = tethering_set_disabled_cb(__tetheringHandle, TETHERING_TYPE_WIFI, SettingEventTetheringDisabled, null); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to register WIFI Tethering event listener"); + + ret = tethering_set_disabled_cb(__tetheringHandle, TETHERING_TYPE_BT, SettingEventTetheringDisabled, null); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to register BT Tethering event listener"); + } + + ret = vconf_get_int(VCONFKEY_WIFI_ENABLE_QS, ¤tIntValue); + if(ret != -1) + { + ret = vconf_notify_key_changed(VCONFKEY_WIFI_ENABLE_QS, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register WIFI QS event listener"); + } + + ret = vconf_notify_key_changed(VCONFKEY_BT_STATUS, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register BT event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_WIFI_STATE, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register WIFI event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_LOCATION_AGPS_ENABLED, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register vibration enable event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register rotate lock event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register usb mode selection event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_STATE_AUTOMATIC_TIME_UPDATE_BOOL, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register automatic time update enable event"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_WEEKOFDAY_FORMAT_INT, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register first day of week event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_CONTACTS_SVC_NAME_DISPLAY_ORDER, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register contact display order event listener"); + + ret = vconf_notify_key_changed(VCONFKEY_SYSTEM_TIME_CHANGED, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register time event"); + + ret = vconf_get_int(VCONFKEY_MOBILE_HOTSPOT_SECURITY, ¤tIntValue); + if(ret != -1) + { + ret = vconf_notify_key_changed(VCONFKEY_MOBILE_HOTSPOT_SECURITY, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register mobile hotspot security event"); + } + + ret = vconf_get_int(VCONFKEY_MOBILE_HOTSPOT_HIDE, ¤tIntValue); + if(ret != -1) + { + ret = vconf_notify_key_changed(VCONFKEY_MOBILE_HOTSPOT_HIDE, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register mobile hotspot hide event"); + } + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_LCD_TIMEOUT_NORMAL, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register VCONFKEY_SETAPPL_LCD_TIMEOUT_NORMAL changed event"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register VCONFKEY_SETAPPL_LCD_BRIGHTNESS changed event"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT changed event"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_TIMEZONE_ID, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register VCONFKEY_SETAPPL_TIMEZONE_ID changed event"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT changed event"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_TOUCH_SOUNDS_BOOL, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register TOUCH_SOUNDS changed event"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_SOUND_LOCK_BOOL, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register SOUND_LOCK changed event"); + + ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register device name changed event"); + + ret = vconf_notify_key_changed(_SCREEN_MODE_VCONFKEY, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register screen mode changed event"); + + _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI_DIRECT, currentBoolValue); + + if(currentBoolValue == true) + { + ret = vconf_notify_key_changed(VCONFKEY_WIFI_DIRECT_STATE, SettingEventVConf, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register wifi direct changed event"); + } + + r = StartSettingEventListenForInternal(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to register internal events"); + + __registeredSettingEvents = true; + } + + return E_SUCCESS; +} + +result +_SettingManager::StopSettingEventListen(void) +{ + if (__listenerCount == 0 && __registeredSettingEvents == true) + { + int ret = 0; + int currentIntValue = 0; + bool currentBoolValue =false; + result r = E_SUCCESS; + + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_24HOUR_CLOCK_FORMAT_ENABLED); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_DATA_ROAMING_ENABLED); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_FLIGHT_MODE_ENABLED); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_LOCATION_SERVICE_ENABLED); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_LOCATION_NETWORK_POSITION_ENABLED); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_PACKET_DATA_ENABLED); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_SILENT_MODE_ENABLED); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_VIBRATION_LEVEL_HAPTIC_FEEDBACK); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + sound_manager_unset_volume_changed_cb(); + + ret = system_settings_unset_changed_cb(SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = system_settings_unset_changed_cb(SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = system_settings_unset_changed_cb(SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + ret = system_settings_unset_changed_cb(SYSTEM_SETTINGS_KEY_MOTION_ACTIVATION); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + + //3.0 extensions + if(__tetheringHandle != null) + { + ret = tethering_unset_enabled_cb(__tetheringHandle, TETHERING_TYPE_USB); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to unregister USB Tethering event listener"); + + ret = tethering_unset_enabled_cb(__tetheringHandle, TETHERING_TYPE_WIFI); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to unregister WIFI Tethering event listener"); + + ret = tethering_unset_enabled_cb(__tetheringHandle, TETHERING_TYPE_BT); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to unregister Bluetooth Tethering event listener"); + + ret = tethering_unset_disabled_cb(__tetheringHandle, TETHERING_TYPE_USB); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to unregister USB Tethering event listener"); + + ret = tethering_unset_disabled_cb(__tetheringHandle, TETHERING_TYPE_WIFI); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to unregister WIFI Tethering event listener"); + + ret = tethering_unset_disabled_cb(__tetheringHandle, TETHERING_TYPE_BT); + SysTryReturnResult(NID_SYS, ret == TETHERING_ERROR_NONE, E_SYSTEM, "Failed to unregister Bluetooth Tethering event listener"); + } + + ret = vconf_get_int(VCONFKEY_WIFI_ENABLE_QS, ¤tIntValue); + if(ret != -1) + { + ret = vconf_ignore_key_changed(VCONFKEY_WIFI_ENABLE_QS, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister WIFI QS event listener"); + } + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_TIMEZONE_ID, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister VCONFKEY_SETAPPL_TIMEZONE_ID changed event"); + + ret = vconf_ignore_key_changed(VCONFKEY_BT_STATUS, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister BT event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_WIFI_STATE, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister WIFI event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_LOCATION_AGPS_ENABLED, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister vibration enable event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister rotate lock event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister usb mode selection event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_STATE_AUTOMATIC_TIME_UPDATE_BOOL, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister automatic time update enable event"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_WEEKOFDAY_FORMAT_INT, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister first day of week event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_CONTACTS_SVC_NAME_DISPLAY_ORDER, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister contact display order event listener"); + + ret = vconf_ignore_key_changed(VCONFKEY_SYSTEM_TIME_CHANGED, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister time event"); + + ret = vconf_get_int(VCONFKEY_MOBILE_HOTSPOT_SECURITY, ¤tIntValue); + if(ret != -1) + { + ret = vconf_ignore_key_changed(VCONFKEY_MOBILE_HOTSPOT_SECURITY, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister mobile hotspot security event"); + } + + ret = vconf_get_int(VCONFKEY_MOBILE_HOTSPOT_HIDE, ¤tIntValue); + if(ret != -1) + { + ret = vconf_ignore_key_changed(VCONFKEY_MOBILE_HOTSPOT_HIDE, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister mobile hotspot hide event"); + } + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_LCD_TIMEOUT_NORMAL, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister VCONFKEY_SETAPPL_LCD_TIMEOUT_NORMAL changed event"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister VCONFKEY_SETAPPL_LCD_BRIGHTNESS changed event"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT changed event"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT changed event"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_TOUCH_SOUNDS_BOOL, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister TOUCH_SOUNDS changed event"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_SOUND_LOCK_BOOL, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister SOUND_LOCK changed event"); + + ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister device name changed event"); + + ret = vconf_ignore_key_changed(_SCREEN_MODE_VCONFKEY, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to unregister screen mode changed event"); + + r = _SystemInfoImpl::GetSysInfo(_SYSTEM_NETWORK_WIFI_DIRECT, currentBoolValue); + + if(r == E_SUCCESS && currentBoolValue == true) + { + ret = vconf_ignore_key_changed(VCONFKEY_WIFI_DIRECT_STATE, SettingEventVConf); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to register wifi direct changed event"); + } + + if(__listenerInternalCount == 0) + { + r = StopSettingEventListenForInternal(); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to register internal events"); + } + + __registeredSettingEvents = false; + } + return E_SUCCESS; +} + +result +_SettingManager::SetSettingEventListener(ISettingEventListener* pListener) +{ + result r = E_SUCCESS; + if (pListener != null) + { + __pSettingEventListener = pListener; + r = AddSettingEventListener(*pListener); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to add event listener"); + } + else + { + if (__pSettingEventListener == null) + { + SysLog(NID_SYS, "listener is not registered"); + return E_SUCCESS; + } + r = RemoveSettingEventListener(*__pSettingEventListener); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "It is failed to remove event listener"); + __pSettingEventListener = null; + } + return E_SUCCESS; +} + +//Event +void +_SettingManager::SettingEventRuntimeInfo(runtime_info_key_e key, void* userData) +{ + SysLog(NID_SYS, "SettingEventListener called [%d]", key); + + if(__pSettingManager == null) + { + SysLogException(NID_SYS, E_SYSTEM, "SettingManager is not initialized"); + return; + } + + String settingKey; + switch (key) + { + case RUNTIME_INFO_KEY_FLIGHT_MODE_ENABLED: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _NETWORK_FLIGHTMODE; + } + else + { + settingKey = _FLIGHT_MODE_ENABLED; + } + break; + case RUNTIME_INFO_KEY_LANGUAGE: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _LOCALE_LANGUAGE; + } + else + { + settingKey = _LANGUAGE; + } + break; + case RUNTIME_INFO_KEY_24HOUR_CLOCK_FORMAT_ENABLED: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + __pSettingManager->DeliverSettingEvent(_LOCALE_TIME_FORMAT); + __pSettingManager->DeliverSettingEvent(_LOCALE_DATETIME_FORMAT); + settingKey = _LOCALE_TIME_FORMAT_24HOUR; + } + else + { + __pSettingManager->DeliverSettingEvent(_DATE_TIME_FORMAT); + __pSettingManager->DeliverSettingEvent(_TIME_FORMAT); + settingKey = _HOUR_FORMAT_SELECTED; + } + break; + case RUNTIME_INFO_KEY_REGION: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _LOCALE_DATE_FORMAT; + } + else + { + settingKey = _DATE_FORMAT; + } + __pSettingManager->DeliverSettingEvent(settingKey); + + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _LOCALE_DATETIME_FORMAT; + } + else + { + settingKey = _DATE_TIME_FORMAT; + } + __pSettingManager->DeliverSettingEvent(settingKey); + + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _LOCALE_TIME_FORMAT; + } + else + { + settingKey = _TIME_FORMAT; + } + __pSettingManager->DeliverSettingEvent(settingKey); + + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _LOCALE_COUNTRY; + } + else + { + settingKey = _COUNTRY; + } + + break; + + case RUNTIME_INFO_KEY_DATA_ROAMING_ENABLED: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _NETWORK_TELEPHONY_ROAMING; + } + else + { + settingKey = _DATA_ROAMING_ENABLED; + } + break; + case RUNTIME_INFO_KEY_LOCATION_SERVICE_ENABLED: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _LOCATION_GPS; + } + else + { + settingKey = _GPS_ENABLED; + } + break; + case RUNTIME_INFO_KEY_LOCATION_NETWORK_POSITION_ENABLED: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _LOCATION_WPS; + } + else + { + settingKey = _WPS_ENABLED; + } + break; + case RUNTIME_INFO_KEY_PACKET_DATA_ENABLED: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _NETWORK_TELEPHONY_PACKETSERVICE; + } + else + { + settingKey = _PACKET_SERVICE_ALLOWED; + } + break; + case RUNTIME_INFO_KEY_SILENT_MODE_ENABLED: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _SOUND_SILENTMODE; + } + else + { + settingKey = _SILENT_MODE; + } + break; + case RUNTIME_INFO_KEY_VIBRATION_LEVEL_HAPTIC_FEEDBACK: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _VIBRATOR_LEVEL; + } + else + { + settingKey = _TOUCH_VIBRATION_LEVEL; + } + break; + default: + SysLog(NID_SYS, "NOT IMPLEMENTED"); + return; + } + + SysLog(NID_SYS, "Event(%ls) is deliverted.", settingKey.GetPointer()); + __pSettingManager->DeliverSettingEvent(settingKey); +} + +void +_SettingManager::SettingEventSettingInfo(system_settings_key_e key, void* userData) +{ + SysLog(NID_SYS, "System setting is changed[%d]", key); + + if(__pSettingManager == null) + { + SysLogException(NID_SYS, E_SYSTEM, "SettingManager is not initialized"); + return; + } + + String settingKey; + switch (key) + { + case SYSTEM_SETTINGS_KEY_MOTION_ACTIVATION: + { + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _MOTION_UI; + } + else + { + settingKey = _ENABLE_MOTION; + } + break; + } + case SYSTEM_SETTINGS_KEY_INCOMING_CALL_RINGTONE: + { + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _SOUND_RINGTONE; + } + else + { + settingKey = _RINGTONE; + } + break; + } + case SYSTEM_SETTINGS_KEY_WALLPAPER_HOME_SCREEN: + { + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _SCREEN_WALLPAPER; + } + else + { + settingKey = _WALLPAPER; + } + break; + } + case SYSTEM_SETTINGS_KEY_WALLPAPER_LOCK_SCREEN: + { + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _SCREEN_WALLPAPER_LOCK; + } + else + { + return; + } + break; + } + + case SYSTEM_SETTINGS_KEY_FONT_SIZE: + { + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _FONT_SIZE; + } + else + { + settingKey = _FONTSIZE; + } + break; + } + case SYSTEM_SETTINGS_KEY_FONT_TYPE: + { + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _FONT_TYPE; + } + else + { + settingKey = _FONTTYPE; + } + break; + } + default: + SysLog(NID_SYS, "NOT IMPLEMENTED"); + return; + } + + __pSettingManager->DeliverSettingEvent(settingKey); +} + +void +_SettingManager::SettingEventSoundManager(sound_type_e type, unsigned int volume, void* userData) +{ + SysLog(NID_SYS, "Sound Volume is changed [%d]", type); + + if(__pSettingManager == null) + { + SysLogException(NID_SYS, E_SYSTEM, "SettingManager is not initialized"); + return; + } + + String settingKey; + switch (type) + { + case SOUND_TYPE_SYSTEM: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _SOUND_SYSTEM_VOLUME; + } + else + { + settingKey = _SYSTEM_SOUND_VOLUME; + } + break; + case SOUND_TYPE_MEDIA: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _SOUND_MEDIA_VOLUME; + } + else + { + settingKey = _MEDIA_SOUND_VOLUME; + } + break; + case SOUND_TYPE_RINGTONE: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _SOUND_RINGTONE_VOLUME; + } + else + { + settingKey = _RINGTONE_SOUND_VOLUME; + } + break; + case SOUND_TYPE_NOTIFICATION: + if(!(_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())) + { + settingKey = _SOUND_NOTIFICATION_VOLUME; + } + else + { + settingKey = _NOTIFICATION_SOUND_VOLUME; + } + break; + default: + SysLog(NID_SYS, "NOT IMPLEMENTED"); + return; + } + + __pSettingManager->DeliverSettingEvent(settingKey); +} + +void +_SettingManager::SettingEventVConf(keynode_t* node, void* userData) +{ + SysLog(NID_SYS, "VConf change event is occured"); + + if(__pSettingManager == null) + { + SysLogException(NID_SYS, E_SYSTEM, "SettingManager is not initialized"); + return; + } + SysLog(NID_SYS, "Vconf is changed [%s]", vconf_keynode_get_name(node)); + + String settingKey; + + if (strcmp(VCONFKEY_SETAPPL_BATTERY_PERCENTAGE_BOOL, vconf_keynode_get_name(node)) == 0) + { + settingKey = _BATTERY_FORMAT_PERCENTAGE; + } + else if (strcmp(VCONFKEY_SETAPPL_VIBRATION_STATUS_BOOL, vconf_keynode_get_name(node)) == 0) + { + settingKey = _VIBRATOR; + } + else if (strcmp(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, vconf_keynode_get_name(node)) == 0) + { + settingKey = _SCREEN_ROTATION_AUTO; + } + else if (strcmp(VCONFKEY_SETAPPL_USB_DEBUG_MODE_BOOL, vconf_keynode_get_name(node)) == 0) + { + settingKey = _DEVELOPER_USBDEBUGGING; + } + else if (strcmp(VCONFKEY_SETAPPL_STATE_AUTOMATIC_TIME_UPDATE_BOOL, vconf_keynode_get_name(node)) == 0) + { + settingKey = _LOCALE_UPDATE_AUTO; + } + else if (strcmp(VCONFKEY_SETAPPL_WEEKOFDAY_FORMAT_INT, vconf_keynode_get_name(node)) == 0) + { + settingKey = _LOCALE_WEEK_FORMAT_FIRSTDAY; + } + else if (strcmp(VCONFKEY_CONTACTS_SVC_NAME_DISPLAY_ORDER, vconf_keynode_get_name(node)) == 0) + { + settingKey = _CONTACT_ORDER_FIRSTNAME; + } + else if (strcmp(VCONFKEY_SYSTEM_TIME_CHANGED, vconf_keynode_get_name(node)) == 0) + { + __pSettingManager->DeliverSettingEvent(_LOCALE_DATETIME); + __pSettingManager->DeliverSettingEvent(_LOCALE_DATE); + settingKey = _LOCALE_TIME; + } + else if (strcmp(VCONFKEY_SETAPPL_TIMEZONE_ID, vconf_keynode_get_name(node)) == 0) + { + settingKey = _LOCALE_TIMEZONE; + } + else if (strcmp(VCONFKEY_SETAPPL_DEVICE_NAME_STR, vconf_keynode_get_name(node)) == 0) + { + settingKey = _DEVICE_NAME; + } + else if (strcmp(VCONFKEY_LOCATION_AGPS_ENABLED, vconf_keynode_get_name(node)) == 0) + { + settingKey = _LOCATION_GPS_ADVANCED; + } + else if (strcmp(VCONFKEY_WIFI_STATE, vconf_keynode_get_name(node)) == 0) + { + int state = VCONFKEY_WIFI_OFF; + int ret = 0; + ret = vconf_get_int(VCONFKEY_WIFI_STATE, &state); + + if(ret == 0 && (state == VCONFKEY_WIFI_OFF || state == VCONFKEY_WIFI_UNCONNECTED)) + { + settingKey = _NETWORK_WIFI; + } + else + { + SysLog(NID_SYS, "It is not Wi-Fi on/off event."); + return; + } + } + else if (strcmp(VCONFKEY_BT_STATUS, vconf_keynode_get_name(node)) == 0) + { + settingKey = _NETWORK_BLUETOOTH; + } + else if (strcmp(VCONFKEY_MOBILE_HOTSPOT_SECURITY, vconf_keynode_get_name(node)) == 0) + { + settingKey = _NETWORK_WIFI_TETHERING_SECURITY; + } + else if (strcmp(VCONFKEY_MOBILE_HOTSPOT_HIDE, vconf_keynode_get_name(node)) == 0) + { + settingKey = _NETWORK_WIFI_TETHERING_HIDE; + } + else if (strcmp(VCONFKEY_WIFI_ENABLE_QS, vconf_keynode_get_name(node)) == 0) + { + settingKey = _NETWORK_WIFI_NOTIFICATION; + } + else if (strcmp(_SCREEN_MODE_VCONFKEY, vconf_keynode_get_name(node)) == 0) + { + settingKey = _SCREEN_MODE; + } + else if (strcmp(VCONFKEY_SETAPPL_TOUCH_SOUNDS_BOOL, vconf_keynode_get_name(node)) == 0) + { + settingKey = _SOUND_TOUCH; + } + else if (strcmp(VCONFKEY_SETAPPL_SOUND_LOCK_BOOL, vconf_keynode_get_name(node)) == 0) + { + settingKey = _SOUND_LOCK; + } + else if (strcmp(VCONFKEY_SETAPPL_NOTI_VIBRATION_LEVEL_INT, vconf_keynode_get_name(node)) == 0) + { + settingKey = _VIBRATOR_LEVEL_NOTIFICATION; + } + else if (strcmp(VCONFKEY_SETAPPL_LCD_TIMEOUT_NORMAL, vconf_keynode_get_name(node)) == 0) + { + settingKey = _SCREEN_BACKLIGHT_TIME; + } + else if (strcmp(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, vconf_keynode_get_name(node)) == 0) + { + settingKey = _SCREEN_BRIGHTNESS; + } + else if (strcmp(VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT, vconf_keynode_get_name(node)) == 0) + { + settingKey = _SCREEN_BRIGHTNESS_AUTO; + } + else if (strcmp(VCONFKEY_WIFI_DIRECT_STATE, vconf_keynode_get_name(node)) == 0) + { + int state = VCONFKEY_WIFI_DIRECT_DEACTIVATED; + int ret = 0; + ret = vconf_get_int(VCONFKEY_WIFI_DIRECT_STATE, &state); + SysLog(NID_SYS, "Wi-Fi Direct state is changed. %d", state); + if(ret == 0 && (state == VCONFKEY_WIFI_DIRECT_DEACTIVATED || state == VCONFKEY_WIFI_DIRECT_ACTIVATED)) + { + settingKey = _NETWORK_WIFI_DIRECT; + } + else + { + SysLog(NID_SYS, "It is not Wi-Fi direct on/off event. %d", state); + return; + } + } + else + { + return; + } + + __pSettingManager->DeliverSettingEvent(settingKey); +} + +void +_SettingManager::SettingEventTetheringEnabled(tethering_error_e err, tethering_type_e type, bool is_requested, void* data) +{ + if(__pSettingManager == null) + { + SysLogException(NID_SYS, E_SYSTEM, "SettingManager is not initialized"); + return; + } + + String settingKey; + switch(type) + { + case TETHERING_TYPE_USB: + settingKey = _USB_TETHERING; + break; + case TETHERING_TYPE_WIFI: + settingKey = _NETWORK_WIFI_TETHERING; + break; + case TETHERING_TYPE_BT: + settingKey = _NETWORK_BLUETOOTH_TETHERING; + break; + default: + return; + } + __pSettingManager->DeliverSettingEvent(settingKey); +} + +void +_SettingManager::SettingEventTetheringDisabled(tethering_error_e err, tethering_type_e type, tethering_disabled_cause_e cause,void* data) +{ + SettingEventTetheringEnabled(err, type, false, null); +} + +void +_SettingManager::DeliverSettingEvent(String keyName) +{ + if(__pSettingEvent != null) + { + _SettingEventArg* settingEventArg = new (std::nothrow) _SettingEventArg(); + if(settingEventArg == null) + { + SysLogException(NID_SYS, E_OUT_OF_MEMORY, "It is failed to create instance of _SettingEventArg"); + } + settingEventArg->KeyName = keyName; + __pSettingEvent->Fire(*settingEventArg); + } + + if(__listenerInternalCount > 0) + { + if(__pSettingEventForInternal != null) + { + _SettingEventArg* settingEventArgForInternal = new (std::nothrow) _SettingEventArg(); + if(settingEventArgForInternal == null) + { + SysLogException(NID_SYS, E_OUT_OF_MEMORY, "It is failed to create instance of _SettingEventArg"); + } + settingEventArgForInternal->KeyName = keyName; + + __pSettingEventForInternal->Fire(*settingEventArgForInternal); + } + } +} + +void +_SettingManager::SettingEventFlightMode(TapiHandle* handle, int res, void* data, void* user_data) +{ + SysLog(NID_SYS, "TAPI change event is occured"); + result r = E_SUCCESS; + int ret = 0; + + if(__pSettingManager == null) + { + SysLogException(NID_SYS, E_SYSTEM, "SettingManager is not initialized"); + return; + } + + if(__pSettingManager->__tapiHandle != handle) + { + SysLogException(NID_SYS, E_SYSTEM, "SettingManager is not initialized"); + return; + } + + SysLog(NID_SYS, "Flight mode changed"); + + switch (res) + { + case TAPI_POWER_FLIGHT_MODE_RESP_ON: + SysLog(NID_SYS, "success change flight mode on"); + + ret = vconf_set_bool(VCONFKEY_TELEPHONY_FLIGHT_MODE, true); + if (ret != 0) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to set on VCONFKEY_TELEPHONY_FLIGHT_MODE vconf"); + } + break; + case TAPI_POWER_FLIGHT_MODE_RESP_OFF: + SysLog(NID_SYS, "success change flight mode off"); + + ret = vconf_set_bool(VCONFKEY_TELEPHONY_FLIGHT_MODE, false); + if (ret != 0) + { + SysLogException(NID_SYS, E_SYSTEM, "Failed to set on VCONFKEY_TELEPHONY_FLIGHT_MODE vconf"); + } + break; + case TAPI_POWER_FLIGHT_MODE_RESP_FAIL: + default: + SysLogException(NID_SYS, E_SYSTEM, "Failed to change flight mode"); + r = E_SYSTEM; + } + + _SettingAsyncEvent* pEvent = (_SettingAsyncEvent*)user_data; + + if(pEvent != null) + { + _SettingAsyncEventArg* pSettingAsyncEventArg = new (std::nothrow) _SettingAsyncEventArg; + pSettingAsyncEventArg->Key = _NETWORK_FLIGHTMODE; + pSettingAsyncEventArg->errorCode = r; + pEvent->Fire(*pSettingAsyncEventArg); + } + + if(__pSettingManager->__tapiHandle != null) + { + tel_deinit(__pSettingManager->__tapiHandle); + __pSettingManager->__tapiHandle = null; + } + else + { + SysLogException(NID_SYS, E_SYSTEM, "TAPI is not ready"); + return; + } +} + +result +_SettingManager::LoadBluetoothDll() +{ + result r = E_SUCCESS; + if(__pBluetoothDllHandle == null) + { + __pBluetoothDllHandle = dlopen(_BLUETOOTH_LIBRARY_NAME, RTLD_LAZY); + SysTryReturnResult(NID_SYS, __pBluetoothDllHandle, E_SYSTEM, "It is failed to open bluetooth library."); + + pBluetoothManagerImpl_Activate = reinterpret_cast< result(*)(void)> (dlsym(__pBluetoothDllHandle, "_BluetoothManagerImpl_Activate")); + pBluetoothManagerImpl_Deactivate = reinterpret_cast< result(*)(void)> (dlsym(__pBluetoothDllHandle, "_BluetoothManagerImpl_Deactivate")); + + SysTryCatch(NID_SYS, pBluetoothManagerImpl_Activate != null, r = E_SYSTEM, E_SYSTEM, "It is failed to find _BluetoothManagerImpl_Activate method"); + SysTryCatch(NID_SYS, pBluetoothManagerImpl_Deactivate != null, r = E_SYSTEM, E_SYSTEM, "It is failed to find _BluetoothManagerImpl_Deactivate method"); + } +CATCH: + if(r != E_SUCCESS) + { + UnloadBluetoothDll(); + } + + return E_SUCCESS; +} + +void +_SettingManager::UnloadBluetoothDll() +{ + if (__pBluetoothDllHandle != null) + { + pBluetoothManagerImpl_Activate = null; + pBluetoothManagerImpl_Deactivate = null; + + dlclose(__pBluetoothDllHandle); + __pBluetoothDllHandle = null; + } +} + +result +_SettingManager::LoadWifiDll() +{ + result r = E_SUCCESS; + if (__pWifiDllHandle == null) + { + __pWifiDllHandle = dlopen(_WIFI_DIRECT_LIBRARY_NAME, RTLD_LAZY); + SysTryReturnResult(NID_SYS, __pWifiDllHandle, E_SYSTEM, "It is failed to open wifi library."); + + pWifiDirectDeviceImpl_Activate = reinterpret_cast< result(*)(void)> (dlsym(__pWifiDllHandle, "_WifiDirectDeviceImpl_Activate")); + pWifiDirectDeviceImpl_Deactivate = reinterpret_cast< result(*)(void)> (dlsym(__pWifiDllHandle, "_WifiDirectDeviceImpl_Deactivate")); + pWifiDirectDeviceImpl_IsActivated = reinterpret_cast< bool(*)(void)> (dlsym(__pWifiDllHandle, "_WifiDirectDeviceImpl_IsActivated")); + pWifiManagerImpl_Activate = reinterpret_cast< result(*)(void)> (dlsym(__pWifiDllHandle, "_WifiManagerImpl_Activate")); + pWifiManagerImpl_Deactivate = reinterpret_cast< result(*)(void)> (dlsym(__pWifiDllHandle, "_WifiManagerImpl_Deactivate")); + + SysTryCatch(NID_SYS, pWifiDirectDeviceImpl_Activate != null, r = E_SYSTEM, E_SYSTEM, "It is failed to find _WifiDirectDeviceImpl_Activate method"); + SysTryCatch(NID_SYS, pWifiDirectDeviceImpl_Deactivate != null, r = E_SYSTEM, E_SYSTEM, "It is failed to find _WifiDirectDeviceImpl_Deactivate method"); + SysTryCatch(NID_SYS, pWifiDirectDeviceImpl_IsActivated != null, r = E_SYSTEM, E_SYSTEM, "It is failed to find _WifiDirectDeviceImpl_IsActivated method"); + SysTryCatch(NID_SYS, pWifiManagerImpl_Activate != null, r = E_SYSTEM, E_SYSTEM, "It is failed to find _WifiManagerImpl_Activate method"); + SysTryCatch(NID_SYS, pWifiManagerImpl_Deactivate != null, r = E_SYSTEM, E_SYSTEM, "It is failed to find _WifiManagerImpl_Deactivate method"); + } +CATCH: + if(r != E_SUCCESS) + { + UnloadWifiDll(); + } + + return E_SUCCESS; +} + +void +_SettingManager::UnloadWifiDll() +{ + if (__pWifiDllHandle != null) + { + pWifiDirectDeviceImpl_Activate = null; + pWifiDirectDeviceImpl_Deactivate = null; + pWifiDirectDeviceImpl_IsActivated = null; + pWifiManagerImpl_Activate = null; + pWifiManagerImpl_Deactivate = null; + + dlclose(__pWifiDllHandle); + __pWifiDllHandle = null; + } +} + +} } // Tizen::System diff --git a/src/system/FSys_SettingManager.h b/src/system/FSys_SettingManager.h new file mode 100644 index 0000000..9e9b07d --- /dev/null +++ b/src/system/FSys_SettingManager.h @@ -0,0 +1,121 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SettingManager.h + * @brief This is the header file for _SettingManager class. + */ + +#ifndef _FSYSTEM_INTERNAL_SETTING_MANAGER_H_ +#define _FSYSTEM_INTERNAL_SETTING_MANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include "FSys_SettingIcu.h" + +namespace Tizen { namespace System +{ + +class _OSP_EXPORT_ _SettingManager + : public Tizen::Base::Object +{ +private: + _SettingManager(void); + virtual ~_SettingManager(void); + +public: + result GetValue(const Tizen::Base::String& key, bool& value); + result GetValue(const Tizen::Base::String& key, double& value); + result GetValue(const Tizen::Base::String& key, int& value); + result GetValue(const Tizen::Base::String& key, long long& value); + result GetValue(const Tizen::Base::String& key, Tizen::Base::String& value); + result GetValue(const Tizen::Base::String& key, Tizen::Base::UuId& value); + result SetSettingEventListener(ISettingEventListener* pListener); + result AddSettingEventListenerForInternal(ISettingEventListener& listener); + result RemoveSettingEventListenerForInternal(ISettingEventListener& listener); + result AddSettingEventListener(ISettingEventListener& listener); + result RemoveSettingEventListener(ISettingEventListener& listener); + + result GetValueForPrivilegedKey(const Tizen::Base::String& key, bool& value); + + bool HasKey(const Tizen::Base::String& key); + + result SetValue(const Tizen::Base::String& key, const bool& value); + result SetValue(const Tizen::Base::String& key, const int& value); + result SetValue(const Tizen::Base::String& key, const Tizen::Base::String& value); + + result SetValueForPrivilegedKey(const Tizen::Base::String& key, bool value); + result SetValueAsyncForPrivilegedKey(const Tizen::Base::String& key, bool value, ISettingInfoSetValueAsyncResultListener* listener); + result SetValueForPrivilegedKey(const Tizen::Base::String& key, Tizen::Base::String value); + + result ResetToFactoryDefault(void); + + static _SettingManager* GetInstance(void); + +private: + void DeliverSettingEvent(Tizen::Base::String keyName); + result SetVolume(const Tizen::Base::String& soundCategory, int level); + result StartSettingEventListen(void); + result StopSettingEventListen(void); + result StartSettingEventListenForInternal(void); + result StopSettingEventListenForInternal(void); + static void InitSettingManager(void); + result LoadWifiDll(); + void UnloadWifiDll(); + result LoadBluetoothDll(); + void UnloadBluetoothDll(); + + static void SettingEventRuntimeInfo(runtime_info_key_e key, void* userData); + static void SettingEventSettingInfo(system_settings_key_e key, void* userData); + static void SettingEventSoundManager(sound_type_e type, unsigned int volume, void* userData); + static void SettingEventVConf(keynode_t* node, void* userData); + static void SettingEventTetheringEnabled(tethering_error_e tetheringErr, tethering_type_e deviceType, bool isRequested, void* date); + static void SettingEventTetheringDisabled(tethering_error_e tetheringErr, tethering_type_e deviceType, tethering_disabled_cause_e tetheringCause, void* dati); + static void SettingEventFlightMode(TapiHandle* handle, int res, void* data, void* user_data); + +private: + ISettingEventListener* __pSettingEventListener; + Tizen::Base::Runtime::Event* __pSettingEvent; + int __listenerCount; + _SettingIcu __settingIcu; + bool __registeredSettingEvents; + haptic_device_h __hapticHandle; + TapiHandle* __tapiHandle; + tethering_h __tetheringHandle; + Tizen::Base::Runtime::Event* __pSettingAsyncEvent; + Tizen::Base::Runtime::Event* __pSettingEventForInternal; + int __listenerInternalCount; + static _SettingManager* __pSettingManager; + bool __registeredSettingEventsForInternal; + void* __pWifiDllHandle; + void* __pBluetoothDllHandle; +}; + +} } // Tizen::System + +#endif //_FSYSTEM_INTERNAL_SETTING_MANAGER_H_ diff --git a/src/system/FSys_SystemInfoImpl.cpp b/src/system/FSys_SystemInfoImpl.cpp new file mode 100644 index 0000000..6a30f6e --- /dev/null +++ b/src/system/FSys_SystemInfoImpl.cpp @@ -0,0 +1,1269 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SystemInfoImpl.cpp + * @brief This is the implementation file for _SystemInfoImpl class. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; +using namespace Tizen::Io; + +namespace Tizen { namespace System +{ + +static const wchar_t* _REGISTRY_PATH = L"/usr/etc/system-info.ini"; +static const wchar_t* _SYSTEM_INFO_SESSION = L"SystemInfo"; + +//Bluetooth +static const wchar_t* _BLUETOOTH = L"http://tizen.org/feature/network.bluetooth"; +static const wchar_t* _BLUETOOTH_SUPPORTED = L"BluetoothSupported"; + +//Camera +static const wchar_t* _CAMERA = L"http://tizen.org/feature/camera"; +static const wchar_t* _CAMERA_FRONT = L"http://tizen.org/feature/camera.front"; +static const wchar_t* _CAMERA_FRONT_FLASH = L"http://tizen.org/feature/camera.front.flash"; +static const wchar_t* _CAMERA_BACK = L"http://tizen.org/feature/camera.back"; +static const wchar_t* _CAMERA_BACK_FLASH = L"http://tizen.org/feature/camera.back.flash"; +static const wchar_t* _CAMERA_COUNT = L"CameraCount"; + +//Database +static const wchar_t* _DATABASE_ENCRYPTION = L"http://tizen.org/feature/database.encryption"; +static const char* _DATABASE_LIBRARY_PATH = "/usr/lib/libsqlite3.so.0"; +static const char* _DATABASE_ENCRYPTION_SYMBOL = "sqlite3_key"; + +//DUID +static const wchar_t* _DUID = L"http://tizen.org/system/duid"; +static const wchar_t* _DEVICE_ID = L"DUID"; + +//FM Radio +static const wchar_t* _FMRADIO = L"http://tizen.org/feature/fmradio"; +static const wchar_t* _FM_RADIO_SUPPORTED = L"FmRadioSupported"; + +//Keyboard +static const wchar_t* _KEYBOARD_TYPE = L"KeyboardType"; +static const wchar_t* _INPUT_KEYBOARD = L"http://tizen.org/feature/input.keyboard"; +static const wchar_t* _INPUT_KEYBOARD_LAYOUT = L"http://tizen.org/feature/input.keyboard.layout"; + +//Location +static const wchar_t* _LOCATION = L"http://tizen.org/feature/location"; +static const wchar_t* _GPS_SUPPORTED = L"GPSSupported"; +static const wchar_t* _LOCATION_GPS = L"http://tizen.org/feature/location.gps"; +static const wchar_t* _WPS_SUPPORTED = L"WPSSupported"; +static const wchar_t* _LOCATION_WPS = L"http://tizen.org/feature/location.wps"; + +//Microphone +static const wchar_t* _MICROPHONE = L"http://tizen.org/feature/microphone"; + +//Model name +static const wchar_t* _MODELNAME = L"http://tizen.org/system/model_name"; +static const wchar_t* _MODEL_NAME = L"ModelName"; + +//Multi point +static const wchar_t* _MULTIPOINTTOUCH_POINTCOUNT = L"http://tizen.org/feature/multi_point_touch.point_count"; +static const wchar_t* _MULTIPOINT_TOUCH_COUNT = L"MultiPointTouchCount"; + +//NFC +static const wchar_t* _NFC = L"http://tizen.org/feature/nfc"; +static const wchar_t* _NETWORK_NFC = L"http://tizen.org/feature/network.nfc"; +static const wchar_t* _NFC_SUPPORTED = L"NFCSupported"; + +//Opengles +static const wchar_t* _OPENGLES_TEXTUREFORMAT_UTC = L"http://tizen.org/feature/opengles.texture_format.utc"; +static const wchar_t* _OPENGLES_TEXTUREFORMAT_PTC = L"http://tizen.org/feature/opengles.texture_format.ptc"; +static const wchar_t* _OPENGLES_TEXTUREFORMAT_ETC = L"http://tizen.org/feature/opengles.texture_format.etc"; +static const wchar_t* _OPENGLES_TEXTUREFORMAT_3DC = L"http://tizen.org/feature/opengles.texture_format.3dc"; +static const wchar_t* _OPENGLES_TEXTUREFORMAT_ATC = L"http://tizen.org/feature/opengles.texture_format.atc"; +static const wchar_t* _OPENGLES_TEXTUREFORMAT_PVRTC = L"http://tizen.org/feature/opengles.texture_format.pvrtc"; + +static const wchar_t* _OPENGLES_VERSION_1_1 = L"http://tizen.org/feature/opengles.version.1_1"; +static const wchar_t* _OPENGLES_VERSION_2_0 = L"http://tizen.org/feature/opengles.version.2_0"; +static const wchar_t* _OPENGL_ES_VERSION = L"OpenGLESVersion"; + +//Platform name +static const wchar_t* _PLATFORM_NAME = L"http://tizen.org/system/platform.name"; + +//CPU +static const wchar_t* _PLATFORM_CORE_CPU_ARCH_ARMV6 = L"http://tizen.org/feature/platform.core.cpu.arch.armv6"; +static const wchar_t* _PLATFORM_CORE_CPU_ARCH_ARMV7 = L"http://tizen.org/feature/platform.core.cpu.arch.armv7"; +static const wchar_t* _PLATFORM_CORE_CPU_ARCH_X86 = L"http://tizen.org/feature/platform.core.cpu.arch.x86"; + +//FPU +static const wchar_t* _PLATFORM_CORE_FPU_ARCH_VFPV2 = L"http://tizen.org/feature/platform.core.fpu.arch.vfpv2"; +static const wchar_t* _PLATFORM_CORE_FPU_ARCH_VFPV3 = L"http://tizen.org/feature/platform.core.fpu.arch.vfpv3"; +static const wchar_t* _PLATFORM_CORE_FPU_ARCH_SSE2 = L"http://tizen.org/feature/platform.core.fpu.arch.sse2"; +static const wchar_t* _PLATFORM_CORE_FPU_ARCH_SSE3 = L"http://tizen.org/feature/platform.core.fpu.arch.sse3"; +static const wchar_t* _PLATFORM_CORE_FPU_ARCH_SSSE3 = L"http://tizen.org/feature/platform.core.fpu.arch.ssse3"; + +// Screen +static const wchar_t* _SCREEN_BPP = L"http://tizen.org/feature/screen.bpp"; +static const wchar_t* _SCREEN_BITS_PER_PIXEL = L"ScreenBitsPerPixel"; +static const wchar_t* _SCREEN_DESKTOPMODE = L"http://tizen.org/feature/screen.desktop_mode"; +static const wchar_t* _SCREEN_DPI = L"http://tizen.org/feature/screen.dpi"; +static const wchar_t* _SCREEN_HEIGHT = L"http://tizen.org/feature/screen.height"; +static const wchar_t* _SCREENHEIGHT = L"ScreenHeight"; +static const wchar_t* _SCREEN_WIDTH = L"http://tizen.org/feature/screen.width"; +static const wchar_t* _SCREENWIDTH = L"ScreenWidth"; +static const wchar_t* _SCREENDPI = L"ScreenDPI"; + +//HDMI RCA +static const wchar_t* _SCREEN_OUTPUT_HDMI = L"http://tizen.org/feature/screen.output.hdmi"; +static const wchar_t* _SCREEN_OUTPUT_RCA = L"http://tizen.org/feature/screen.output.rca"; +static const wchar_t* _TV_OUT_SUPPORTED = L"TvOutSupported"; + +//Sensors +static const wchar_t* _SENSOR_ACCELEROMETER = L"http://tizen.org/feature/sensor.accelerometer"; +static const wchar_t* _SENSOR_ACCELEROMETER_WAKEUP = L"http://tizen.org/feature/sensor.accelerometer.wakeup"; +static const wchar_t* _SENSOR_BAROMETER = L"http://tizen.org/feature/sensor.barometer"; +static const wchar_t* _SENSOR_BAROMETER_WAKEUP = L"http://tizen.org/feature/sensor.barometer.wakeup"; +static const wchar_t* _SENSOR_MAGNETOMETER = L"http://tizen.org/feature/sensor.magnetometer"; +static const wchar_t* _SENSOR_MAGNETOMETER_WAKEUP = L"http://tizen.org/feature/sensor.magnetometer.wakeup"; +static const wchar_t* _SENSOR_GYROSCOPE = L"http://tizen.org/feature/sensor.gyroscope"; +static const wchar_t* _SENSOR_GYROSCOPE_WAKEUP = L"http://tizen.org/feature/sensor.gyroscope.wakeup"; +static const wchar_t* _SENSOR_PHOTOMETER = L"http://tizen.org/feature/sensor.photometer"; +static const wchar_t* _SENSOR_PHOTOMETER_WAKEUP = L"http://tizen.org/feature/sensor.photometer.wakeup"; +static const wchar_t* _SENSOR_TILTMETER = L"http://tizen.org/feature/sensor.tiltmeter"; +static const wchar_t* _SENSOR_TILTMETER_WAKEUP = L"http://tizen.org/feature/sensor.tiltmeter.wakeup"; +static const wchar_t* _SENSOR_PROXIMITY = L"http://tizen.org/feature/sensor.proximity"; +static const wchar_t* _SENSOR_PROXIMITY_WAKEUP = L"http://tizen.org/feature/sensor.proximity.wakeup"; + +//VOIP +static const wchar_t* _SIP_VOIP = L"http://tizen.org/feature/sip.voip"; + +//Sound +static const wchar_t* _SOUND_MEDIA_VOLUME_MAX = L"http://tizen.org/system/sound.media.volume.resolution.max"; +static const wchar_t* _MAX_MEDIA_SOUND_VOLUME = L"MaxMediaSoundVolume"; +static const wchar_t* _SOUND_NOTIFICATION_VOLUME_MAX = L"http://tizen.org/system/sound.notification.volume.resolution.max"; +static const wchar_t* _MAX_NOTIFICATION_SOUND_VOLUME = L"MaxNotificationSoundVolume"; +static const wchar_t* _SOUND_RINGTONE_VOLUME_MAX = L"http://tizen.org/system/sound.ringtone.volume.resolution.max"; +static const wchar_t* _MAX_RINGTONE_SOUND_VOLUME = L"MaxRingtoneSoundVolume"; +static const wchar_t* _SOUND_SYSTEM_VOLUME_MAX = L"http://tizen.org/system/sound.system.volume.resolution.max"; +static const wchar_t* _MAX_SYSTEM_SOUND_VOLUME = L"MaxSystemSoundVolume"; + +//Speech Recognition +static const wchar_t* _SPEECH_RECOGNITION = L"http://tizen.org/feature/speech.recognition"; + +//Telephony +static const wchar_t* _TELEPHONY = L"http://tizen.org/feature/network.telephony"; +static const wchar_t* _TELEPHONY_SERVICE_GSM = L"http://tizen.org/feature/network.telephony.service.gsm"; +static const wchar_t* _TELEPHONY_SERVICE_GPRS = L"http://tizen.org/feature/network.telephony.service.gprs"; +static const wchar_t* _TELEPHONY_SERVICE_EDGE = L"http://tizen.org/feature/network.telephony.service.edge"; +static const wchar_t* _TELEPHONY_SERVICE_UMTS = L"http://tizen.org/feature/network.telephony.service.umts"; +static const wchar_t* _TELEPHONY_SERVICE_HSDPA = L"http://tizen.org/feature/network.telephony.service.hsdpa"; +static const wchar_t* _TELEPHONY_SERVICE_HSUPA = L"http://tizen.org/feature/network.telephony.service.hsupa"; +static const wchar_t* _TELEPHONY_SERVICE_HSPA = L"http://tizen.org/feature/network.telephony.service.hspa"; +static const wchar_t* _TELEPHONY_SERVICE_LTE = L"http://tizen.org/feature/network.telephony.service.lte"; +static const wchar_t* _TELEPHONY_SERVICE_CDMA = L"http://tizen.org/feature/network.telephony.service.cdma"; +static const wchar_t* _NETWORK_TYPE = L"NetworkType"; +static const wchar_t* _NETWORK_EMERGENCY = L"Emergency"; + +//USB +static const wchar_t* _USB_HOST = L"http://tizen.org/feature/usb.host"; +static const wchar_t* _USB_ACCESSORY = L"http://tizen.org/feature/usb.accessory"; + +//WIFI +static const wchar_t* _WIFI = L"http://tizen.org/feature/network.wifi"; +static const wchar_t* _WIFI_SUPPORTED = L"WiFiSupported"; +static const wchar_t* _WIFI_DIRECT_SUPPORTED = L"WiFiDirectSupported"; +static const wchar_t* _WIFI_DIRECT = L"http://tizen.org/feature/network.wifi.direct"; + +//Version +static const wchar_t* _PLATFORM_VERSION = L"http://tizen.org/feature/platform.version"; +static const wchar_t* _PLATFORM_NATIVE_API_VERSION = L"http://tizen.org/feature/platform.native.api.version"; +static const wchar_t* _PLATFORM_WEB_API_VERSION = L"http://tizen.org/feature/platform.web.api.version"; + +static const wchar_t* _WAC_VERSION = L"WACVersion"; +static const wchar_t* _SUPPORTED = L"Supported"; +static const wchar_t* _UNSUPPORTED = L"Unsupported"; + +result +_SystemInfoImpl::GetSysInfo(const String& key, String& value) +{ + int ret = 0; + result r = E_SYSTEM; + char* pValue = null; + + if (key == _NETWORK_TYPE) + { + sim_state_e simState; + ret = sim_get_state(&simState); + + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the SIM state"); + + if (simState == SIM_STATE_UNAVAILABLE) + { + value.Append(_NETWORK_EMERGENCY); + return E_SUCCESS; + } + + ret = system_info_get_value_string(SYSTEM_INFO_KEY_NETWORK_TYPE, &pValue); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_NETWORK_TYPE\"failed"); + + if(pValue == null) + { + value.Clear(); + return E_SUCCESS; + } + + r = StringUtil::Utf8ToString(pValue, value); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + } + else if (key == _DEVICE_ID || key == _DUID) + { + r = _DeviceId::GetId(value); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_SYSTEM, "Failed to get the key[%ls]", key.GetPointer()); + return E_SUCCESS; + } + else if (key == _MODEL_NAME || key == _MODELNAME) + { + ret = system_info_get_value_string(SYSTEM_INFO_KEY_MODEL, &pValue); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE && pValue, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_MODEL"); + + r = StringUtil::Utf8ToString(pValue, value); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + } + else if (key == _OPENGL_ES_VERSION) + { + ret = system_info_get_value_string(SYSTEM_INFO_KEY_OPENGLES_VERSION, &pValue); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE && pValue, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_OPENGLES_TEXTURE_FORMAT\"failed"); + + r = StringUtil::Utf8ToString(pValue, value); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + } + else if (key == _KEYBOARD_TYPE || key == _INPUT_KEYBOARD_LAYOUT) + { + ret = system_info_get_value_string(SYSTEM_INFO_KEY_KEYBOARD_TYPE, &pValue); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_KEYBOARD_TYPE\"failed"); + + if(pValue == null) + { + value.Clear(); + return E_SUCCESS; + } + + r = StringUtil::Utf8ToString(pValue, value); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + + if(key == _INPUT_KEYBOARD_LAYOUT) + { + value.ToLowerCase(); + } + } + else if (key == _WAC_VERSION) + { + value = ""; + return E_SUCCESS; + } + else if (key == _BLUETOOTH_SUPPORTED) + { + value.Clear(); + bool bluetoothSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_BLUETOOTH_SUPPORTED, &bluetoothSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__BLUETOOTH_SUPPORTED"); + if(bluetoothSupported == true) + { + value = _SUPPORTED; + } + else + { + value = _UNSUPPORTED; + } + + r = E_SUCCESS; + } + else if (key == _GPS_SUPPORTED) + { + value.Clear(); + bool gpsSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_GPS_SUPPORTED, &gpsSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__GPS_SUPPORTED"); + if(gpsSupported == true) + { + value = _SUPPORTED; + } + else + { + value = _UNSUPPORTED; + } + r = E_SUCCESS; + } + else if (key == _WIFI_SUPPORTED) + { + value.Clear(); + bool wiFiSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_WIFI_SUPPORTED, &wiFiSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__WIFI_SUPPORTED"); + if(wiFiSupported == true) + { + value = _SUPPORTED; + } + else + { + value = _UNSUPPORTED; + } + r = E_SUCCESS; + } + else if (key == _PLATFORM_VERSION) + { + char* pPlatformVersion = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_TIZEN_VERSION, &pPlatformVersion); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_PLATFORM_NAME\"failed"); + + r = StringUtil::Utf8ToString(pPlatformVersion, value); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + free(pPlatformVersion); + return r; + + } + else if (key == _PLATFORM_NAME) + { + ret = system_info_get_value_string(SYSTEM_INFO_KEY_PLATFORM_NAME, &pValue); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_PLATFORM_NAME\"failed"); + + r = StringUtil::Utf8ToString(pValue, value); + SysTryCatch(NID_SYS, r == E_SUCCESS, r = E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + } + else if (key == _PLATFORM_NATIVE_API_VERSION) + { + return E_OBJ_NOT_FOUND; + } + else if (key == _PLATFORM_WEB_API_VERSION) + { + return E_OBJ_NOT_FOUND; + } + else + { + r = GetFromRegistry(key, value); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_OBJ_NOT_FOUND, "Failed to get the key[%ls]", key.GetPointer()); + return E_SUCCESS; + } +CATCH: + if(pValue != null) + { + free(pValue); + } + return r; +} + + +result +_SystemInfoImpl::GetSysInfo(const String& key, int& value) +{ + int ret = -1; + result r = E_SUCCESS; + + if (key == _CAMERA_COUNT) + { + int cameraCount = 0; + ret = system_info_get_value_int(SYSTEM_INFO_KEY_CAMERA_COUNT, &cameraCount); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__CAMERA_COUNT"); + value = cameraCount; + } + else if (key == _SCREEN_BITS_PER_PIXEL ||key == _SCREEN_BPP) + { + int screenBitsPerPixel = 0; + ret = system_info_get_value_int(SYSTEM_INFO_KEY_SCREEN_BITS_PER_PIXEL, &screenBitsPerPixel); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__SCREEN_BITS_PER_PIXEL"); + value = screenBitsPerPixel; + } + else if (key == _SCREENHEIGHT || key == _SCREEN_HEIGHT) + { + int screenHeight = 0; + ret = system_info_get_value_int(SYSTEM_INFO_KEY_SCREEN_HEIGHT, &screenHeight); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__SCREEN_HEIGHT"); + value = screenHeight; + } + else if (key == _SCREENWIDTH || key == _SCREEN_WIDTH) + { + int screenWidth = 0; + ret = system_info_get_value_int(SYSTEM_INFO_KEY_SCREEN_WIDTH, &screenWidth); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__SCREEN_WIDTH"); + value = screenWidth; + } + else if (key == _SCREENDPI || key == _SCREEN_DPI) + { + int screenDPI = 0; + ret = system_info_get_value_int(SYSTEM_INFO_KEY_SCREEN_DPI, &screenDPI); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__SCREEN_DPI"); + value = screenDPI; + } + else if (key == _MAX_SYSTEM_SOUND_VOLUME || key == _SOUND_SYSTEM_VOLUME_MAX) + { + int maxVolume = 0; + int ret = sound_manager_get_max_volume(SOUND_TYPE_SYSTEM, &maxVolume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "Failed to get the max volume"); + value = maxVolume; + } + else if (key == _MAX_MEDIA_SOUND_VOLUME || key == _SOUND_MEDIA_VOLUME_MAX) + { + int maxVolume = 0; + int ret = sound_manager_get_max_volume(SOUND_TYPE_MEDIA, &maxVolume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "Failed to get the max volume"); + + value = maxVolume; + } + else if (key == _MAX_RINGTONE_SOUND_VOLUME || key == _SOUND_RINGTONE_VOLUME_MAX) + { + int maxVolume = 0; + int ret = sound_manager_get_max_volume(SOUND_TYPE_RINGTONE, &maxVolume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "Failed to get the max volume"); + + value = maxVolume; + } + else if (key == _MAX_NOTIFICATION_SOUND_VOLUME || key == _SOUND_NOTIFICATION_VOLUME_MAX) + { + int maxVolume = 0; + int ret = sound_manager_get_max_volume(SOUND_TYPE_NOTIFICATION, &maxVolume); + SysTryReturnResult(NID_SYS, ret == SOUND_MANAGER_ERROR_NONE, E_SYSTEM, "Failed to get the max volume"); + value = maxVolume; + } + else if (key == _MULTIPOINT_TOUCH_COUNT || key == _MULTIPOINTTOUCH_POINTCOUNT) + { + int multiPointTouchCount = 0; + ret = system_info_get_value_int(SYSTEM_INFO_KEY_MULTI_POINT_TOUCH_COUNT, &multiPointTouchCount); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the ISYSTEM_INFO_KEY_MULTI_POINT_TOUCH_COUNT"); + value = multiPointTouchCount; + } + else + { + r = GetFromRegistry(key, value); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_OBJ_NOT_FOUND, "Failed to get the key[%ls]", key.GetPointer()); + } + + return E_SUCCESS; +} + + +result +_SystemInfoImpl::GetSysInfo(const String& key, long long& value) +{ + return E_OBJ_NOT_FOUND; +} + + +result +_SystemInfoImpl::GetSysInfo(const String& key, double& value) +{ + return E_OBJ_NOT_FOUND; +} + + +result +_SystemInfoImpl::GetSysInfo(const String& key, bool& value) +{ + int ret = 0; + result r = E_SUCCESS; + + if (key == _BLUETOOTH_SUPPORTED || key == _BLUETOOTH) + { + bool bluetoothSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_BLUETOOTH_SUPPORTED, &bluetoothSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_BLUETOOTH_SUPPORTED"); + value = bluetoothSupported; + } + else if (key == _CAMERA) + { + int cameraCount = 0; + ret = system_info_get_value_int(SYSTEM_INFO_KEY_CAMERA_COUNT, &cameraCount); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY__CAMERA_COUNT"); + + if (cameraCount > 0) + { + value = true; + } + else + { + value = false; + } + } + else if (key == _CAMERA_FRONT) + { + bool frontCameraSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_FRONT_CAMERA_SUPPORTED, &frontCameraSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_FRONT_CAMERA_SUPPORTED"); + value = frontCameraSupported; + } + else if (key == _CAMERA_FRONT_FLASH) + { + bool frontCameraFlashSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_FRONT_CAMERA_FLASH_SUPPORTED, &frontCameraFlashSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_FRONT_CAMERA_FLASH_SUPPORTED"); + value = frontCameraFlashSupported; + } + else if (key == _CAMERA_BACK) + { + bool backCameraSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_BACK_CAMERA_SUPPORTED, &backCameraSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_FRONT_CAMERA_SUPPORTED"); + value = backCameraSupported; + } + else if ( key == _CAMERA_BACK_FLASH) + { + bool backCameraFlashSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_BACK_CAMERA_FLASH_SUPPORTED, &backCameraFlashSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_FRONT_CAMERA_FLASH_SUPPORTED"); + value = backCameraFlashSupported; + } + else if (key == _DATABASE_ENCRYPTION) + { +#ifndef _OSP_EMUL_ + void* handle = dlopen(_DATABASE_LIBRARY_PATH, RTLD_NOW); + SysTryReturnResult(NID_SYS, handle != null, E_SYSTEM, "Failed to open database library file"); + void* function = dlsym(handle, _DATABASE_ENCRYPTION_SYMBOL); + if (function != null) + { + value = true; + } + else + { + value = false; + } + dlclose(handle); +#else + value = true; +#endif + } + else if (key == _LOCATION) + { + bool gpsSupported = false; + bool wpsSupported = false; + + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_GPS_SUPPORTED, &gpsSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_GPS_SUPPORTED"); + wpsSupported = location_manager_is_supported_method(LOCATIONS_METHOD_WPS); + + if(gpsSupported == true || wpsSupported == true) + { + value = true; + } + else + { + value = false; + } + } + else if (key == _GPS_SUPPORTED || key == _LOCATION_GPS) + { + bool gpsSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_GPS_SUPPORTED, &gpsSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_GPS_SUPPORTED"); + value = gpsSupported; + } + else if (key == _WPS_SUPPORTED || key == _LOCATION_WPS) + { + bool wpsSupported = false; + wpsSupported = location_manager_is_supported_method(LOCATIONS_METHOD_WPS); + value = wpsSupported; + } + else if (key == _MICROPHONE) + { + bool micSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_MICROPHONE_SUPPORTED, &micSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_MICROPHONE_SUPPORTED"); + value = micSupported; + } + else if (key == _PLATFORM_CORE_CPU_ARCH_ARMV6) + { + char* cpu = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_CORE_CPU_ARCH, &cpu); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_CORE_CPU_ARCH\"failed"); + + if(strcmp(cpu, "ARMv6") == 0) + { + value = true; + } + else + { + value = false; + } + free(cpu); + } + else if (key == _PLATFORM_CORE_CPU_ARCH_ARMV7) + { + char* cpu = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_CORE_CPU_ARCH, &cpu); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_CORE_CPU_ARCH\"failed"); + + if(strcmp(cpu, "ARMv7") == 0) + { + value = true; + } + else + { + value = false; + } + free(cpu); + } + else if (key == _PLATFORM_CORE_CPU_ARCH_X86) + { + char* cpu = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_CORE_CPU_ARCH, &cpu); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_CORE_CPU_ARCH\"failed"); + + if(strcmp(cpu, "x86") == 0) + { + value = true; + } + else + { + value = false; + } + free(cpu); + } + else if (key == _PLATFORM_CORE_FPU_ARCH_VFPV2) + { + char* fpu = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_CORE_FPU_ARCH, &fpu); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_CORE_fPU_ARCH\"failed"); + + if(strcmp(fpu, "vfpv2") == 0) + { + value = true; + } + else + { + value = false; + } + free(fpu); + } + else if (key == _PLATFORM_CORE_FPU_ARCH_VFPV3) + { + char* fpu = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_CORE_FPU_ARCH, &fpu); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_CORE_fPU_ARCH\"failed"); + + if(strcmp(fpu, "vfpv3") == 0) + { + value = true; + } + else + { + value = false; + } + free(fpu); + } + else if (key == _PLATFORM_CORE_FPU_ARCH_SSE2) + { + char* fpu = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_CORE_FPU_ARCH, &fpu); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_CORE_fPU_ARCH\"failed"); + + if(strcmp(fpu, "sse2") == 0) + { + value = true; + } + else + { + value = false; + } + free(fpu); + } + else if (key == _PLATFORM_CORE_FPU_ARCH_SSE3) + { + char* fpu = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_CORE_FPU_ARCH, &fpu); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_CORE_fPU_ARCH\"failed"); + + if(strcmp(fpu, "sse3") == 0) + { + value = true; + } + else + { + value = false; + } + free(fpu); + } + else if (key == _PLATFORM_CORE_FPU_ARCH_SSSE3) + { + char* fpu = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_CORE_FPU_ARCH, &fpu); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_CORE_fPU_ARCH\"failed"); + + if(strcmp(fpu, "ssse3") == 0) + { + value = true; + } + else + { + value = false; + } + free(fpu); + } + else if (key == _WIFI_SUPPORTED || key == _WIFI) + { + bool wifiSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_WIFI_SUPPORTED, &wifiSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_WIFI_SUPPORTED"); + value = wifiSupported; + } + else if (key == _WIFI_DIRECT || key == _WIFI_DIRECT_SUPPORTED) + { + bool wifiDirectSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_WIFI_DIRECT_SUPPORTED, &wifiDirectSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_WIFI_DIRECT_SUPPORTED"); + value = wifiDirectSupported; + } + else if (key == _FM_RADIO_SUPPORTED || key == _FMRADIO) + { + bool fmRadioSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_FMRADIO_SUPPORTED, &fmRadioSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_FMRADIO_SUPPORTED"); + value = fmRadioSupported; + } + else if (key == _TV_OUT_SUPPORTED) + { + bool tvOutSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_TVOUT_SUPPORTED, &tvOutSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_TVOUT_SUPPORTED"); + value = tvOutSupported; + } + else if (key == _SCREEN_OUTPUT_RCA) + { + bool rcaSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_RCA_SUPPORTED, &rcaSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_RCA_SUPPORTED"); + value = rcaSupported; + } + else if (key == _SCREEN_OUTPUT_HDMI) + { + bool hdmiSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_HDMI_SUPPORTED, &hdmiSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_HDMI_SUPPORTED"); + value = hdmiSupported; + } + else if (key == _NFC_SUPPORTED || key == _NFC || key == _NETWORK_NFC) + { + bool nfcSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_NFC_SUPPORTED, &nfcSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_NFC_SUPPORTED"); + value = nfcSupported; + } + else if (key == _TELEPHONY) + { + sim_state_e simState; + ret = sim_get_state(&simState); + + if(ret == 0) + { + value = true; + } + else + { + value = false; + } + } + else if (key == _TELEPHONY_SERVICE_GSM || key == _TELEPHONY_SERVICE_GPRS || key == _TELEPHONY_SERVICE_EDGE + || key == _TELEPHONY_SERVICE_UMTS || key == _TELEPHONY_SERVICE_HSDPA || key == _TELEPHONY_SERVICE_HSUPA + || key == _TELEPHONY_SERVICE_HSPA || key == _TELEPHONY_SERVICE_LTE || key == _TELEPHONY_SERVICE_CDMA) + { + String telephonyInfo; + char* pValue = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_NETWORK_TYPE, &pValue); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_NETWORK_TYPE\"failed"); + + if(pValue == null) + { + value = false; + return E_SUCCESS; + } + + r = StringUtil::Utf8ToString(pValue, telephonyInfo); + if(r != E_SUCCESS) + { + free(pValue); + return E_SYSTEM; + } + telephonyInfo.ToLowerCase(); + if(key == _TELEPHONY_SERVICE_GSM && telephonyInfo.Contains("gsm")) + { + value = true; + } + else if(key == _TELEPHONY_SERVICE_GPRS && telephonyInfo.Contains("gprs")) + { + value = true; + } + else if(key == _TELEPHONY_SERVICE_EDGE && telephonyInfo.Contains("edge")) + { + value = true; + } + else if(key == _TELEPHONY_SERVICE_UMTS && telephonyInfo.Contains("umts")) + { + value = true; + } + else if(key == _TELEPHONY_SERVICE_HSDPA && telephonyInfo.Contains("hsdpa")) + { + value = true; + } + else if(key == _TELEPHONY_SERVICE_HSUPA && telephonyInfo.Contains("hsupa")) + { + value = true; + } + else if(key == _TELEPHONY_SERVICE_HSPA && telephonyInfo.Contains("hspa")) + { + value = true; + } + else if(key == _TELEPHONY_SERVICE_LTE && telephonyInfo.Contains("lte")) + { + value = true; + } + else if(key == _TELEPHONY_SERVICE_CDMA && telephonyInfo.Contains("cdma")) + { + value = true; + } + else + { + value = false; + } + free(pValue); + } + else if (key == _SENSOR_BAROMETER) + { + bool barometerSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_BAROMETER_SENSOR_SUPPORTED, &barometerSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_BAROMETER_SENSOR_SUPPORTED"); + value = barometerSupported; + } + else if (key == _SENSOR_BAROMETER_WAKEUP) + { + bool barometerWakeupSupported = false; + ret = sf_is_wakeup_supported(BAROMETER_SENSOR); + if(ret == 0) + { + barometerWakeupSupported = true; + } + value = barometerWakeupSupported; + } + else if (key == _SENSOR_ACCELEROMETER) + { + bool accelerometerSupported = false; + ret = sensor_is_supported(SENSOR_ACCELEROMETER, &accelerometerSupported); + SysTryReturnResult(NID_SYS, ret == SENSOR_ERROR_NONE, E_SYSTEM, "Failed to get the SENSOR_ACCELEROMETER"); + value = accelerometerSupported; + } + else if (key == _SENSOR_ACCELEROMETER_WAKEUP) + { + bool accelerometerWakeupSupported = false; + ret = sf_is_wakeup_supported(ACCELEROMETER_SENSOR); + if(ret == 0) + { + accelerometerWakeupSupported = true; + } + value = accelerometerWakeupSupported; + } + else if (key == _SENSOR_MAGNETOMETER) + { + bool magnetometerSupported = false; + ret = sensor_is_supported(SENSOR_MAGNETIC, &magnetometerSupported); + SysTryReturnResult(NID_SYS, ret == SENSOR_ERROR_NONE, E_SYSTEM, "Failed to get the SENSOR_MAGNETOMETER"); + value = magnetometerSupported; + } + else if (key == _SENSOR_MAGNETOMETER_WAKEUP) + { + bool magnetometerWakeupSupported = false; + ret = sf_is_wakeup_supported(GEOMAGNETIC_SENSOR); + if(ret == 0) + { + magnetometerWakeupSupported = true; + } + value = magnetometerWakeupSupported; + } + else if (key == _SENSOR_PHOTOMETER) + { + bool lightSupported = false; + ret = sensor_is_supported(SENSOR_LIGHT, &lightSupported); + SysTryReturnResult(NID_SYS, ret == SENSOR_ERROR_NONE, E_SYSTEM, "Failed to get the SENSOR_PHOTOMETER"); + value = lightSupported; + } + else if (key == _SENSOR_PHOTOMETER_WAKEUP) + { + bool photometerWakeupSupported = false; + ret = sf_is_wakeup_supported(LIGHT_SENSOR); + if(ret == 0) + { + photometerWakeupSupported = true; + } + value = photometerWakeupSupported; + } + else if (key == _SENSOR_GYROSCOPE) + { + bool gyroscopeSupported = false; + ret = sensor_is_supported(SENSOR_GYROSCOPE, &gyroscopeSupported); + SysTryReturnResult(NID_SYS, ret == SENSOR_ERROR_NONE, E_SYSTEM, "Failed to get the SENSOR_GYROSCOPE"); + value = gyroscopeSupported; + } + else if (key == _SENSOR_GYROSCOPE_WAKEUP) + { + bool gyroscopeWakeupSupported = false; + ret = sf_is_wakeup_supported(GYROSCOPE_SENSOR); + if(ret == 0) + { + gyroscopeWakeupSupported = true; + } + value = gyroscopeWakeupSupported; + } + else if (key == _SENSOR_PROXIMITY) + { + bool proximitySupported = false; + ret = sensor_is_supported(SENSOR_PROXIMITY, &proximitySupported); + SysTryReturnResult(NID_SYS, ret == SENSOR_ERROR_NONE, E_SYSTEM, "Failed to get the SENSOR_PROXIMITY"); + value = proximitySupported; + } + else if (key == _SENSOR_PROXIMITY_WAKEUP) + { + bool proximityWakeupSupported = false; + ret = sf_is_wakeup_supported(PROXIMITY_SENSOR); + if(ret == 0) + { + proximityWakeupSupported = true; + } + value = proximityWakeupSupported; + } + else if (key == _SENSOR_TILTMETER) + { + bool magnetometerSupported = false; + ret = sensor_is_supported(SENSOR_MAGNETIC, &magnetometerSupported); + SysTryReturnResult(NID_SYS, ret == SENSOR_ERROR_NONE, E_SYSTEM, "Failed to get the SENSOR_MAGNETOMETER"); + + bool accelerometerSupported = false; + ret = sensor_is_supported(SENSOR_ACCELEROMETER, &accelerometerSupported); + SysTryReturnResult(NID_SYS, ret == SENSOR_ERROR_NONE, E_SYSTEM, "Failed to get the SENSOR_ACCELEROMETER"); + + if(magnetometerSupported == true && accelerometerSupported == true) + { + value = true; + } + else + { + value = false; + } + } + else if (key == _SENSOR_TILTMETER_WAKEUP) + { + int magnetic = 0; + int accelerometer = 0; + magnetic = sf_is_wakeup_supported(GEOMAGNETIC_SENSOR); + accelerometer = sf_is_wakeup_supported(ACCELEROMETER_SENSOR); + if(magnetic == 0 && accelerometer == 0) + { + value = true; + } + else + { + value = false; + } + } + else if (key == _OPENGLES_VERSION_1_1) + { + char* pOpenglVersion = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_OPENGLES_VERSION, &pOpenglVersion); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE && pOpenglVersion, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_OPENGLES_VERSION\"failed"); + if(strcmp(pOpenglVersion, "1.1") != -1) + { + value = true; + } + else + { + value = false; + } + free(pOpenglVersion); + } + else if (key == _OPENGLES_VERSION_2_0) + { + char* pOpenglVersion = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_OPENGLES_VERSION, &pOpenglVersion); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE && pOpenglVersion, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_OPENGLES_VERSION\"failed"); + if(strcmp(pOpenglVersion + strlen(pOpenglVersion) - 3, "2.0") != -1) + { + value = true; + } + else + { + value = false; + } + free(pOpenglVersion); + } + else if(key == _OPENGLES_TEXTUREFORMAT_UTC || key == _OPENGLES_TEXTUREFORMAT_PTC || key == _OPENGLES_TEXTUREFORMAT_ETC + || key == _OPENGLES_TEXTUREFORMAT_3DC || key == _OPENGLES_TEXTUREFORMAT_ATC || key == _OPENGLES_TEXTUREFORMAT_PVRTC) + { + int ret = 0; + String openglesTexture; + + char* pTextureFormat = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_OPENGLES_TEXTURE_FORMAT, &pTextureFormat); + + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE && pTextureFormat, E_SYSTEM, "system_info_get_value_string : \"SYSTEM_INFO_KEY_OPENGLES_VERSION\"failed"); + + r = StringUtil::Utf8ToString(pTextureFormat, openglesTexture); + + if (r != E_SUCCESS) + { + free(pTextureFormat); + SysLog(NID_SYS, "Fail to convert string"); + } + + openglesTexture.ToUpperCase(); + if (key == _OPENGLES_TEXTUREFORMAT_UTC && openglesTexture.Contains(L"UTC") == true) + { + value = true; + } + else if (key == _OPENGLES_TEXTUREFORMAT_PTC && openglesTexture.Contains(L"PTC") == true) + { + value = true; + } + else if (key == _OPENGLES_TEXTUREFORMAT_ETC && openglesTexture.Contains(L"ETC") == true) + { + value = true; + } + else if (key == _OPENGLES_TEXTUREFORMAT_3DC && openglesTexture.Contains(L"3DC") == true) + { + value = true; + } + else if (key == _OPENGLES_TEXTUREFORMAT_ATC && openglesTexture.Contains(L"ATC") == true) + { + value = true; + } + else if (key == _OPENGLES_TEXTUREFORMAT_PVRTC && openglesTexture.Contains(L"PVRTC") == true) + { + value = true; + } + else + { + value = false; + } + } + else if (key == _SCREEN_DESKTOPMODE) + { + value = false; + } + else if (key == _SPEECH_RECOGNITION) + { + bool speechRecognitionSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_SPEECH_RECOGNITION_SUPPORTED, &speechRecognitionSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_SPEECH_RECOGNITION_SUPPORTED"); + value = speechRecognitionSupported; + } + else if (key == _SIP_VOIP) + { + bool sipVoipSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_SIP_VOIP_SUPPORTED, &sipVoipSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_SIP_VOIP_SUPPORTED"); + value = sipVoipSupported; + } + else if (key == _USB_HOST) + { + bool usbHostSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_USB_HOST_SUPPORTED, &usbHostSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_USB_HOST_SUPPORTED"); + value = usbHostSupported; + } + else if (key == _USB_ACCESSORY) + { + bool usbAccessorytSupported = false; + ret = system_info_get_value_bool(SYSTEM_INFO_KEY_USB_ACCESSORY_SUPPORTED, &usbAccessorytSupported); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "Failed to get the SYSTEM_INFO_KEY_USB_HOST_SUPPORTED"); + value = usbAccessorytSupported; + } + else if (key == _INPUT_KEYBOARD) + { + char* pKeyboardType = null; + ret = system_info_get_value_string(SYSTEM_INFO_KEY_KEYBOARD_TYPE, &pKeyboardType); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_KEYBOARD_TYPE\"failed"); + + value = false; + if(pKeyboardType != null) + { + if(strlen(pKeyboardType) > 0) + { + value = true; + } + } + free(pKeyboardType); + return r; + } + else + { + r = GetFromRegistry(key, value); + SysTryReturnResult(NID_SYS, r == E_SUCCESS, E_OBJ_NOT_FOUND, "Failed to get the key[%ls]", key.GetPointer()); + } + + return E_SUCCESS; +} + + +result +_SystemInfoImpl::GetSysInfo(const String& key, UuId& value) +{ + return E_OBJ_NOT_FOUND; +} + + +Collection::IList* +_SystemInfoImpl::GetSysInfoValuesN(const String& key, SystemInfoValueType type) +{ + SetLastResult(E_OBJ_NOT_FOUND); + return null; +} + +result +_SystemInfoImpl::GetPlatformVersion(String& platformVersion) +{ + result r = E_SUCCESS; + char* pPlatformVersion = null; + int ret = system_info_get_value_string(SYSTEM_INFO_KEY_TIZEN_VERSION, &pPlatformVersion); + SysTryReturnResult(NID_SYS, ret == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_TIZEN_VERSION_NAME\"failed"); + + r = StringUtil::Utf8ToString(pPlatformVersion, platformVersion); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + free(pPlatformVersion); + return r; +} + +result +_SystemInfoImpl::GetNativeApiVersion(String& nativeApiVersion) +{ + return GetFromRegistry(_PLATFORM_NATIVE_API_VERSION, nativeApiVersion); +} + +result +_SystemInfoImpl::GetWebApiVersion(String& webApiVersion) +{ + return GetFromRegistry(_PLATFORM_WEB_API_VERSION, webApiVersion); +} + +result +_SystemInfoImpl::GetImei(String& imei) +{ + result r = E_SUCCESS; + int error = -1; + char* pImei = null; + + error = system_info_get_value_string(SYSTEM_INFO_KEY_MOBILE_DEVICE_ID, &pImei); + SysTryReturnResult(NID_SYS, error == SYSTEM_INFO_ERROR_NONE, E_SYSTEM, "[E_SYSTEM] system_info_get_value_string : \"SYSTEM_INFO_KEY_MOBILE_DEVICE_ID\"failed"); + + r = StringUtil::Utf8ToString(pImei, imei); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] StringUtil::Utf8ToString failed", GetErrorMessage(r)); + free(pImei); + + return r; +} + +result +_SystemInfoImpl::GetFromRegistry(const String& key, String& value) +{ + result r = E_SUCCESS; + _RegistryImpl _reg; + String valStr; + + r = _reg.Construct(_REGISTRY_PATH, REG_OPEN_READ_ONLY, null); + SysTryReturnResult(NID_SYS, !IsFailed(r), r, " RegistryImpl construct Failed"); + + r = _reg.GetValue(_SYSTEM_INFO_SESSION, key, valStr); + SysTryReturnResult(NID_SYS, !IsFailed(r), r, " Registry GetValue Failed"); + + if(valStr == L"true" || valStr == L"false") + { + return E_OBJ_NOT_FOUND; + } + else + { + value = valStr; + } + + return E_SUCCESS; +} + +result +_SystemInfoImpl::GetFromRegistry(const String& key, int& value) +{ + result r = E_SUCCESS; + _RegistryImpl _reg; + String valStr; + r = _reg.Construct(_REGISTRY_PATH, REG_OPEN_READ_ONLY, null); + SysTryReturnResult(NID_SYS, !IsFailed(r), r, " RegistryImpl construct Failed"); + + r = _reg.GetValue(_SYSTEM_INFO_SESSION, key, valStr); + SysTryReturnResult(NID_SYS, !IsFailed(r), r, " Registry GetValue Failed"); + SysTryReturnResult(NID_SYS, !IsFailed(r), E_SYSTEM, " Registry GetValue Failed"); + r = Integer::Parse(valStr, value); + SysTryReturnResult(NID_SYS, !IsFailed(r), E_OBJ_NOT_FOUND, " Integer::Parse() Failed"); + return E_SUCCESS; +} + +result +_SystemInfoImpl::GetFromRegistry(const String& key, bool& value) +{ + result r = E_SUCCESS; + _RegistryImpl _reg; + String valStr; + r = _reg.Construct(_REGISTRY_PATH, REG_OPEN_READ_ONLY, null); + SysTryReturnResult(NID_SYS, !IsFailed(r), r, " RegistryImpl construct Failed"); + + r = _reg.GetValue(_SYSTEM_INFO_SESSION, key, valStr); + SysTryReturnResult(NID_SYS, !IsFailed(r), r, " Registry GetValue Failed"); + SysTryReturnResult(NID_SYS, !IsFailed(r), E_SYSTEM, " Registry GetValue Failed"); + if(valStr == L"true") + { + value = true; + } + else if(valStr == L"false") + { + value = false; + } + else + { + return E_OBJ_NOT_FOUND; + } + return E_SUCCESS; +} +_SystemInfoImpl* +_SystemInfoImpl::GetInstance(SystemInfo& systeminfo) +{ + return systeminfo.__pSystemInfoImpl; +} +const _SystemInfoImpl* +_SystemInfoImpl::GetInstance(const SystemInfo& systeminfo) +{ + return systeminfo.__pSystemInfoImpl; +} +} } // Tizen::System diff --git a/src/system/FSys_SystemResource.cpp b/src/system/FSys_SystemResource.cpp new file mode 100644 index 0000000..2de56f3 --- /dev/null +++ b/src/system/FSys_SystemResource.cpp @@ -0,0 +1,97 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SystemResource.cpp + * @brief This is the implementation for the _SystemResource class. + */ + +#include +#include + +#include +#include + +#include + +#include "FSys_SystemResource.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace System +{ + +_ResourceDomainId _RESOURCE_DOMAIN_ID_OSP = "osp"; + +_SystemResource* _SystemResource::__pSystemRsrc = null; + +_SystemResource::_SystemResource(void) +{ +} + + +_SystemResource::~_SystemResource(void) +{ +} + +void +_SystemResource::InitSystemResource(void) +{ + static _SystemResource systemResource; + __pSystemRsrc = &systemResource; +} + +_SystemResource* +_SystemResource::GetInstance(void) +{ + static pthread_once_t once_block = PTHREAD_ONCE_INIT; + if(__pSystemRsrc == null) + { + pthread_once(&once_block, InitSystemResource); + } + return __pSystemRsrc; +} + + +String +_SystemResource::GetString(_ResourceDomainId domainId, _ResourceId resourceId) const +{ + return String(dgettext(domainId, resourceId)); +} + +#define _L(r) # r + +String +_SystemResource::GetString(_SystemStringId id) const +{ + static const char* const systemStringTable[] = + { + _L(IDS_COM_INVALID), + _L(IDS_COM_SK_OK), + _L(IDS_COM_SK_CANCEL), + _L(IDS_COM_POP_SELECT_DEFAULT_APPLICATION), + _L(IDS_COM_POP_DEFAULT_APPLICATION), + _L(IDS_COM_POP_APPLICATION_TYPE), + }; + + return GetString(_RESOURCE_DOMAIN_ID_OSP, systemStringTable[id]); +} + +#undef _L + +} } // Tizen::System diff --git a/src/system/FSys_SystemTimeImpl.cpp b/src/system/FSys_SystemTimeImpl.cpp new file mode 100644 index 0000000..13b5070 --- /dev/null +++ b/src/system/FSys_SystemTimeImpl.cpp @@ -0,0 +1,225 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SystemTimeImpl.cpp + * @brief This is the implementation file for _SystemTimeImpl class. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Io; +using namespace Tizen::Locales; + +namespace Tizen { namespace System +{ + +_SystemTimeImpl::_SystemTimeImpl(void) +{ +} + +_SystemTimeImpl::~_SystemTimeImpl(void) +{ +} + +result +_SystemTimeImpl::GetUptime(TimeSpan& uptime) +{ + int ret = 0; + long long ticks = 0; + struct timespec timeSpec; + + ret = clock_gettime(CLOCK_MONOTONIC_RAW, &timeSpec); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the time "); + + ticks = (long long) timeSpec.tv_sec * 1000ll; + ticks += (long long) timeSpec.tv_nsec / 1000000ll; + uptime = TimeSpan(ticks); + + return E_SUCCESS; +} + +result +_SystemTimeImpl::GetCurrentTime(TimeMode timeMode, DateTime& currentTime) +{ + struct tm* pGmTime = null; + time_t currTime = 0; + TimeZone timeZone; + DateTime tempTime; + _LocaleManagerImpl* plm = null; + + time(&currTime); + + pGmTime = gmtime(&currTime); + SysTryReturnResult(NID_SYS, null != pGmTime, E_SYSTEM, "Failed to convert the time value to UTC time"); + + plm = new (std::nothrow) _LocaleManagerImpl(); + SysTryReturnResult(NID_SYS, null != plm, E_SYSTEM, "_LocaleManagerImpl instance must not be null"); + + timeZone = plm->GetSystemTimeZone(); + delete plm; + String timeZoneId = timeZone.GetId(); + int rawOffset = timeZone.GetRawOffset(); + int dstSavings = timeZone.GetDstSavings(); + SysLog(NID_SYS, "Time zone: %S, %d, %d", timeZoneId.GetPointer(), rawOffset, dstSavings); + + + tempTime.SetValue(pGmTime->tm_year + 1900, pGmTime->tm_mon + 1, pGmTime->tm_mday, pGmTime->tm_hour, pGmTime->tm_min, pGmTime->tm_sec); + + SysLog(NID_SYS, "Temp Time %d %d/%d, %d:%d:%d", tempTime.GetYear(), tempTime.GetMonth(), tempTime.GetDay(), tempTime.GetHour(), tempTime.GetMinute(), tempTime.GetSecond()); + + switch (timeMode) + { + case UTC_TIME: + currentTime.SetValue(tempTime); + break; + + case STANDARD_TIME: + currentTime = timeZone.UtcTimeToStandardTime(tempTime); + break; + + case WALL_TIME: + currentTime = timeZone.UtcTimeToWallTime(tempTime); + break; + + default: + break; + } + + SysLog(NID_SYS, "Current Time %d %d/%d, %d:%d:%d", currentTime.GetYear(), currentTime.GetMonth(), currentTime.GetDay(), currentTime.GetHour(), currentTime.GetMinute(), currentTime.GetSecond()); + + return E_SUCCESS; +} + +result +_SystemTimeImpl::GetCurrentTime(DateTime& currentTime) +{ + return GetCurrentTime(UTC_TIME, currentTime); +} + +result +_SystemTimeImpl::SetCurrentTime(const DateTime& currentTime) +{ + result r = E_SUCCESS; + + ArrayList requestMessage; + ArrayList responseMessage; + char datetime[32] = {0,}; + + LocaleManager localeManager; + localeManager.Construct(); + TimeZone timeZone = localeManager.GetSystemTimeZone(); + + DateTime wallTime = timeZone.UtcTimeToWallTime(currentTime); + + std::unique_ptr<_IpcClient> pIpcClient(new (std::nothrow) _IpcClient()); + r = pIpcClient->Construct(_COMMUNICATION_DISPATCHER_IPC_ID); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] Fail to create IpcClient", GetErrorMessage(r)); + + requestMessage.Construct(); + responseMessage.Construct(); + + String serviceId = _SYSTEM_SERVICE_ID; + String commandId = _SYSTEM_COMMAND_CHANGE_TIME ; + String dateTime; + + sprintf(datetime, "%03d %02d %02d %02d:%02d:%02d", wallTime.GetYear() - 1900, wallTime.GetMonth()-1, wallTime.GetDay(), wallTime.GetHour(), wallTime.GetMinute(), wallTime.GetSecond()); + dateTime.Append(datetime); + + requestMessage.Add(serviceId); + requestMessage.Add(commandId); + requestMessage.Add(dateTime); + + std::unique_ptr pMsg (new (std::nothrow) IoService_Request(requestMessage, &responseMessage)); + SysTryReturnResult(NID_SYS, pMsg != null, E_SYSTEM, "[E_SYSTEM] fail to create Ipc message"); + + r = pIpcClient->SendRequest(pMsg.get()); + SysTryReturn(NID_SYS, r == E_SUCCESS, E_SYSTEM, r, "[%s] Fail to ipc message", GetErrorMessage(r)); + + String* pResult = (String*)responseMessage.GetAt(_SYSTEM_RESPONSE_DATA); + + SysTryReturnResult(NID_SYS, pResult != null, E_SYSTEM, "[E_SYSTEM] fail to receive Ipc response"); + SysTryReturnResult(NID_SYS, *pResult != _SYSTEM_RESULT_PRIVILEGED, E_PRIVILEGE_DENIED, "[E_PRIVILEGE_DENIED] applciation does not have proper privilege."); + SysTryReturnResult(NID_SYS, *pResult == _SYSTEM_RESULT_OK, E_SYSTEM, "[E_SYSTEM] fail to set time"); + + vconf_sync_key(VCONFKEY_SYSTEM_TIME_CHANGED); + + return r; +} +result +_SystemTimeImpl::GetTicks(long long& ticks) +{ + int ret = 0; + struct timeval timeValue; + + ret = gettimeofday(&timeValue, null); + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get the date and Time"); + + ticks = (long long) timeValue.tv_sec * 1000ll; + ticks += (long long) timeValue.tv_usec / 1000ll; + + return E_SUCCESS; +} + +result +_SystemTimeImpl::GetNanoTicks(long long& nanoTicks) +{ + int ret = 0; + struct timespec realTime; + + ret = clock_gettime(CLOCK_MONOTONIC_RAW, &realTime); + + SysTryReturnResult(NID_SYS, ret == 0, E_SYSTEM, "Failed to get clock information"); + + nanoTicks = (long long) realTime.tv_sec * 1000000000; + nanoTicks += (long long) realTime.tv_nsec; + + return E_SUCCESS; +} + +_SystemTimeImpl* +_SystemTimeImpl::GetInstance(SystemTime& systemtime) +{ + return systemtime.__pSystemTimeImpl; +} + +const _SystemTimeImpl* +_SystemTimeImpl::GetInstance(const SystemTime& systemtime) +{ + return systemtime.__pSystemTimeImpl; +} + + +} } // Tizen::System diff --git a/src/system/FSys_Types.h b/src/system/FSys_Types.h new file mode 100644 index 0000000..66d8033 --- /dev/null +++ b/src/system/FSys_Types.h @@ -0,0 +1,23 @@ +#ifndef _FSYS_INTERNAL_TYPES_H_ +#define _FSYS_INTERNAL_TYPES_H_ + +namespace Tizen { namespace System +{ + +static const wchar_t* _COMMUNICATION_DISPATCHER_IPC_ID = L"osp.app.ipcserver.communicationdispatcher"; +static const wchar_t* _SYSTEM_SERVICE_ID = L"osp.system.service"; +static const wchar_t* _SYSTEM_COMMAND_CHANGE_TIME = L"osp.system.command.change.time"; +static const wchar_t* _SYSTEM_COMMAND_CHANGE_BRIGHTNESS = L"osp.system.command.change.brightness"; +static const wchar_t* _SYSTEM_COMMAND_RESTORE_BRIGHTNESS = L"osp.system.command.restore.brightness"; +static const wchar_t* _SYSTEM_COMMAND_GET_IMEI= L"osp.system.command.get.imei"; +static const wchar_t* _SYSTEM_RESULT_OK = L"osp.system.result.ok"; +static const wchar_t* _SYSTEM_RESULT_ERROR = L"osp.system.result.error"; +static const wchar_t* _SYSTEM_RESULT_INVALID = L"osp.system.result.invalid"; +static const wchar_t* _SYSTEM_RESULT_PRIVILEGED = L"osp.system.result.privilege"; +const int _SYSTEM_RESPONSE_DATA = 2; + +static const int _BATTERY_LEVEL_FULL = 100; + +}} + +#endif diff --git a/src/system/FSys_VibratorImpl.cpp b/src/system/FSys_VibratorImpl.cpp new file mode 100644 index 0000000..a2d9713 --- /dev/null +++ b/src/system/FSys_VibratorImpl.cpp @@ -0,0 +1,399 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_VibratorImpl.cpp + * @brief This is the implementation file for _VibratorImpl class. + */ + +#include +#include + +#include +#include +#include + +#include + +namespace Tizen { namespace System +{ +namespace +{ +static const haptic_dev_idx INDEX_SYSTEM_VIBRATOR = DEV_IDX_ALL; +static const unsigned int MODE_SYSTEM_VIBRATION = 0; +static const int LEVEL_SYSTEM_VIBRATION = -1; +static const long INVALID_PERIOD = 0L; +static const int INVALID_COUNT = -1; +static const int INVALID_LEVEL = -1; + +inline bool +IsNegative(const int value) +{ + return value < 0; +} + +template inline bool +IsCreated(const T* pT) +{ + return pT != null; +} + +template inline void +SafeDelete(T*& rpT) +{ + if (IsCreated(rpT)) + { + delete rpT; + rpT = null; + } +} + +result +InitializeVibrator(Handle& handle) +{ + result r = E_SUCCESS; + + Handle deviceHandle = device_haptic_open(INDEX_SYSTEM_VIBRATOR, MODE_SYSTEM_VIBRATION); + if (IsNegative(deviceHandle)) + { + SysAssertf(false, "device_haptic_open() failed. [index:%d, mode:%d, result:%d]", INDEX_SYSTEM_VIBRATOR, MODE_SYSTEM_VIBRATION, deviceHandle); + + r = E_SYSTEM; + SysLogException(NID_SYS, r, "[%s] Vibrator initialize operation has failed. [result:%d]", GetErrorMessage(r), deviceHandle); + return r; + } + + handle = deviceHandle; + + return r; +} + +result +FinalizeVibrator(Handle& handle) +{ + result r = E_SUCCESS; + + if (handle != INVALID_HANDLE) + { + int deviceResult = device_haptic_close(handle); + if (IsNegative(deviceResult)) + { + SysAssertf(false, "device_haptic_close() failed. [handle:%d, result:%d]", handle, deviceResult); + + r = E_SYSTEM; + SysLogException(NID_SYS, r, "[%s] Vibrator finalize operation has failed. [result:%d]", GetErrorMessage(r), deviceResult); + return r; + } + + handle = INVALID_HANDLE; + } + + return r; +} + +result +StartVibration(const Handle handle, const long onPeriod, const int level) +{ + result r = E_SUCCESS; + int aLevel = (level == 0) ? LEVEL_SYSTEM_VIBRATION : level; + SysLog(NID_SYS, "Vibrator Action level: %d", aLevel); + + int deviceResult = device_haptic_play_monotone_with_detail_feedback_level(handle, onPeriod, (level == 0) ? LEVEL_SYSTEM_VIBRATION : level); + if (IsNegative(deviceResult)) + { + SysAssertf(false, "device_haptic_play_monotone_with_detail_feedback_level() failed. [handle:%d, duration:%ld, level:%d, result:%d]", handle, onPeriod, level, deviceResult); + + r = E_SYSTEM; + SysLogException(NID_SYS, r, "[%s] Vibration start operation has failed. [handle:%d, duration:%ld, level:%d, result:%d]", GetErrorMessage(r), handle, onPeriod, level, deviceResult); + return r; + } + + return r; +} + +result +StopVibration(const Handle handle) +{ + result r = E_SUCCESS; + + int deviceResult = device_haptic_stop_play(handle); + if (IsNegative(deviceResult)) + { + SysAssertf(false, "device_haptic_stop_play() failed. [handle:%d, result:%d]", handle, deviceResult); + + r = E_SYSTEM; + SysLogException(NID_SYS, r, "[%s] Vibration stop operation has failed. [handle:%d, result:%d]", GetErrorMessage(r), handle, deviceResult); + return r; + } + + return r; +} +} // Anonymous + + +const _VibratorImpl::VibrationInformation _VibratorImpl::__INVALID_VIBRATION_INFORMATION = { + INVALID_PERIOD, // on period + INVALID_PERIOD, // off period + INVALID_COUNT, // count + INVALID_LEVEL, // level + false, // is vibrating? + true, // is finished? +}; + +_VibratorImpl::_VibratorImpl(void) + : __handle(INVALID_HANDLE) + , __pTimer(null) + , __vibrationInformation(_VibratorImpl::__INVALID_VIBRATION_INFORMATION) +{ + +} + +_VibratorImpl::~_VibratorImpl(void) +{ + Destruct(); +} + +result +_VibratorImpl::Construct(void) +{ + SysAssertf(__handle == INVALID_HANDLE, "_VibratorImpl was already constructed. [handle:%d]", __handle); + + + result r = E_SUCCESS; + + Tizen::Base::Runtime::Timer* pTimer = new (std::nothrow) Tizen::Base::Runtime::Timer(); + if (!IsCreated(pTimer)) + { + r = E_OUT_OF_MEMORY; + SysLogException(NID_SYS, r, "[%s] Timer allocation failed.", GetErrorMessage(r)); + return r; + } + + r = pTimer->Construct(*this); + if (IsFailed(r)) + { + SafeDelete(pTimer); + return r; + } + + r = InitializeVibrator(__handle); + if (IsFailed(r)) + { + SafeDelete(pTimer); + return r; + } + + __pTimer = pTimer; + + return r; +} + +void +_VibratorImpl::Destruct(void) +{ + if (!__vibrationInformation.isFinished) + { + Stop(); + } + + SafeDelete(__pTimer); + + if (__handle != INVALID_HANDLE) + { + FinalizeVibrator(__handle); + } +} + +result +_VibratorImpl::Start(long onPeriod, long offPeriod, int count, int level) +{ + SysAssertf(__handle != INVALID_HANDLE, "_VibratorImpl was not constructed."); + + + // If (is vibrating) + // Stop current vibration immediately + // + // Prepare vibration information + // + // Start vibration(=> This vibration just one repeat) + // + // Start repetition timer(=> Remaining vibration be started by timer) + // + // Modify vibration information + result r = E_SUCCESS; + + if (!__vibrationInformation.isFinished) + { + r = Stop(); + if (IsFailed(r)) + { + return r; + } + + __vibrationInformation = _VibratorImpl::__INVALID_VIBRATION_INFORMATION; + } + + __vibrationInformation.onPeriod = onPeriod; + __vibrationInformation.offPeriod = offPeriod; + __vibrationInformation.count = count; + __vibrationInformation.level = level; + + r = StartVibration(__handle, __vibrationInformation.onPeriod, __vibrationInformation.level); + if (IsFailed(r)) + { + __vibrationInformation = _VibratorImpl::__INVALID_VIBRATION_INFORMATION; + return r; + } + + r = __pTimer->Start(__vibrationInformation.onPeriod); + if (IsFailed(r)) + { + r = E_DEVICE_FAILED; + SysLogException(NID_SYS, r, "[%s] Repetition timer starting failed.", GetErrorMessage(r)); + StopVibration(__handle); + __vibrationInformation = _VibratorImpl::__INVALID_VIBRATION_INFORMATION; + return r; + } + + __vibrationInformation.isVibrating = true; + __vibrationInformation.isFinished = false; + __vibrationInformation.count--; + + return r; +} + +result +_VibratorImpl::Stop(void) +{ + SysAssertf(__handle != INVALID_HANDLE, "_VibratorImpl was not constructed."); + + + // If (is not vibrating) + // { + // return + // } + // + // Cancel timer(=> for block another repetition) + // + // Stop current vibration + // + // Initialize vibration information + result r = E_SUCCESS; + + if (__vibrationInformation.isFinished) + { + r = E_DEVICE_FAILED; + SysLogException(NID_SYS, r, "[%s] Vibrator was already stopped.", GetErrorMessage(r)); + return r; + } + + r = __pTimer->Cancel(); + SysTryLog(NID_SYS, !IsFailed(r), "[%s] This canceling started just after timer has expired.", GetErrorMessage(r)); + + r = StopVibration(__handle); + if (IsFailed(r)) + { + return r; + } + + __vibrationInformation = _VibratorImpl::__INVALID_VIBRATION_INFORMATION; + + return r; +} + +_VibratorImpl* +_VibratorImpl::GetInstance(Vibrator& vibrator) +{ + return vibrator.__pVibratorImpl; +} + +const _VibratorImpl* +_VibratorImpl::GetInstance(const Vibrator& vibrator) +{ + return vibrator.__pVibratorImpl; +} + +void +_VibratorImpl::OnTimerExpired(Tizen::Base::Runtime::Timer& timer) +{ + // If (is end of repetition) + // { + // Initialize vibration information + // return + // } + // + // If (is end of vibration) + // { + // Start waiting + // return + // } + // + // If (is end of waiting) + // { + // Start vibration + // return + // } + if (__vibrationInformation.count == 0) + { + __vibrationInformation = _VibratorImpl::__INVALID_VIBRATION_INFORMATION; + return; + } + + + result r = E_SUCCESS; + + if (__vibrationInformation.isVibrating) + { + // off period + __vibrationInformation.isVibrating = false; + + r = timer.Start(__vibrationInformation.offPeriod); + if (IsFailed(r)) + { + SysLog(NID_SYS, "Vibration waiting failed."); + goto CATCH; + } + } + else + { + // on period + r = StartVibration(__handle, __vibrationInformation.onPeriod, __vibrationInformation.level); + if (IsFailed(r)) + { + goto CATCH; + } + + r = __pTimer->Start(__vibrationInformation.onPeriod); + if (IsFailed(r)) + { + SysLog(NID_SYS, "Vibration re-starting failed."); + StopVibration(__handle); + goto CATCH; + } + + __vibrationInformation.isVibrating = true; + __vibrationInformation.count--; + } + + return; + +CATCH: + SysLogException(NID_UIX, r, "[%s] Critical error occurred! Vibration was stopped.", GetErrorMessage(r)); + __vibrationInformation = _VibratorImpl::__INVALID_VIBRATION_INFORMATION; +} + +} } // Tizen::System diff --git a/src/system/inc/FSys_AlarmImpl.h b/src/system/inc/FSys_AlarmImpl.h new file mode 100644 index 0000000..82eb426 --- /dev/null +++ b/src/system/inc/FSys_AlarmImpl.h @@ -0,0 +1,110 @@ + // +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_AlarmImpl.h + * @brief This is the header file for _AlarmImpl class. + */ + +#ifndef _FSYSTEM_INTERNAL_ALARM_IMPL_H_ +#define _FSYSTEM_INTERNAL_ALARM_IMPL_H_ + +#include +#include +#include +#include + +#include + +namespace Tizen { namespace Base +{ + +namespace Collection { +class ArrayList; +} +}} + +namespace Tizen { namespace Io +{ +class _IpcClient; +}} + +namespace Tizen { namespace System +{ + +class _OSP_EXPORT_ _AlarmImpl + : public Tizen::Base::Object + , public Tizen::Io::_IIpcClientEventListener +{ +public: + _AlarmImpl(Alarm* pAlarm); + + result Construct(void); + + virtual ~_AlarmImpl(); + + result Set(const Tizen::Base::DateTime& startTime, int period, const Tizen::Base::DateTime* pEndTime); + + result Cancel(void); + + const Tizen::Base::DateTime GetStartTime(void) const; + + int GetPeriod(void) const; + + const Tizen::Base::DateTime* GetEndTime(void) const; + + result SetAlarmEventListener(IAlarmEventListener* pListener); + + void OnAlarmExpired(int alarmId); + + void OnIpcResponseReceived(Tizen::Io::_IpcClient& client, const IPC::Message& message); + + void OnDataReceived(const Tizen::Base::Collection::ArrayList& data); + + Tizen::Io::_IpcClient* GetIpcClient(void); + + static _AlarmImpl* GetInstance(Alarm* pAlarm); + + static const _AlarmImpl* GetInstance(const Alarm* pAlarm); + +private: + _AlarmImpl(const _AlarmImpl& alarmImpl); + + _AlarmImpl& operator =(const _AlarmImpl& alarmImpl); + +private: + Tizen::Io::_IpcClient* __pIpcClient; + + Tizen::Base::Integer __period; + + Tizen::Base::Integer* __pAlarmId; + + Tizen::Base::DateTime __startTime; + + Tizen::Base::DateTime* __pEndTime; + + Tizen::Base::Runtime::Event* __pEvent; + + Alarm* __pAlarm; + + +}; + + +} } // Tizen::Sys + +#endif //_FSYSTEM_INTERNAL_ALARM_IMPL_H_ diff --git a/src/system/inc/FSys_DeviceManagerEventProvider.h b/src/system/inc/FSys_DeviceManagerEventProvider.h new file mode 100644 index 0000000..c1b1099 --- /dev/null +++ b/src/system/inc/FSys_DeviceManagerEventProvider.h @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_DeviceManagerEventProvider.h + * @brief This is the header file for the _DeviceManagerEventProvider class. + */ + +#ifndef _FSYS_INTERNAL_DEVICEMANAGER_EVENT_PROVIDER_H_ +#define _FSYS_INTERNAL_DEVICEMANAGER_EVENT_PROVIDER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +class _IDeviceManagerEventProvider; + +/** + * @class _DeviceManagerEventProvider + * @brief This class provides device event for service. + * + */ +class _OSP_EXPORT_ _DeviceManagerEventProvider + : public Tizen::Base::Object +{ + +public: + static _DeviceManagerEventProvider* GetInstance(void); + + void SetIDeviceManageEventProvider(_IDeviceManagerEventProvider* listener); + +private: + /** + * This is the default constructor for this class. + */ + _DeviceManagerEventProvider(void); + + /** + * This is the default destructor for this class. + */ + virtual ~_DeviceManagerEventProvider(void); + + static void InitDeviceManagerEventProvider(void); + +private: + + _IDeviceManagerEventProvider* __pListener; + + static _DeviceManagerEventProvider* __pDeviceManagerEventProvider; +}; + +} } + +#endif //_FSYS_INTERNAL_DEVICEMANAGER_EVENT_PROVIDER_H_ diff --git a/src/system/inc/FSys_EnvironmentImpl.h b/src/system/inc/FSys_EnvironmentImpl.h new file mode 100644 index 0000000..bf4a115 --- /dev/null +++ b/src/system/inc/FSys_EnvironmentImpl.h @@ -0,0 +1,62 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_EnvironmentImpl.h + * @brief This is the header file for the %_EnvironmentImpl class. + * + * This header file contains the declarations of the %_EnvironmentImpl class. + */ + +#ifndef _FSYS_INTERNAL_ENVIRONMENT_IMPL_H_ +#define _FSYS_INTERNAL_ENVIRONMENT_IMPL_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +class _OSP_EXPORT_ _EnvironmentImpl + : public Tizen::Base::Object +{ + +public: + static Tizen::Base::String GetMediaPath(void); + + static Tizen::Base::String GetDefaultDownloadPath(void); + + static Tizen::Base::String GetExternalStoragePath(void); + + static Tizen::Base::String GetOspCompatSharedPath(void); + + static Tizen::Base::String GetPredefinedPath(PredefinedDirectoryType dirType); + +private: + _EnvironmentImpl(void); + + virtual ~_EnvironmentImpl(void); + + _EnvironmentImpl(const _EnvironmentImpl& rhs); + + _EnvironmentImpl& operator =(const _EnvironmentImpl& rhs); + +}; // _EnvironmentImpl + +}} // Tizen::System + +#endif // _FSYS_INTERNAL_ENVIRONMENT_IMPL_H_ diff --git a/src/system/inc/FSys_IDeviceManagerEventListener.h b/src/system/inc/FSys_IDeviceManagerEventListener.h new file mode 100644 index 0000000..60b7ebd --- /dev/null +++ b/src/system/inc/FSys_IDeviceManagerEventListener.h @@ -0,0 +1,48 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_IDeviceManagerEventListener.h + * @brief This is the header file for the _IDeviceManagerEventListener class. + */ + +#ifndef _FSYS_INTERNAL_DEVICEMANAGER_EVENT_LISTENER_H_ +#define _FSYS_INTERNAL_DEVICEMANAGER_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @class _IDeviceManagerEventListener + * @brief This interface is the listener of the device event for service. + * + */ +class _OSP_EXPORT_ _IDeviceManagerEventListener + : public Tizen::Base::Runtime::IEventListener +{ + +public: + virtual ~_IDeviceManagerEventListener(void) {} + virtual void OnBluetoothEventOccured(int code) = 0; +}; + +} } + +#endif //_FSYS_INTERNAL_DEVICEMANAGER_EVENT_LISTENER_H_ diff --git a/src/system/inc/FSys_IPowerManagerEventListener.h b/src/system/inc/FSys_IPowerManagerEventListener.h new file mode 100644 index 0000000..8f02dc8 --- /dev/null +++ b/src/system/inc/FSys_IPowerManagerEventListener.h @@ -0,0 +1,66 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_IPowerManagerEventListener.h + * @brief This is the header file for the %_IPowerManagerEventListener interface. + * + * This header file contains the declarations of the %_IPowerManagerEventListener interface. + */ + +#ifndef _FSYS_INTERNAL_IPOWERMANAGER_EVENT_LISTENER_H_ +#define _FSYS_INTERNAL_IPOWERMANAGER_EVENT_LISTENER_H_ + +#include +#include + +namespace Tizen { namespace System +{ + +/** + * @interface _IPowerManagerEventListener + * @brief This interface is the listener of internal PowerManager event. + * + * @sinces2.1 + * + * The %_IPowerManagerEventListener interface must be registered and implemented by an application to receive PowerManager events from the system. + */ + +class _OSP_EXPORT_ _IPowerManagerEventListener + : public virtual Tizen::Base::Runtime::IEventListener +{ +public: + /** + * This is the destructor for this class. This polymorphic destructor should be overridden if required. This way, the destructors of the derived classes are called when the destructor of this interface is called. + * + * @sinces2.1 + */ + + virtual ~_IPowerManagerEventListener(void) {} + + /** + * Called when the screen state is changed. + * + * @sinces2.1 + * @param[in] state The screen state whether screen is on or off. + */ + virtual void OnScreenStateChanged(bool state) = 0; +}; // _IPowerManagerEventListener + +} } // Osp::System + +#endif // diff --git a/src/system/inc/FSys_PowerManagerImpl.h b/src/system/inc/FSys_PowerManagerImpl.h new file mode 100644 index 0000000..38d9324 --- /dev/null +++ b/src/system/inc/FSys_PowerManagerImpl.h @@ -0,0 +1,92 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_PowerManagerImpl.h + * @brief This is the header file for the _PowerManagerImpl class. + */ + + +#ifndef _FSYS_INTERNAL_POWERMANAGER_IMPL_H_ +#define _FSYS_INTERNAL_POWERMANAGER_IMPL_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace System +{ + +class IScreenEventListener; +class IChargingEventListener; +class IBatteryEventListener; + +/** + * @class _PowerManagerImpl + * @brief This class provides methods for power management. + * + */ +class _OSP_EXPORT_ _PowerManagerImpl + : public Tizen::Base::Object +{ + +public: + static int GetScreenBrightness(void); + static bool GetScreenState(void); + static result InitBatteryEvent(void); + static bool IsScreenOn(void); + static result KeepCpuAwake(bool enable); + static result KeepScreenOnState(bool keepOn, bool dimming = true); + static result OnBackground(void); + static result OnForeground(void); + static result RestoreScreenBrightness(void); + static result SetScreenBrightness(int brightness); + static result SetBatteryEventListener(IBatteryEventListener* pListener); + static void SetChargingEventListener(IChargingEventListener& listener); + static void SetScreenEventListener(IScreenEventListener& listener); + static result TurnScreenOff(void); + static result TurnScreenOn(void); + + static result PowerControl(int deviceId, int level); + static bool IsActive(void); + + static int GetCurrentBatteryLevelInPercentage(void); + static BatteryLevel GetCurrentBatteryLevel(void); + static bool IsCharging(void); + + static result Add_IPowerManagerEventListener(_IPowerManagerEventListener* listener); + static result Remove_IPowerManagerEventListener(_IPowerManagerEventListener* listener); + + static _PowerManagerImpl* GetInstance(PowerManager& powerManager); + static const _PowerManagerImpl* GetInstance(const PowerManager& powerManager); + + +private: + + _PowerManagerImpl(void); + virtual ~_PowerManagerImpl(void); + + static void Init(); + static void Term(); + + static bool _InitPowerManager; +}; + +} } + +#endif //_FSYS_INTERNAL_POWERMANAGER_IMPL_H_ diff --git a/src/system/inc/FSys_RuntimeInfoImpl.h b/src/system/inc/FSys_RuntimeInfoImpl.h new file mode 100644 index 0000000..32e6a22 --- /dev/null +++ b/src/system/inc/FSys_RuntimeInfoImpl.h @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_RuntimeInfoImpl.h + * @brief This is the header file for _RuntimeInfoImpl class. + */ + +#ifndef _FSYSTEM_INTERNAL_RUNTIMEINFO_IMPL_H_ +#define _FSYSTEM_INTERNAL_RUNTIMEINFO_IMPL_H_ + +#include +#include +#include +#include + +namespace Tizen { namespace System +{ + + +class _OSP_EXPORT_ _RuntimeInfoImpl + : public Tizen::Base::Object +{ +public: + _RuntimeInfoImpl(void); + + virtual ~_RuntimeInfoImpl(void); + + static result GetValue(const Tizen::Base::String& key, Tizen::Base::String& value); + static result GetValue(const Tizen::Base::String& key, int& value); + static result GetValue(const Tizen::Base::String& key, long long& value); + static result GetValue(const Tizen::Base::String& key, double& value); + static result GetValue(const Tizen::Base::String& key, bool& value); + static result GetValue(const Tizen::Base::String& key, Tizen::Base::UuId& value); + static result GetValueAsync(const Tizen::Base::String& key, IRuntimeInfoGetIntAsyncResultListener* listener); + static result GetValueAsync(const Tizen::Base::String& key, IRuntimeInfoGetLonglongAsyncResultListener* listener); + static _RuntimeInfoImpl* GetInstance(RuntimeInfo& runtimeinfo); + static const _RuntimeInfoImpl* GetInstance(const RuntimeInfo& runtimeinfo); + +private: + static result GetBatteryLevel(int& value); + static result IsChargingMode(bool& value); + static result GetAvailableInternalStorage(long long& value); + static result GetAvailableExternalStorage(long long& value); + static result GetAvailableMediaStorage(long long& value); + static result GetCapacity(const char* path, long long& totalSize, long long& availableSize); + static result GetFromProc(const char* path, const char* key, int& value); + static result GetFromProcLonglong(const char* path, const char* key, long long& value); + static long long GetDirectorySize(const char* path); + static void* GetDirectorySizeAsync(void* data); + static void* GetCpuUsageAsync(void* data); +}; + +} } // Tizen::Sys + +#endif //_FSYSTEM_INTERNAL_ALARM_IMPL_H_ diff --git a/src/system/inc/FSys_SettingInfoImpl.h b/src/system/inc/FSys_SettingInfoImpl.h new file mode 100644 index 0000000..7430acf --- /dev/null +++ b/src/system/inc/FSys_SettingInfoImpl.h @@ -0,0 +1,75 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SettingInfoImpl.h + * @brief This is the header file for _SettingInfoImpl class. + */ + +#ifndef _FSYSTEM_INTERNAL_SETTINGINFO_IMPL_H_ +#define _FSYSTEM_INTERNAL_SETTINGINFO_IMPL_H_ + +#include + +namespace Tizen { namespace System +{ + +class _OSP_EXPORT_ _SettingInfoImpl + : public Tizen::Base::Object +{ +public: + _SettingInfoImpl(void); + virtual ~_SettingInfoImpl(void); + + static result GetValue(const Tizen::Base::String& key, Tizen::Base::String& value); + static result GetValue(const Tizen::Base::String& key, int& value); + static result GetValue(const Tizen::Base::String& key, long long& value); + static result GetValue(const Tizen::Base::String& key, double& value); + static result GetValue(const Tizen::Base::String& key, bool& value); + static result GetValue(const Tizen::Base::String& key, Tizen::Base::UuId& value); + static result SetSettingEventListener(ISettingEventListener* pListener); + static result AddSettingEventListenerForInternal(ISettingEventListener& listener); + static result RemoveSettingEventListenerForInternal(ISettingEventListener& listener); + static result AddSettingEventListener(ISettingEventListener& listener); + static result RemoveSettingEventListener(ISettingEventListener& listener); + + static result SetWallpaper(const Tizen::Base::String& filePath); + static result SetRingtone(const Tizen::Base::String& filePath); + static result SetVolume(const Tizen::Base::String& soundCategory, int level); + static _SettingInfoImpl* GetInstance(SettingInfo& settinginfo); + static const _SettingInfoImpl* GetInstance(const SettingInfo& settinginfo); + + static bool HasKey(const Tizen::Base::String& key); + + static result GetValueForPrivilegedKey(const Tizen::Base::String& key, bool& value); + + static result SetValue(const Tizen::Base::String& key, bool value); + static result SetValue(const Tizen::Base::String& key, int value); + static result SetValue(const Tizen::Base::String& key, Tizen::Base::String value); + static result SetValueForPrivilegedKey(const Tizen::Base::String& key, bool value); + static result SetValueAsyncForPrivilegedKey(const Tizen::Base::String& key, bool value, ISettingInfoSetValueAsyncResultListener* listener); + static result SetValueForPrivilegedKey(const Tizen::Base::String& key, Tizen::Base::String value); + + static result ResetToFactoryDefault(void); +private: + static void InitSettingManager(void); + +}; + +} } // Tizen::Sys + +#endif //_FSYSTEM_INTERNAL_SETTINGINFO_IMPL_H_ diff --git a/src/system/inc/FSys_SystemInfoImpl.h b/src/system/inc/FSys_SystemInfoImpl.h new file mode 100644 index 0000000..7ee221c --- /dev/null +++ b/src/system/inc/FSys_SystemInfoImpl.h @@ -0,0 +1,86 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SystemInfoImpl.h + * @brief This is the header file for the _SystemInfoImpl class. + */ + +#ifndef _FSYS_INTERNAL_SYS_INFO_IMPL_H_ +#define _FSYS_INTERNAL_SYS_INFO_IMPL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace Tizen { namespace System +{ + +class IDeviceEventListener; +class IBatteryEventListener; +class IChargingEventListener; +class IScreenEventListener; + +class _OSP_EXPORT_ _SystemInfoImpl +{ +public: + static result GetSysInfo(const Tizen::Base::String& key, Tizen::Base::String& value); + + static result GetSysInfo(const Tizen::Base::String& key, int& value); + + static result GetSysInfo(const Tizen::Base::String& key, long long& value); + + static result GetSysInfo(const Tizen::Base::String& key, double& value); + + static result GetSysInfo(const Tizen::Base::String& key, bool& value); + + static result GetSysInfo(const Tizen::Base::String& key, Tizen::Base::UuId& value); + + static Tizen::Base::Collection::IList* GetSysInfoValuesN(const Tizen::Base::String& key, SystemInfoValueType type); + + static result GetImei(Tizen::Base::String& imei); + + static result GetPlatformVersion(Tizen::Base::String& platformVersion); + + static result GetNativeApiVersion(Tizen::Base::String& nativeApiVersion); + + static result GetWebApiVersion(Tizen::Base::String& webApiVersion); + + static _SystemInfoImpl* GetInstance(SystemInfo& systeminfo); + + static const _SystemInfoImpl* GetInstance(const SystemInfo& systeminfo); + +private: + static result GetFromRegistry(const Tizen::Base::String& key, Tizen::Base::String& value); + + static result GetFromRegistry(const Tizen::Base::String& key, int& value); + + static result GetFromRegistry(const Tizen::Base::String& key, bool& value); +}; + +} } // Tizen::System + +#endif // _FSYS_INTERNAL_SYS_INFO_IMPL_H_ diff --git a/src/system/inc/FSys_SystemResource.h b/src/system/inc/FSys_SystemResource.h new file mode 100644 index 0000000..5b8dd1c --- /dev/null +++ b/src/system/inc/FSys_SystemResource.h @@ -0,0 +1,90 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SystemResource.h + * @brief This is the header file of the _SystemResource class. + */ + +#ifndef _FSYS_INTERNAL_SYSTEM_RESOURCE_H_ +#define _FSYS_INTERNAL_SYSTEM_RESOURCE_H_ + +#include +#include + +#include + + +namespace Tizen { namespace System +{ + +/** + * @class _SystemResource + * @since 2.1 + */ +class _OSP_EXPORT_ _SystemResource + : public Tizen::Base::Object +{ +public: + /** + * Retrieves class instance. + * + * @since 2.1 + * @return A pointer to the %_SystemResource instance, @n + * else @c null if it fails + */ + static _SystemResource* GetInstance(void); + + /** + * Gets the service's Id. + * + * @since 2.1 + * @return The string obtained from the loaded application resource @n + * If no matched resource ID found, empty string is returned. + * @param[in] resourceId The resource ID that represents the resource + */ + Tizen::Base::String GetString(_SystemStringId resourceId) const; + + /** + * Gets the service's Id. + * + * @since 2.1 + * @return The string obtained from the loaded application resource @n + * If no matched resource ID found, empty string is returned. + * @param[in] domainId The resource domain ID + * @param[in] resourceId The resource ID that represents the resource + */ + Tizen::Base::String GetString(_ResourceDomainId domainId, _ResourceId resourceId) const; + +private: + _OSP_LOCAL_ _SystemResource(void); + + _OSP_LOCAL_ virtual ~_SystemResource(void); + + _SystemResource(const _SystemResource& rhs); + + _SystemResource& operator =(const _SystemResource& rhs); + + static void InitSystemResource(void); + +private: + static _SystemResource* __pSystemRsrc; +}; // _SystemResource + +} } // Tizen::System + +#endif // _FSYS_INTERNAL_SYSTEM_RESOURCE_H_ diff --git a/src/system/inc/FSys_SystemStrings.h b/src/system/inc/FSys_SystemStrings.h new file mode 100644 index 0000000..6983825 --- /dev/null +++ b/src/system/inc/FSys_SystemStrings.h @@ -0,0 +1,63 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SystemStrings.h + * @brief This is the header file of the system string list. + */ + +#ifndef _FSYS_INTERNAL_SYSTEM_STRINGS_H_ +#define _FSYS_INTERNAL_SYSTEM_STRINGS_H_ + +namespace Tizen { namespace System +{ + +/** + * System resource domain ID + * + * @since 2.1 + */ +typedef const char* _ResourceDomainId; + +/** + * System resource ID + * + * @since 2.1 + */ +typedef const char* _ResourceId; + +/** + * @enum _SystemStringId + * Defines the system string ID + * + * @since 2.1 + */ +enum _SystemStringId +{ + IDS_COM_INVALID = 0, + IDS_COM_SK_OK, /**< OK */ + IDS_COM_SK_CANCEL, /**< Cancel */ + IDS_COM_POP_SELECT_DEFAULT_APPLICATION, /**< Select default application */ + IDS_COM_POP_DEFAULT_APPLICATION, /**< Default application */ + IDS_COM_POP_APPLICATION_TYPE, /**< Application Type */ +}; + +_OSP_EXPORT_ extern _ResourceDomainId _RESOURCE_DOMAIN_ID_OSP; + +} } // Tizen::System + +#endif // _FSYS_INTERNAL_SYSTEM_STRINGS_H_ diff --git a/src/system/inc/FSys_SystemTimeImpl.h b/src/system/inc/FSys_SystemTimeImpl.h new file mode 100644 index 0000000..ac4eb08 --- /dev/null +++ b/src/system/inc/FSys_SystemTimeImpl.h @@ -0,0 +1,55 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_SystemTimeImpl.h + * @brief This is the header file for _SystemTimeImpl class. + */ + +#ifndef _FSYSTEM_INTERNAL_SYSTEMTIME_IMPL_H_ +#define _FSYSTEM_INTERNAL_SYSTEMTIME_IMPL_H_ + +#include +#include + +namespace Tizen { namespace System +{ + + +class _OSP_EXPORT_ _SystemTimeImpl +{ +public: + _SystemTimeImpl(void); + + virtual ~_SystemTimeImpl(void); + static result GetUptime(Tizen::Base::TimeSpan& uptime); + static result GetCurrentTime(TimeMode timeMode, Tizen::Base::DateTime& currentTime); + static result GetCurrentTime(Tizen::Base::DateTime& currentTime); + static result SetCurrentTime(const Tizen::Base::DateTime& currentTime); + static result GetTicks(long long& ticks); + static result GetNanoTicks(long long& nanoTicks); + + static _SystemTimeImpl* GetInstance(SystemTime& systemtime); + static const _SystemTimeImpl* GetInstance(const SystemTime& systemtime); + +private: +}; + + +} } // Tizen::Sys + +#endif //_FSYSTEM_INTERNAL_SYSTEMTIME_IMPL_H_ diff --git a/src/system/inc/FSys_VibratorImpl.h b/src/system/inc/FSys_VibratorImpl.h new file mode 100644 index 0000000..6e913d2 --- /dev/null +++ b/src/system/inc/FSys_VibratorImpl.h @@ -0,0 +1,139 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FSys_VibratorImpl.h + * @brief This is the header file for _VibratorImpl class. + */ + +#ifndef _FSYSTEM_INTERNAL_VIBRATOR_IMPL_H_ +#define _FSYSTEM_INTERNAL_VIBRATOR_IMPL_H_ + +#include +#include +#include +#include +#include + +namespace Tizen { namespace System +{ +class Vibrator; + +class _OSP_EXPORT_ _VibratorImpl + : public Tizen::Base::Object + , public Tizen::Base::Runtime::ITimerEventListener +{ +public: + /* + * This is the default constructor for this class. + * + * @since 2.1 + */ + _VibratorImpl(void); + + /* + * This is the destructor for this class. + * + * @since 2.1 + */ + virtual ~_VibratorImpl(void); + + /* + * Initializes this instance of %Vibrator. + * + * @since 2.1 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_SYSTEM An unknown operating system error has occurred. + * @exception E_OUT_OF_MEMORY The memory is insufficient. + * + */ + result Construct(void); + + /* + * Vibrates the device with the specified pattern and level. @n + * This method returns the result immediately so that the vibration occurs simultaneously as the device runs. + * If this method is called again before the previous vibration stops, the previous vibration is canceled and the new vibration starts immediately. + * + * @since 2.1 + * + * @return An error code + * @param[in] onPeriod The period in milliseconds when the vibrator is on @n + * It should be greater than @c 0. + * @param[in] offPeriod The period in milliseconds when the vibrator is off @n + * It should be equal to or greater than @c 0. + * @param[in] count The number of times to execute the given pattern @n + * It should be greater than @c 0. + * @param[in] level The vibration level @n + * Ranges from @c [0~100], where ' @c 0' is a special case indicating the system default level. + * @exception E_SUCCESS The method is successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. + * @exception E_DEVICE_BUSY The device cannot be approached because of other operations. + * @exception E_DEVICE_FAILED The device operation has failed. + * @remarks Various devices may have different vibration capabilities. + * If the device supports only one level of vibration, then a level value between @c [0~100] results in the default vibration. + * If the device supports many levels of vibration, then a level value @c 0 results in the system default vibration, value @c 1 results in the lowest frequency vibration, value @c 100 results in the highest frequency vibration, and intermediate values result in intermediate vibration levels. @n + * Devices have implementation-specific limits for the total duration of the vibration, and vibration cuts off at that limit even if the duration parameter is greater than the limit. + * + */ + result Start(long onPeriod, long offPeriod, int count, int level = 0); + + /* + * Turns the vibrator off. + * + * @since 2.1 + * + * @return An error code + * @exception E_SUCCESS The method is successful. + * @exception E_DEVICE_FAILED The device operation has failed. + */ + result Stop(void); + + static _VibratorImpl* GetInstance(Vibrator& vibrator); + + static const _VibratorImpl* GetInstance(const Vibrator& vibrator); + +private: + void Destruct(void); + + _VibratorImpl(const _VibratorImpl& value); + + _VibratorImpl& operator =(const _VibratorImpl& value); + + virtual void OnTimerExpired(Tizen::Base::Runtime::Timer& timer); + + +private: + Handle __handle; + Tizen::Base::Runtime::Timer* __pTimer; + + struct VibrationInformation + { + long onPeriod; + long offPeriod; + int count; + int level; + bool isVibrating; + bool isFinished; + }; + VibrationInformation __vibrationInformation; + + static const VibrationInformation __INVALID_VIBRATION_INFORMATION; +}; +} } // Tizen::System +#endif diff --git a/src/text/CMakeLists.txt b/src/text/CMakeLists.txt new file mode 100755 index 0000000..1b23a78 --- /dev/null +++ b/src/text/CMakeLists.txt @@ -0,0 +1,42 @@ +SET (this_target text) + +INCLUDE_DIRECTORIES( + ${SLP_INCLUDE_DIRS} + ${CMAKE_SOURCE_DIR}/inc + inc + ${CMAKE_SOURCE_DIR}/src/base/inc +) + +SET (${this_target}_SOURCE_FILES + FText_IcuEncodingCore.cpp + FText_GsmEncodingCore.cpp + FText_Ucs2EncodingCore.cpp + FText_Iso885916EncodingCore.cpp + FText_EncodingCore.cpp + FText_DecoderImpl.cpp + FText_EncoderImpl.cpp + FText_EncodingImpl.cpp + FTextEncoding.cpp + FTextAsciiEncoding.cpp + FTextGsmEncoding.cpp + FTextLatin1Encoding.cpp + FTextUcs2Encoding.cpp + FTextUtf8Encoding.cpp + FTextUtf8Decoder.cpp + FTextUtf8Encoder.cpp +) + + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") + +## SET EXTRA COMPILER FLAGS +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fPIC" ) + +## SET C COMPILER FLAGS +SET(CMAKE_C_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## SET CPP COMPILER FLAGS +SET(CMAKE_CXX_FLAGS "${OSP_DEBUG_FLAGS} ${OSP_OPT_FLAGS} ${CMAKE_CXX_FLAGS} ${EXTRA_CFLAGS} ${OSP_COMPILER_FLAGS}") + +## Create Library +ADD_LIBRARY (${this_target} STATIC ${${this_target}_SOURCE_FILES}) diff --git a/src/text/FTextAsciiEncoding.cpp b/src/text/FTextAsciiEncoding.cpp new file mode 100644 index 0000000..49954ae --- /dev/null +++ b/src/text/FTextAsciiEncoding.cpp @@ -0,0 +1,149 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextAsciiEncoding.cpp + * @brief This is the implementation file for ASCII Encoding class. + */ + +#include +#include +#include "FText_EncodingImpl.h" + + +#define ENCODING_NAME L"ASCII" + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + + +AsciiEncoding::AsciiEncoding(void) + : __pAsciiEncodingImpl(null) +{ + _pEncodingImpl = new (std::nothrow) _EncodingImpl; + if (_pEncodingImpl) + { + result r = _pEncodingImpl->Construct(ENCODING_NAME); + if (IsFailed(r)) + { + delete _pEncodingImpl; + _pEncodingImpl = null; + } + } + + SysAssert(_pEncodingImpl); +} + + +AsciiEncoding::~AsciiEncoding(void) +{ + delete _pEncodingImpl; +} + + +ByteBuffer* +AsciiEncoding::GetBytesN(const WcharBuffer& chars) const +{ + return _pEncodingImpl->GetBytesN(chars); +} + +ByteBuffer* +AsciiEncoding::GetBytesN(const String& str) const +{ + return _pEncodingImpl->GetBytesN(str); +} + + +result +AsciiEncoding::GetBytes(const WcharBuffer& chars, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(chars, charIndex, charCount, bytes, byteIndex); +} + + +result +AsciiEncoding::GetBytes(const String& str, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(str, charIndex, charCount, bytes, byteIndex); +} + + +WcharBuffer* +AsciiEncoding::GetCharsN(const ByteBuffer& bytes) const +{ + return _pEncodingImpl->GetCharsN(bytes); +} + + +result +AsciiEncoding::GetChars(const ByteBuffer& bytes, int byteIndex, int byteCount, WcharBuffer& chars, int charIndex) const +{ + return _pEncodingImpl->GetChars(bytes, byteIndex, byteCount, chars, charIndex); +} + + +result +AsciiEncoding::GetString(const ByteBuffer& bytes, String& str) const +{ + return _pEncodingImpl->GetString(bytes, str); +} + + +result +AsciiEncoding::GetString(const ByteBuffer& bytes, int byteIndex, int byteCount, String& str) const +{ + return _pEncodingImpl->GetString(bytes, byteIndex, byteCount, str); +} + + +int +AsciiEncoding::GetMaxByteCount(int charCount) const +{ + return charCount; +} + + +int +AsciiEncoding::GetMaxCharCount(int byteCount) const +{ + return byteCount; +} + + +Encoder* +AsciiEncoding::GetEncoderN(void) const +{ + return null; +} + + +Decoder* +AsciiEncoding::GetDecoderN(void) const +{ + return null; +} + + +String +AsciiEncoding::GetEncodingType(void) const +{ + return String(ENCODING_NAME); +} + +} } // Tizen::Text diff --git a/src/text/FTextEncoding.cpp b/src/text/FTextEncoding.cpp new file mode 100644 index 0000000..71561c3 --- /dev/null +++ b/src/text/FTextEncoding.cpp @@ -0,0 +1,164 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextEncoding.cpp + * @brief This is the implementation file for Encoding class. + */ + +#include +#include +#include +#include +#include +#include +#include "FText_EncodingImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Text +{ + +Encoding::Encoding(void) + : _pEncodingImpl(null) +{ + +} + +Encoding::~Encoding(void) +{ + +} + +result +Encoding::GetByteCount(const String& str, int& byteCount) const +{ + SysAssertf(_pEncodingImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pEncodingImpl->GetByteCount(str, byteCount); +} + + +result +Encoding::GetByteCount(const WcharBuffer& chars, int& byteCount) const +{ + SysAssertf(_pEncodingImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pEncodingImpl->GetByteCount(chars, byteCount); +} + + +result +Encoding::GetByteCount(const WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const +{ + SysAssertf(_pEncodingImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pEncodingImpl->GetByteCount(chars, charIndex, charCount, byteCount); +} + +result +Encoding::GetCharCount(const ByteBuffer& bytes, int& charCount) const +{ + SysAssertf(_pEncodingImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pEncodingImpl->GetCharCount(bytes, charCount); +} + + +result +Encoding::GetCharCount(const ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const +{ + SysAssertf(_pEncodingImpl != null, "Not yet constructed! Construct() should be called before use."); + return _pEncodingImpl->GetCharCount(bytes, byteIndex, byteCount, charCount); +} + +Utf8Encoding& +Encoding::GetUtf8Encoding(void) +{ + static Utf8Encoding utf8; + return utf8; +} + +Ucs2Encoding& +Encoding::GetUcs2Encoding(void) +{ + static Ucs2Encoding ucs2; + return ucs2; +} + +GsmEncoding& +Encoding::GetGsmEncoding(void) +{ + static GsmEncoding gsm; + return gsm; +} + +Latin1Encoding& +Encoding::GetLatin1Encoding(void) +{ + static Latin1Encoding latin1; + return latin1; +} + +AsciiEncoding& +Encoding::GetAsciiEncoding(void) +{ + static AsciiEncoding ascii; + return ascii; +} + +Encoding* +Encoding::GetEncodingN(const Tizen::Base::String& encodingType) +{ + ClearLastResult(); + result r = E_SUCCESS; + + _EncodingImpl* pEncodingImpl = new (std::nothrow) _EncodingImpl(); + SysTryReturn(NID_TEXT, pEncodingImpl != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pEncodingImpl->Construct(encodingType); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Encoder construct failed.", GetErrorMessage(r)); + + return pEncodingImpl; + +CATCH: + delete pEncodingImpl; + return null; +} + +String +Encoding::GetEncodingType(const Encoding& encoding) +{ + return encoding.GetEncodingType(); +} + +IList* +Encoding::GetAvailableEncodingsN(void) +{ + return _EncodingImpl::GetAvailableEncodingsImplN(); +} + +ByteBuffer* +Encoding::ConvertN(const Encoding& src, const Encoding& dst, const ByteBuffer& srcBytes) +{ + return _EncodingImpl::ConvertImplN(src, dst, srcBytes); +} + +ByteBuffer* +Encoding::ConvertN(const Encoding& src, const Encoding& dst, const ByteBuffer& srcBytes, int index, int count) +{ + return _EncodingImpl::ConvertImplN(src, dst, srcBytes, index, count); +} + +} } // Tizen::Text diff --git a/src/text/FTextGsmEncoding.cpp b/src/text/FTextGsmEncoding.cpp new file mode 100644 index 0000000..b63ea60 --- /dev/null +++ b/src/text/FTextGsmEncoding.cpp @@ -0,0 +1,184 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextGsmEncoding.cpp + * @brief This is the implementation file for GSM Encoding class. + */ + +#include +#include +#include "FText_EncodingImpl.h" + + +#define ENCODING_NAME L"GSM" + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + +GsmEncoding::GsmEncoding(void) + : __pGsmEncodingImpl(null) +{ + _pEncodingImpl = new (std::nothrow) _EncodingImpl; + if (_pEncodingImpl) + { + result r = _pEncodingImpl->Construct(ENCODING_NAME); + if (IsFailed(r)) + { + delete _pEncodingImpl; + _pEncodingImpl = null; + } + } + + SysAssert(_pEncodingImpl); +} + + +GsmEncoding::~GsmEncoding(void) +{ + delete _pEncodingImpl; +} + + +result +GsmEncoding::GetByteCount(const String& str, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(str, byteCount); +} + + +result +GsmEncoding::GetByteCount(const WcharBuffer& chars, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(chars, byteCount); +} + + +result +GsmEncoding::GetByteCount(const WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(chars, charIndex, charCount, byteCount); +} + + +ByteBuffer* +GsmEncoding::GetBytesN(const WcharBuffer& chars) const +{ + return _pEncodingImpl->GetBytesN(chars); +} + + +ByteBuffer* +GsmEncoding::GetBytesN(const String& str) const +{ + return _pEncodingImpl->GetBytesN(str); +} + + +result +GsmEncoding::GetBytes(const WcharBuffer& chars, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(chars, charIndex, charCount, bytes, byteIndex); +} + + +result +GsmEncoding::GetBytes(const String& str, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(str, charIndex, charCount, bytes, byteIndex); +} + + +result +GsmEncoding::GetCharCount(const ByteBuffer& bytes, int& charCount) const +{ + return _pEncodingImpl->GetCharCount(bytes, charCount); +} + + +result +GsmEncoding::GetCharCount(const ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const +{ + return _pEncodingImpl->GetCharCount(bytes, byteIndex, byteCount, charCount); +} + + +WcharBuffer* +GsmEncoding::GetCharsN(const ByteBuffer& bytes) const +{ + return _pEncodingImpl->GetCharsN(bytes); +} + + +result +GsmEncoding::GetChars(const ByteBuffer& bytes, int byteIndex, int byteCount, WcharBuffer& chars, int charIndex) const +{ + return _pEncodingImpl->GetChars(bytes, byteIndex, byteCount, chars, charIndex); +} + + +result +GsmEncoding::GetString(const ByteBuffer& bytes, String& str) const +{ + return GetString(bytes, bytes.GetPosition(), bytes.GetRemaining(), str); +} + + +result +GsmEncoding::GetString(const ByteBuffer& bytes, int index, int count, String& str) const +{ + return _pEncodingImpl->GetString(bytes, index, count, str); +} + + +int +GsmEncoding::GetMaxByteCount(int charCount) const +{ + return charCount * 2; +} + + +int +GsmEncoding::GetMaxCharCount(int byteCount) const +{ + return byteCount; +} + + +Encoder* +GsmEncoding::GetEncoderN(void) const +{ + return null; +} + + +Decoder* +GsmEncoding::GetDecoderN(void) const +{ + return null; +} + + +String +GsmEncoding::GetEncodingType(void) const +{ + return String(ENCODING_NAME); +} + +} } // Tizen::Text diff --git a/src/text/FTextLatin1Encoding.cpp b/src/text/FTextLatin1Encoding.cpp new file mode 100644 index 0000000..484dc26 --- /dev/null +++ b/src/text/FTextLatin1Encoding.cpp @@ -0,0 +1,149 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextLatin1Encoding.cpp + * @brief This is the implementation file for Latin1 Encoding class. + */ + +#include +#include +#include "FText_EncodingImpl.h" + + +#define ENCODING_NAME L"ISO-8859-1" + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + + +Latin1Encoding::Latin1Encoding(void) + : __pLatin1EncodingImpl(null) +{ + _pEncodingImpl = new (std::nothrow) _EncodingImpl; + if (_pEncodingImpl) + { + result r = _pEncodingImpl->Construct(ENCODING_NAME); + if (IsFailed(r)) + { + delete _pEncodingImpl; + _pEncodingImpl = null; + } + } + + SysAssert(_pEncodingImpl); +} + + +Latin1Encoding::~Latin1Encoding(void) +{ + delete _pEncodingImpl; +} + + +ByteBuffer* +Latin1Encoding::GetBytesN(const WcharBuffer& chars) const +{ + return _pEncodingImpl->GetBytesN(chars); +} + +ByteBuffer* +Latin1Encoding::GetBytesN(const String& str) const +{ + return _pEncodingImpl->GetBytesN(str); +} + + +result +Latin1Encoding::GetBytes(const WcharBuffer& chars, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(chars, charIndex, charCount, bytes, byteIndex); +} + + +result +Latin1Encoding::GetBytes(const String& str, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(str, charIndex, charCount, bytes, byteIndex); +} + + +WcharBuffer* +Latin1Encoding::GetCharsN(const ByteBuffer& bytes) const +{ + return _pEncodingImpl->GetCharsN(bytes); +} + + +result +Latin1Encoding::GetChars(const ByteBuffer& bytes, int byteIndex, int byteCount, WcharBuffer& chars, int charIndex) const +{ + return _pEncodingImpl->GetChars(bytes, byteIndex, byteCount, chars, charIndex); +} + + +result +Latin1Encoding::GetString(const ByteBuffer& bytes, String& str) const +{ + return _pEncodingImpl->GetString(bytes, str); +} + + +result +Latin1Encoding::GetString(const ByteBuffer& bytes, int byteIndex, int byteCount, String& str) const +{ + return _pEncodingImpl->GetString(bytes, byteIndex, byteCount, str); +} + + +int +Latin1Encoding::GetMaxByteCount(int charCount) const +{ + return charCount; +} + + +int +Latin1Encoding::GetMaxCharCount(int byteCount) const +{ + return byteCount; +} + + +Encoder* +Latin1Encoding::GetEncoderN(void) const +{ + return null; +} + + +Decoder* +Latin1Encoding::GetDecoderN(void) const +{ + return null; +} + + +String +Latin1Encoding::GetEncodingType(void) const +{ + return String(ENCODING_NAME); +} + +} } // Tizen::Text diff --git a/src/text/FTextUcs2Encoding.cpp b/src/text/FTextUcs2Encoding.cpp new file mode 100644 index 0000000..5f3ba79 --- /dev/null +++ b/src/text/FTextUcs2Encoding.cpp @@ -0,0 +1,185 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextUcs2Encoding.cpp + * @brief This is the implementation file for UCS2 Encoding class. + */ + +#include +#include +#include "FText_EncodingImpl.h" + + +#define ENCODING_NAME L"UCS-2" + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + + +Ucs2Encoding::Ucs2Encoding(void) + : __pUcs2EncodingImpl(null) +{ + _pEncodingImpl = new (std::nothrow) _EncodingImpl; + if (_pEncodingImpl) + { + result r = _pEncodingImpl->Construct(ENCODING_NAME); + if (IsFailed(r)) + { + delete _pEncodingImpl; + _pEncodingImpl = null; + } + } + + SysAssert(_pEncodingImpl); +} + + +Ucs2Encoding::~Ucs2Encoding(void) +{ + delete _pEncodingImpl; +} + + +result +Ucs2Encoding::GetByteCount(const String& str, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(str, byteCount); +} + + +result +Ucs2Encoding::GetByteCount(const WcharBuffer& chars, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(chars, byteCount); +} + + +result +Ucs2Encoding::GetByteCount(const WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(chars, charIndex, charCount, byteCount); +} + + +ByteBuffer* +Ucs2Encoding::GetBytesN(const WcharBuffer& chars) const +{ + return _pEncodingImpl->GetBytesN(chars); +} + + +ByteBuffer* +Ucs2Encoding::GetBytesN(const String& str) const +{ + return _pEncodingImpl->GetBytesN(str); +} + + +result +Ucs2Encoding::GetBytes(const WcharBuffer& chars, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(chars, charIndex, charCount, bytes, byteIndex); +} + + +result +Ucs2Encoding::GetBytes(const String& str, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(str, charIndex, charCount, bytes, byteIndex); +} + + +result +Ucs2Encoding::GetCharCount(const ByteBuffer& bytes, int& charCount) const +{ + return _pEncodingImpl->GetCharCount(bytes, charCount); +} + + +result +Ucs2Encoding::GetCharCount(const ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const +{ + return _pEncodingImpl->GetCharCount(bytes, byteIndex, byteCount, charCount); +} + + +WcharBuffer* +Ucs2Encoding::GetCharsN(const ByteBuffer& bytes) const +{ + return _pEncodingImpl->GetCharsN(bytes); +} + + +result +Ucs2Encoding::GetChars(const ByteBuffer& bytes, int byteIndex, int byteCount, WcharBuffer& chars, int charIndex) const +{ + return _pEncodingImpl->GetChars(bytes, byteIndex, byteCount, chars, charIndex); +} + + +result +Ucs2Encoding::GetString(const ByteBuffer& bytes, String& str) const +{ + return _pEncodingImpl->GetString(bytes, str); +} + + +result +Ucs2Encoding::GetString(const ByteBuffer& bytes, int byteIndex, int byteCount, String& str) const +{ + return _pEncodingImpl->GetString(bytes, byteIndex, byteCount, str); +} + + +int +Ucs2Encoding::GetMaxByteCount(int charCount) const +{ + return (charCount + 1) * 2; +} + + +int +Ucs2Encoding::GetMaxCharCount(int byteCount) const +{ + return byteCount; +} + + +Encoder* +Ucs2Encoding::GetEncoderN(void) const +{ + return null; +} + + +Decoder* +Ucs2Encoding::GetDecoderN(void) const +{ + return null; +} + + +String +Ucs2Encoding::GetEncodingType(void) const +{ + return String(ENCODING_NAME); +} + +} } // Tizen::Text diff --git a/src/text/FTextUtf8Decoder.cpp b/src/text/FTextUtf8Decoder.cpp new file mode 100644 index 0000000..42e186f --- /dev/null +++ b/src/text/FTextUtf8Decoder.cpp @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextUtf8Decoder.cpp + * @brief This is the implementation file for UTF-8 Decoder class. + */ + +// Includes +#include +#include +#include "FText_DecoderImpl.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + +Utf8Decoder::Utf8Decoder(void) + : __pUtf8DecoderImpl(null) +{ + _pDecoderImpl = _DecoderImpl::GetDecoderN(L"UTF-8"); + + SysAssert(_pDecoderImpl); +} + + +Utf8Decoder::~Utf8Decoder(void) +{ + delete _pDecoderImpl; +} + + +result +Utf8Decoder::GetCharCount(const ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount, bool flush) const +{ + return _pDecoderImpl->GetCharCount(bytes, byteIndex, byteCount, charCount, flush); +} + + +WcharBuffer* +Utf8Decoder::GetCharsN(const ByteBuffer& bytes, bool flush) const +{ + return _pDecoderImpl->GetCharsN(bytes, flush); +} + + +WcharBuffer* +Utf8Decoder::GetCharsN(const ByteBuffer& bytes, int byteIndex, int byteCount, bool flush) const +{ + return _pDecoderImpl->GetCharsN(bytes, byteIndex, byteCount, flush); +} + + +} } // Tizen::Text diff --git a/src/text/FTextUtf8Encoder.cpp b/src/text/FTextUtf8Encoder.cpp new file mode 100644 index 0000000..eae3db3 --- /dev/null +++ b/src/text/FTextUtf8Encoder.cpp @@ -0,0 +1,70 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextUtf8Encoder.cpp + * @brief This is the implementation file for UTF-8 Encoder class. + */ + +// Includes +#include +#include +#include "FText_EncoderImpl.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + +Utf8Encoder::Utf8Encoder(void) + : __pUtf8EncoderImpl(null) +{ + _pEncoderImpl = _EncoderImpl::GetEncoderN(L"UTF-8"); + + SysAssert(_pEncoderImpl); +} + + +Utf8Encoder::~Utf8Encoder(void) +{ + delete _pEncoderImpl; +} + + +result +Utf8Encoder::GetByteCount(const WcharBuffer& chars, int charIndex, int charCount, int& byteCount, bool flush) const +{ + return _pEncoderImpl->GetByteCount(chars, charIndex, charCount, byteCount, flush); +} + + +ByteBuffer* +Utf8Encoder::GetBytesN(const WcharBuffer& chars, bool flush) const +{ + return _pEncoderImpl->GetBytesN(chars, flush); +} + + +ByteBuffer* +Utf8Encoder::GetBytesN(const WcharBuffer& chars, int charIndex, int charCount, bool flush) const +{ + return _pEncoderImpl->GetBytesN(chars, charIndex, charCount, flush); +} + + +} } // Tizen::Text diff --git a/src/text/FTextUtf8Encoding.cpp b/src/text/FTextUtf8Encoding.cpp new file mode 100644 index 0000000..8ea3c61 --- /dev/null +++ b/src/text/FTextUtf8Encoding.cpp @@ -0,0 +1,185 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FTextUtf8Encoding.cpp + * @brief This is the implementation file for UTF-8 Encoding class. + */ + +#include +#include +#include "FText_EncodingImpl.h" + + +#define ENCODING_NAME L"UTF-8" + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + + +Utf8Encoding::Utf8Encoding(void) + : __pUtf8EncodingImpl(null) +{ + _pEncodingImpl = new (std::nothrow) _EncodingImpl; + if (_pEncodingImpl) + { + result r = _pEncodingImpl->Construct(ENCODING_NAME); + if (IsFailed(r)) + { + delete _pEncodingImpl; + _pEncodingImpl = null; + } + } + + SysAssert(_pEncodingImpl); +} + + +Utf8Encoding::~Utf8Encoding(void) +{ + delete _pEncodingImpl; +} + + +result +Utf8Encoding::GetByteCount(const String& str, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(str, byteCount); +} + + +result +Utf8Encoding::GetByteCount(const WcharBuffer& chars, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(chars, byteCount); +} + + +result +Utf8Encoding::GetByteCount(const WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const +{ + return _pEncodingImpl->GetByteCount(chars, charIndex, charCount, byteCount); +} + + +ByteBuffer* +Utf8Encoding::GetBytesN(const WcharBuffer& chars) const +{ + return _pEncodingImpl->GetBytesN(chars); +} + + +ByteBuffer* +Utf8Encoding::GetBytesN(const String& str) const +{ + return _pEncodingImpl->GetBytesN(str); +} + + +result +Utf8Encoding::GetBytes(const WcharBuffer& chars, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(chars, charIndex, charCount, bytes, byteIndex); +} + + +result +Utf8Encoding::GetBytes(const String& str, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + return _pEncodingImpl->GetBytes(str, charIndex, charCount, bytes, byteIndex); +} + + +result +Utf8Encoding::GetCharCount(const ByteBuffer& bytes, int& charCount) const +{ + return _pEncodingImpl->GetCharCount(bytes, charCount); +} + + +result +Utf8Encoding::GetCharCount(const ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const +{ + return _pEncodingImpl->GetCharCount(bytes, byteIndex, byteCount, charCount); +} + + +WcharBuffer* +Utf8Encoding::GetCharsN(const ByteBuffer& bytes) const +{ + return _pEncodingImpl->GetCharsN(bytes); +} + + +result +Utf8Encoding::GetChars(const ByteBuffer& bytes, int byteIndex, int byteCount, WcharBuffer& chars, int charIndex) const +{ + return _pEncodingImpl->GetChars(bytes, byteIndex, byteCount, chars, charIndex); +} + + +result +Utf8Encoding::GetString(const ByteBuffer& bytes, String& str) const +{ + return _pEncodingImpl->GetString(bytes, str); +} + + +result +Utf8Encoding::GetString(const ByteBuffer& bytes, int byteIndex, int byteCount, String& str) const +{ + return _pEncodingImpl->GetString(bytes, byteIndex, byteCount, str); +} + + +int +Utf8Encoding::GetMaxByteCount(int charCount) const +{ + return charCount * 3; +} + + +int +Utf8Encoding::GetMaxCharCount(int byteCount) const +{ + return byteCount; +} + + +Encoder* +Utf8Encoding::GetEncoderN(void) const +{ + return new (std::nothrow) Utf8Encoder(); +} + + +Decoder* +Utf8Encoding::GetDecoderN(void) const +{ + return new (std::nothrow) Utf8Decoder(); +} + + +String +Utf8Encoding::GetEncodingType(void) const +{ + return String(ENCODING_NAME); +} + +} } // Tizen::Text diff --git a/src/text/FText_DecoderImpl.cpp b/src/text/FText_DecoderImpl.cpp new file mode 100644 index 0000000..9b5e56d --- /dev/null +++ b/src/text/FText_DecoderImpl.cpp @@ -0,0 +1,232 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_DecoderImpl.cpp + * @brief This is the implementation file for _DecoderImpl class. + */ + +#include +#include "FText_EncodingCore.h" +#include +#include "FText_DecoderImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +namespace Tizen { namespace Text +{ + +_DecoderImpl::_DecoderImpl(void) + : __pDecoder(null) + , __encodingType("") +{ +} + +_DecoderImpl::~_DecoderImpl(void) +{ +} + +_DecoderImpl* +_DecoderImpl::GetDecoderN(const String& encodingType) +{ + SysTryReturn(NID_TEXT, (encodingType == L"UTF-8"), null, E_INVALID_ARG, + "[%s] Invalid argument is used.encdoingType(%ls) is not UTF-8.Failed to open decoder.", GetErrorMessage(E_INVALID_ARG), encodingType.GetPointer()); + + std::unique_ptr<_DecoderImpl> pDecoderImpl(new (std::nothrow) _DecoderImpl); + SysTryReturn(NID_TEXT, pDecoderImpl, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + pDecoderImpl->__pDecoder.reset(_EncodingCore::GetEncodingCoreN(encodingType, L"WCHAR_T")); + + result r = GetLastResult(); + SysTryReturn(NID_TEXT, (pDecoderImpl->__pDecoder != null), null, r, + "[%s] Failed to open decoder.", GetErrorMessage(r)); + + pDecoderImpl->__encodingType = encodingType; + pDecoderImpl->_pDecoderImpl = pDecoderImpl.get(); + + SetLastResult(E_SUCCESS); + return pDecoderImpl.release(); +} + +result +_DecoderImpl::Decode(const byte* pSrc, int srcLength, WcharBuffer*& pWcharBuffer, int index, bool flush) const +{ + SysAssertf(__pDecoder != null, "Not yet constructed! Construct() should be called before use."); + + SysTryReturnResult(NID_TEXT, (pSrc != null), E_INVALID_ARG, "[%s] Invalid argument is used. pSrc can not be null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturnResult(NID_TEXT, (srcLength >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + SysTryReturnResult(NID_TEXT, (index >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. index(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), index); + + result r = E_SUCCESS; + int currPosition = 0; + int retLength = 0; + bool isMemAllocReq = false; + + std::unique_ptr pDst(__pDecoder->DecodeExN(pSrc, srcLength, retLength, flush)); + r = GetLastResult(); + SysTryReturnResult(NID_TEXT, (pDst != null), r, "[%s] Decoding failed", GetErrorMessage(r)); + + WcharBuffer* pOutBuffer = pWcharBuffer; + if (retLength > 0) + { + if (pOutBuffer == null) + { + isMemAllocReq = true; + pOutBuffer = new (std::nothrow) WcharBuffer; + SysTryCatch(NID_TEXT, (pOutBuffer != null), , + E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Byte Buffer allocation failed"); + + r = pOutBuffer->Construct(retLength); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to Construct Byte buffer", GetErrorMessage(r)); + + pWcharBuffer = pOutBuffer; + + } + else + { + currPosition = pOutBuffer->GetPosition(); + + r = pOutBuffer->SetPosition(index); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set Byte buffer position", GetErrorMessage(r)); + } + + r = pOutBuffer->SetArray(pDst.get(), 0, retLength); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to fill Byte buffer", GetErrorMessage(r)); + + r = pOutBuffer->SetPosition(currPosition); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set Byte buffer position", GetErrorMessage(r)); + + return r; + } + +CATCH: + if (isMemAllocReq) + { + delete pWcharBuffer; + pWcharBuffer = null; + } + return r; +} + +result +_DecoderImpl::GetCharCount(const ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount, bool flush) const +{ + SysAssertf(__pDecoder != null, "Not yet constructed! Construct() should be called before use."); + + charCount = 0; + int inBufSize = bytes.GetLimit(); + result r = CheckBufferInput(inBufSize, byteIndex, byteCount); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + byte lastByte = 0; + r = bytes.GetByte(byteIndex + byteCount - 1, lastByte); + if (!IsFailed(r)) + { + if (lastByte == '\0') + { + byteCount--; + } + } + + r = __pDecoder->GetCharCount((bytes.GetPointer() + byteIndex), byteCount, charCount); + + if (charCount < 0) + { + charCount = 0; + } + + return r; +} + +WcharBuffer* +_DecoderImpl::GetCharsN(const ByteBuffer& bytes, bool flush) const +{ + SysAssertf(__pDecoder != null, "Not yet constructed! Construct() should be called before use."); + + WcharBuffer* pBuffer = null; + int srcLength = 0; + result r = GetBufferSize(bytes, srcLength); + SysTryReturn(NID_TEXT, (!IsFailed(r)), null, r, "[%s] Input validation failed", GetErrorMessage(r)); + + r = Decode(bytes.GetPointer(), srcLength, pBuffer, 0, flush); + + SetLastResult(r); + return pBuffer; +} + +WcharBuffer* +_DecoderImpl::GetCharsN(const ByteBuffer& bytes, int byteIndex, int byteCount, bool flush) const +{ + SysAssertf(__pDecoder != null, "Not yet constructed! Construct() should be called before use."); + + WcharBuffer* pBuffer = null; + int srcLength = bytes.GetLimit(); + result r = CheckBufferInput(srcLength, byteIndex, byteCount); + SysTryReturn(NID_TEXT, (!IsFailed(r)), null, r, "[%s] Input validation failed", GetErrorMessage(r)); + + r = Decode(bytes.GetPointer() + byteIndex, byteCount, pBuffer, 0, flush); + + SetLastResult(r); + return pBuffer; +} + +result +_DecoderImpl::GetBufferSize(const ByteBuffer& bytes, int& byteBufSize) const +{ + // It is assumed that user has set limit properly + byteBufSize = bytes.GetLimit(); + + // Adjusting byteBufSize if bytes has null char at the end + byte lastByte = 0; + result r = bytes.GetByte(byteBufSize - 1, lastByte); + SysTryReturnResult(NID_TEXT, (!IsFailed(r)), E_INVALID_ARG, "[%s] Last byte check failed", GetErrorMessage(r)); + + if ((lastByte == '\0')and(byteBufSize > 1)) + { + byteBufSize -= 1; + } + SysTryReturnResult(NID_TEXT, (byteBufSize > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. byteBufSize [%d] is invalid.", GetErrorMessage(E_INVALID_ARG), byteBufSize); + + return E_SUCCESS; +} + +result +_DecoderImpl::CheckBufferInput(int inBufSize, int inIndex, int inCount) const +{ + SysTryReturnResult(NID_TEXT, (inIndex >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inIndex(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inIndex); + SysTryReturnResult(NID_TEXT, (inCount >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inCount(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inCount); + SysTryReturnResult(NID_TEXT, (inBufSize > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inBufSize(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inBufSize); + + SysTryReturnResult(NID_TEXT, (inBufSize > inIndex), E_OUT_OF_RANGE, + "[%s] inIndex(%d) is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE), inIndex); + SysTryReturnResult(NID_TEXT, (inBufSize >= inCount), E_OUT_OF_RANGE, + "[%s] inCount(%d) is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE), inCount); + SysTryReturnResult(NID_TEXT, (inBufSize >= (inIndex + inCount)), E_UNDERFLOW, + "[%s] sum of the length of the inIndex(%d) and inCount(%d) is greater than inBufSize(%d).", + GetErrorMessage(E_UNDERFLOW), inIndex, inCount, inBufSize); + return E_SUCCESS; +} + +} } // Tizen::Text diff --git a/src/text/FText_DecoderImpl.h b/src/text/FText_DecoderImpl.h new file mode 100644 index 0000000..77a2d50 --- /dev/null +++ b/src/text/FText_DecoderImpl.h @@ -0,0 +1,145 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_DecoderImpl.h + * @brief This is the header file for the _DecoderImpl class. + */ + +#ifndef _FTEXT_INTERNAL_DECODER_IMPL_H_ +#define _FTEXT_INTERNAL_DECODER_IMPL_H_ + +// Include +#include +#include +#include + + +namespace Tizen { namespace Text +{ + +class _EncodingCore; + +class _DecoderImpl + : public Decoder +{ +// Lifecycle +public: + /** + * This is the destructor for this class. + * + * @since 1.0 + */ + virtual ~_DecoderImpl(void); + + static _DecoderImpl* GetDecoderN(const Tizen::Base::String& encodingType); +// Operations +public: + /** + * Calculates the number of characters produced by decoding a specified range of elements in a ByteBuffer. + * + * @since 1.0 + * @return An error code + * @param[in] bytes The ByteBuffer to decode + * @param[in] byteIndex The starting index where decoding begins + * @param[in] byteCount The number of bytes to decode + * @param[out] charCount The number of characters produced by decoding a range of bytes in the specified ByteBuffer + * @param[in] flush Set to @c true, to allow this instance to flush its state at the end of the conversion @n + * @c false, otherwise + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation caused an underflow. @n + * The sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points, which are outside the bounds specified by the character encoding scheme. + * + * @see Encoder::GetByteCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount, bool flush = false) const; + + /** + * Decodes a ByteBuffer into a WcharBuffer. + * + * @since 1.0 + * @return A new WcharBuffer where the resulting decoded data is stored @n + * @c null, if an exception occurs @n + * The buffer's limit is the position of the last encoded byte plus one in the buffer, and the position is zero + * @param[in] bytes The buffer containing ByteBuffer to decode + * @param[in] flush Set to @c true, to allow this instance to flush its state at the end of the conversion @n + * @c false, otherwise + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points, which are outside the bounds specified by the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * @see Encoder::GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes, bool flush = false) const; + + /** + * Decodes a range of bytes in a ByteBuffer into a range of characters in a WcharBuffer. + * + * @since 1.0 + * @return A new WcharBuffer where the resulting decoded data is stored @n + * @c null, if an exception occurs @n + * The buffer's limit is the position of the last encoded byte in the buffer, and the position is zero + * @param[in] bytes The buffer containing ByteBuffer to decode + * @param[in] byteIndex The starting index where decoding begins + * @param[in] byteCount The number of bytes to decode + * @param[in] flush Set to @c true, to allow this instance to flush its state at the end of the conversion @n + * @c false, otherwise + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation caused an underflow. @n + * The sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points, which are outside the bounds specified by the character encoding scheme. + * @remarks The GetChars() method maintains state consistency between conversions. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks The new ByteBuffer isn't terminated by @c null character. + * + * @see Encoder::GetBytesN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, bool flush = false) const; + +private: + _DecoderImpl(); + + result GetBufferSize(const Tizen::Base::ByteBuffer& bytes, int& byteBufSize) const; + result CheckBufferInput(int inBufSize, int inIndex, int inCount) const; + result Decode(const byte* pSrc, int srcLength, Tizen::Base::WcharBuffer*& pWcharBuffer, int index, bool flush) const; + + + _DecoderImpl(const _DecoderImpl& decoderImpl); + _DecoderImpl& operator =(const _DecoderImpl& decoderImpl); + +private: + std::unique_ptr<_EncodingCore> __pDecoder; + Tizen::Base::String __encodingType; + +}; // _DecoderImpl + +} } // Tizen::Text + +#endif //_FTEXT_INTERNAL_DECODER_IMPL_H_ diff --git a/src/text/FText_EncoderImpl.cpp b/src/text/FText_EncoderImpl.cpp new file mode 100644 index 0000000..1a2090a --- /dev/null +++ b/src/text/FText_EncoderImpl.cpp @@ -0,0 +1,216 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_EncoderImpl.cpp + * @brief This is the implementation file for _EncoderImpl class. + */ + +#include "FText_EncodingCore.h" +#include +#include "FText_EncoderImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +namespace Tizen { namespace Text +{ + +_EncoderImpl::_EncoderImpl(void) + : __pEncoder(null) + , __encodingType("") +{ +} + +_EncoderImpl::~_EncoderImpl(void) +{ + +} + +_EncoderImpl* +_EncoderImpl::GetEncoderN(const String& encodingType) +{ + SysTryReturn(NID_TEXT, (encodingType == L"UTF-8"), null, E_INVALID_ARG, + "[%s] Invalid argument is used.encdoingType(%ls) is not UTF-8.Failed to open encoder.", GetErrorMessage(E_INVALID_ARG), encodingType.GetPointer()); + + std::unique_ptr<_EncoderImpl> pEncoderImpl( new (std::nothrow) _EncoderImpl); + SysTryReturn(NID_TEXT, pEncoderImpl, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + pEncoderImpl->__pEncoder.reset(_EncodingCore::GetEncodingCoreN(encodingType, L"WCHAR_T")); + + result r = GetLastResult(); + SysTryReturn(NID_TEXT, (pEncoderImpl->__pEncoder != null), null, r, + "[%s] Failed to open encoder.", GetErrorMessage(r)); + + pEncoderImpl->__encodingType = encodingType; + pEncoderImpl->_pEncoderImpl = pEncoderImpl.get(); + + SetLastResult(E_SUCCESS); + return pEncoderImpl.release(); +} + +result +_EncoderImpl::Encode(const wchar_t* pSrc, int srcLength, ByteBuffer*& pByteBuffer, int index, bool flush) const +{ + SysAssertf(__pEncoder != null, "Not yet constructed! Construct() should be called before use."); + + SysTryReturnResult(NID_TEXT, (pSrc != null), E_INVALID_ARG, "[%s] Invalid argument is used. pSrc can not be null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturnResult(NID_TEXT, (srcLength >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + SysTryReturnResult(NID_TEXT, (index >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. index(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), index); + + result r = E_SUCCESS; + int currPosition = 0; + int retLength = 0; + bool isMemAllocReq = false; + + std::unique_ptr pDst(__pEncoder->EncodeExN(pSrc, srcLength, retLength, flush)); + r = GetLastResult(); + SysTryReturnResult(NID_TEXT, (pDst != null), r, "[%s] Decoding failed", GetErrorMessage(r)); + + ByteBuffer* pOutBuffer = pByteBuffer; + if (retLength > 0) + { + if (pOutBuffer == null) + { + isMemAllocReq = true; + pOutBuffer = new (std::nothrow) ByteBuffer; + SysTryCatch(NID_TEXT, (pOutBuffer != null), , + E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Byte Buffer allocation failed"); + + r = pOutBuffer->Construct(retLength); + SysTryCatch(NID_TEXT, !IsFailed(r), , r, "[%s] Unable to Construct Byte buffer", GetErrorMessage(r)); + + pByteBuffer = pOutBuffer; + } + else + { + currPosition = pOutBuffer->GetPosition(); + + r = pOutBuffer->SetPosition(index); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set Byte buffer position", GetErrorMessage(r)); + + } + + r = pOutBuffer->SetArray(pDst.get(), 0, retLength); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to fill Byte buffer", GetErrorMessage(r)); + + r = pOutBuffer->SetPosition(currPosition); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set Byte buffer position", GetErrorMessage(r)); + + return r; + } + +CATCH: + if (isMemAllocReq) + { + delete pByteBuffer; + pByteBuffer = null; + } + return r; +} + +result +_EncoderImpl::GetByteCount(const WcharBuffer& chars, int charIndex, int charCount, int& byteCount, bool flush) const +{ + SysAssertf(__pEncoder != null, "Not yet constructed! Construct() should be called before use."); + + byteCount = 0; + int inBufSize = chars.GetLimit(); + result r = CheckBufferInput(inBufSize, charIndex, charCount); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return __pEncoder->GetByteCount((chars.GetPointer() + charIndex), charCount, byteCount); +} + +ByteBuffer* +_EncoderImpl::GetBytesN(const WcharBuffer& chars, bool flush) const +{ + SysAssertf(__pEncoder != null, "Not yet constructed! Construct() should be called before use."); + + ByteBuffer* pBuffer = null; + int srcLength = 0; + result r = GetBufferSize(chars, srcLength); + SysTryReturn(NID_TEXT, (!IsFailed(r)), null, r, "[%s] Input validation failed", GetErrorMessage(r)); + + r = Encode(chars.GetPointer(), srcLength, pBuffer, 0, flush); + + SetLastResult(r); + return pBuffer; +} + +ByteBuffer* +_EncoderImpl::GetBytesN(const WcharBuffer& chars, int charIndex, int charCount, bool flush) const +{ + SysAssertf(__pEncoder != null, "Not yet constructed! Construct() should be called before use."); + + ByteBuffer* pBuffer = null; + int srcLength = chars.GetLimit(); + result r = CheckBufferInput(srcLength, charIndex, charCount); + SysTryReturn(NID_TEXT, (!IsFailed(r)), null, r, "[%s] Input validation failed", GetErrorMessage(r)); + + r = Encode(chars.GetPointer() + charIndex, charCount, pBuffer, 0, flush); + + SetLastResult(r); + return pBuffer; +} + +result +_EncoderImpl::GetBufferSize(const WcharBuffer& chars, int& charBufSize) const +{ + // It is assumed that user has set limit properly + charBufSize = chars.GetLimit(); + + // Adjusting byteBufSize if bytes has null char at the end + wchar_t lastChar = -1; + result r = chars.Get(charBufSize - 1, lastChar); + SysTryReturnResult(NID_TEXT, (!IsFailed(r)), E_INVALID_ARG, "[%s] Last byte check failed", GetErrorMessage(r)); + + if ((lastChar == '\0')and(charBufSize > 1)) + { + charBufSize -= 1; + } + SysTryReturnResult(NID_TEXT, (charBufSize > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. charBufSize [%d] is invalid.", GetErrorMessage(E_INVALID_ARG), charBufSize); + + return E_SUCCESS; +} + +result +_EncoderImpl::CheckBufferInput(int inBufSize, int inIndex, int inCount) const +{ + SysTryReturnResult(NID_TEXT, (inIndex >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inIndex(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inIndex); + SysTryReturnResult(NID_TEXT, (inCount >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inCount(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inCount); + SysTryReturnResult(NID_TEXT, (inBufSize > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inBufSize(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inBufSize); + + SysTryReturnResult(NID_TEXT, (inBufSize > inIndex), E_OUT_OF_RANGE, + "[%s] inIndex(%d) is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE), inIndex); + SysTryReturnResult(NID_TEXT, (inBufSize >= inCount), E_OUT_OF_RANGE, + "[%s] inCount(%d) is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE), inCount); + SysTryReturnResult(NID_TEXT, (inBufSize >= (inIndex + inCount)), E_UNDERFLOW, + "[%s] sum of the length of the inIndex(%d) and inCount(%d) is greater than inBufSize(%d).", + GetErrorMessage(E_UNDERFLOW), inIndex, inCount, inBufSize); + + return E_SUCCESS; +} + +} } // Tizen::Text diff --git a/src/text/FText_EncoderImpl.h b/src/text/FText_EncoderImpl.h new file mode 100644 index 0000000..fb6955c --- /dev/null +++ b/src/text/FText_EncoderImpl.h @@ -0,0 +1,147 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_EncoderImpl.h + * @brief This is the header file for the _EncoderImpl class. + */ + +#ifndef _FTEXT_INTERNAL_ENCODER_IMPL_H_ +#define _FTEXT_INTERNAL_ENCODER_IMPL_H_ + +// Include +#include +#include +#include + + +namespace Tizen { namespace Text +{ + +class _EncodingCore; + +class _EncoderImpl + : public Encoder +{ +// Lifecycle +public: + /** + * This is the destructor for this class. + * + * @since 1.0 + */ + virtual ~_EncoderImpl(void); + + static _EncoderImpl* GetEncoderN(const Tizen::Base::String& encodingType); +// Operations +// Operations +public: + /** + * Calculates the number of bytes required to encode a range of characters in the specified WcharBuffer. + * + * @since 1.0 + * @return An error code + * @param[in] chars The buffer containing the character array to encode + * @param[in] charIndex The starting index of the WcharBuffer to encode + * @param[in] charCount The number of characters to encode + * @param[in] flush Set to @c true, to allow this instance to flush its state at the end of the conversion @n + * @c false, otherwise + * @param[out] byteCount The number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c charIndex or @c charCount is greater than the @n + * length of the specified @c chars. + * @exception E_UNDERFLOW This operation caused an underflow. @n + * The sum of the length of the specified @c charIndex and @c charCount is greater + * than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points, which are outside the bounds specified @n + * by the character encoding scheme. + * + * @see Decoder::GetCharCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, int& byteCount, bool flush = false) const; + + /** + * Encodes a specified WcharBuffer into a ByteBuffer. + * + * @since 1.0 + * @return A new ByteBuffer where the resulting encoded string is stored @n + * @c null, if an exception occurs @n + * The buffer's limit is the position of the last encoded byte plus one in the buffer, and the position is zero + * @param[in] chars The WcharBuffer to encode + * @param[in] flush Set to @c true, to allow this instance to flush its state at the end of the conversion @n + * @c false, otherwise + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points, which are outside the bounds specified by the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * @see Decoder::GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars, bool flush = false) const; + + /** + * Encodes a range of characters from a WcharBuffer into a ByteBuffer. + * + * @since 1.0 + * @return A new ByteBuffer where the resulting encoded string is stored @n + * @c null if an exception occurs @n + * The buffer's limit is the position of the last encoded byte in the buffer, and the position is zero + * @param[in] chars The buffer containing the character array to encode + * @param[in] charIndex The starting index of the WcharBuffer to encode + * @param[in] charCount The number of characters to encode + * @param[in] flush Set to @c true, to allow this instance to flush its state at the end of the conversion @n + * @c false, otherwise + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation caused an underflow. @n + * The sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points, which are outside the bounds specified by the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * @remarks The new ByteBuffer isn't terminated by @c null character. + * + * @see Decoder::GetCharsN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, bool flush = false) const; + +private: + _EncoderImpl(); + + result GetBufferSize(const Tizen::Base::WcharBuffer& chars, int& charBufSize) const; + result CheckBufferInput(int inBufSize, int inIndex, int inCount) const; + result Encode(const wchar_t* pSrc, int srcLength, Tizen::Base::ByteBuffer*& pByteBuffer, int index, bool flush) const; + + _EncoderImpl(const _EncoderImpl& encoderImpl); + _EncoderImpl& operator =(const _EncoderImpl& encoderImpl); + +private: + std::unique_ptr<_EncodingCore> __pEncoder; + Tizen::Base::String __encodingType; + +}; // _EncoderImpl + +} } // Tizen::Text + +#endif //_FTEXT_INTERNAL_ENCODER_IMPL_H_ diff --git a/src/text/FText_EncodingCore.cpp b/src/text/FText_EncodingCore.cpp new file mode 100644 index 0000000..08fbf97 --- /dev/null +++ b/src/text/FText_EncodingCore.cpp @@ -0,0 +1,146 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_EncodingCore.cpp + * @brief This is the implementation file for _EncodingCore class. + */ + +// Includes +#include +#include "FText_EncodingCore.h" +#include +#include +#include "FText_IcuEncodingCore.h" +#include "FText_GsmEncodingCore.h" +#include "FText_Ucs2EncodingCore.h" +#include "FText_Iso885916EncodingCore.h" + +using namespace std; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; + +namespace Tizen { namespace Text +{ + +_EncodingCore::_EncodingCore(void) + : _encodingTo() + , _encodingFrom() +{ +} + +_EncodingCore::~_EncodingCore(void) +{ +} + + +_EncodingCore* +_EncodingCore::GetEncodingCoreN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo) +{ + _EncodingCore* pEncoderDecoder = null; + + pEncoderDecoder = _Ucs2EncodingCore::GetEncodingCoreImplN(encodingFrom, encodingTo); + if (pEncoderDecoder) + { + return pEncoderDecoder; + } + + pEncoderDecoder = _IcuEncodingCore::GetEncodingCoreImplN(encodingFrom, encodingTo); + if (pEncoderDecoder) + { + return pEncoderDecoder; + } + + pEncoderDecoder = _GsmEncodingCore::GetEncodingCoreImplN(encodingFrom, encodingTo); + if (pEncoderDecoder) + { + return pEncoderDecoder; + } + + pEncoderDecoder = _Iso885916EncodingCore::GetEncodingCoreImplN(encodingFrom, encodingTo); + if (pEncoderDecoder) + { + return pEncoderDecoder; + } + + return null; +} + +IList* +_EncodingCore::GetAvailableEncodingsN(void) +{ + ClearLastResult(); + result r = E_SUCCESS; + + unique_ptr pList(new (std::nothrow) LinkedList()); + SysTryReturn(NID_TEXT, pList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + _IcuEncodingCore icuConverter; + _GsmEncodingCore gsmConverter; + _Ucs2EncodingCore ucs2Converter; + _Iso885916EncodingCore iso885916Converter; + + r = icuConverter.GetAvailableEncodingsN(pList.get()); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Available encoding list is empty. List allocation failed.", GetErrorMessage(r)); + + r = gsmConverter.GetAvailableEncodingsN(pList.get()); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Available encoding list is empty. List allocation failed.", GetErrorMessage(r)); + + r = ucs2Converter.GetAvailableEncodingsN(pList.get()); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Available encoding list is empty. List allocation failed.", GetErrorMessage(r)); + + r = iso885916Converter.GetAvailableEncodingsN(pList.get()); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Available encoding list is empty. List allocation failed.", GetErrorMessage(r)); + + return pList.release(); +} + +byte* +_EncodingCore::ConvertN(_EncodingCore* pDstConverter, const byte* pSrc, int srcLength, int& retLength) +{ + result r = E_SUCCESS; + + SysTryReturn(NID_TEXT, pDstConverter != null, null, E_INVALID_ARG, + "[%s] Invalid argument is used. Unable to get encoder decoder object. pDstConverter can not be null", GetErrorMessage(E_INVALID_ARG)); + + unique_ptr pWchar(DecodeN(pSrc, srcLength, retLength)); + r = GetLastResult(); + SysTryReturn(NID_TEXT, (pWchar != null), null, r, "[%s] Decoding failed", GetErrorMessage(r)); + + unique_ptr pByte(pDstConverter->EncodeN(pWchar.get(), retLength, retLength)); + r = GetLastResult(); + SysTryReturn(NID_TEXT, (pByte != null), null, r, "[%s] Decoding failed", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return pByte.release(); +} + +byte* +_EncodingCore::EncodeExN(const wchar_t* pSrc, int srcLength, int& retLength, bool flush) +{ + SetLastResult(E_UNSUPPORTED_OPERATION); + return null; +} + +wchar_t* +_EncodingCore::DecodeExN(const byte* pSrc, int srcLength, int& retLength, bool flush) +{ + SetLastResult(E_UNSUPPORTED_OPERATION); + return null; +} + +} } // Tizen::Text diff --git a/src/text/FText_EncodingImpl.cpp b/src/text/FText_EncodingImpl.cpp new file mode 100644 index 0000000..c5ae8f4 --- /dev/null +++ b/src/text/FText_EncodingImpl.cpp @@ -0,0 +1,693 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_EncodingImpl.cpp + * @brief This is the implementation file for _EncodingImpl class. + */ + +#include +#include "FText_EncodingCore.h" +#include +#include "FText_EncodingImpl.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +#define AVAILABLE_ENCODING_COUNT 45 +static String availableEncodings[] = +{ +L"ASCII", +L"GSM", +L"KSC5601", +L"Big5", +L"GB2312", +L"UTF-8", +L"UTF-16", +L"UTF-16BE", +L"UTF-16LE", +L"UTF-32", +L"UTF-32BE", +L"UTF-32LE", +L"UCS-2", +L"UCS-2BE", +L"UCS-2LE", +L"UCS-4", +L"UCS-4BE", +L"UCS-4LE", +L"ISO-8859-1", +L"ISO-8859-2", +L"ISO-8859-3", +L"ISO-8859-4", +L"ISO-8859-5", +L"ISO-8859-6", +L"ISO-8859-7", +L"ISO-8859-8", +L"ISO-8859-9", +L"ISO-8859-10", +L"ISO-8859-11", +L"ISO-8859-13", +L"ISO-8859-14", +L"ISO-8859-15", +L"ISO-8859-16", +L"Windows-874", +L"Windows-1250", +L"Windows-1251", +L"Windows-1252", +L"Windows-1253", +L"Windows-1254", +L"Windows-1255", +L"Windows-1256", +L"Windows-1257", +L"Windows-1258", +L"Shift-JIS", +L"ISO-2022-JP", +}; + +namespace Tizen { namespace Text +{ + +_EncodingImpl::_EncodingImpl(void) + : Encoding() + , __encodingType() + , __pEncodingCore(null) +{ +} + +_EncodingImpl::~_EncodingImpl(void) +{ + +} + +result +_EncodingImpl::Construct(const String& encodingType) +{ + // Object is not allowed to construct twice + SysAssertf(__pEncodingCore == null, + "Already constructed! Calling Construct() twice or more on a same instance is not allowed for this class"); + + SysTryReturnResult(NID_TEXT, IsEncodingSupported(encodingType), + E_UNSUPPORTED_TYPE, "[%s] encodingType[%ls] is not supported", GetErrorMessage(E_UNSUPPORTED_TYPE), encodingType.GetPointer()); + + __pEncodingCore.reset(_EncodingCore::GetEncodingCoreN(encodingType, L"WCHAR_T")); + + result r = GetLastResult(); + SysTryReturnResult(NID_TEXT, (__pEncodingCore != null), r, "[%s] Failed to open encoder/decoder.", GetErrorMessage(r)); + + __encodingType = encodingType; + _pEncodingImpl = this; + + return E_SUCCESS; +} + +result +_EncodingImpl::Encode(const wchar_t* pSrc, int srcLength, ByteBuffer*& pByteBuffer, int index) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + SysTryReturnResult(NID_TEXT, (pSrc != null), E_INVALID_ARG, "[%s] Invalid argument is used. pSrc can not be null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturnResult(NID_TEXT, (srcLength >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + SysTryReturnResult(NID_TEXT, (index >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. index(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), index); + + result r = E_SUCCESS; + int currPosition = 0; + int retLength = 0; + bool isMemAllocReq = false; + + std::unique_ptr pDst(__pEncodingCore->EncodeN(pSrc, srcLength, retLength)); + r = GetLastResult(); + SysTryReturnResult(NID_TEXT, (pDst != null), r, "[%s] Decoding failed", GetErrorMessage(r)); + + ByteBuffer* pOutBuffer = pByteBuffer; + if (retLength > 0) + { + if (pOutBuffer == null) + { + isMemAllocReq = true; + pOutBuffer = new (std::nothrow) ByteBuffer; + SysTryCatch(NID_TEXT, (pOutBuffer != null), , E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pOutBuffer->Construct(retLength + 1); + SysTryCatch(NID_TEXT, !IsFailed(r), , r, "[%s] Unable to Construct Byte buffer", GetErrorMessage(r)); + + pByteBuffer = pOutBuffer; + } + else + { + currPosition = pOutBuffer->GetPosition(); + + r = pOutBuffer->SetPosition(index); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set Byte buffer position", GetErrorMessage(r)); + } + r = pOutBuffer->SetArray(pDst.get(), 0, retLength); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to fill Byte buffer", GetErrorMessage(r)); + + r = pOutBuffer->SetPosition(currPosition); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set Byte buffer position", GetErrorMessage(r)); + + return r; + } + +CATCH: + if (isMemAllocReq) + { + delete pByteBuffer; + pByteBuffer = null; + } + return r; +} + +result +_EncodingImpl::Decode(const byte* pSrc, int srcLength, WcharBuffer*& pWcharBuffer, int index) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + SysTryReturnResult(NID_TEXT, (pSrc != null), E_INVALID_ARG, "[%s] Invalid argument is used. pSrc can not be null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturnResult(NID_TEXT, (srcLength >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + SysTryReturnResult(NID_TEXT, (index >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. index(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), index); + + result r = E_SUCCESS; + int currPosition = 0; + int retLength = 0; + bool isMemAllocReq = false; + + std::unique_ptr pDst(__pEncodingCore->DecodeN(pSrc, srcLength, retLength)); + r = GetLastResult(); + SysTryReturnResult(NID_TEXT, (pDst != null), r, "[%s] Decoding failed", GetErrorMessage(r)); + + WcharBuffer* pOutBuffer = pWcharBuffer; + if (retLength > 0) + { + if (pOutBuffer == null) + { + isMemAllocReq = true; + pOutBuffer = new (std::nothrow) WcharBuffer; + SysTryCatch(NID_TEXT, (pOutBuffer != null), , E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pOutBuffer->Construct(retLength + 1); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to Construct Byte buffer", GetErrorMessage(r)); + + r = pOutBuffer->SetArray(pDst.get(), 0, retLength); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to fill Byte buffer", GetErrorMessage(r)); + + r = pOutBuffer->Set(L'\0'); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set null Byte", GetErrorMessage(r)); + + pOutBuffer->Rewind(); + pWcharBuffer = pOutBuffer; + } + else + { + currPosition = pOutBuffer->GetPosition(); + + r = pOutBuffer->SetPosition(index); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set Byte buffer position", GetErrorMessage(r)); + + r = pOutBuffer->SetArray(pDst.get(), 0, retLength); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to fill Byte buffer", GetErrorMessage(r)); + + r = pOutBuffer->SetPosition(currPosition); + SysTryCatch(NID_TEXT, (!IsFailed(r)), , r, "[%s] Unable to set Byte buffer position", GetErrorMessage(r)); + } + return r; + } + +CATCH: + if (isMemAllocReq) + { + delete pWcharBuffer; + pWcharBuffer = null; + } + return r; +} + +result +_EncodingImpl::Decode(const byte* pSrc, int srcLength, String& outStr, int index) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + SysTryReturnResult(NID_TEXT, (pSrc != null), E_INVALID_ARG, "[%s] Invalid argument is used. pSrc can not be null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturnResult(NID_TEXT, (srcLength >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + SysTryReturnResult(NID_TEXT, (index >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. index(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), index); + + result r = E_SUCCESS; + int retLength = 0; + + std::unique_ptr pDst(__pEncodingCore->DecodeN(pSrc, srcLength, retLength)); + r = GetLastResult(); + SysTryReturnResult(NID_TEXT, (pDst != null), r, "[%s] Decoding failed", GetErrorMessage(r)); + + outStr = pDst.get(); + + return E_SUCCESS; +} + +result +_EncodingImpl::GetByteCount(const String& str, int& byteCount) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + byteCount = -1; + int srcLength = str.GetLength(); + SysTryReturnResult(NID_TEXT, (srcLength > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. Input string is empty.", GetErrorMessage(E_INVALID_ARG)); + + return __pEncodingCore->GetByteCount(str.GetPointer(), srcLength, byteCount); +} + +result +_EncodingImpl::GetByteCount(const WcharBuffer& chars, int& byteCount) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + byteCount = -1; + int srcLength = 0; + result r = GetBufferSize(chars, srcLength); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return __pEncodingCore->GetByteCount(chars.GetPointer(), srcLength, byteCount); +} + +result +_EncodingImpl::GetByteCount(const WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + byteCount = -1; + int inBufSize = chars.GetLimit(); + result r = CheckBufferInput(inBufSize, charIndex, charCount); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return __pEncodingCore->GetByteCount((chars.GetPointer() + charIndex), charCount, byteCount); +} + +result +_EncodingImpl::GetCharCount(const ByteBuffer& bytes, int& charCount) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + charCount = -1; + int srcLength = 0; + result r = GetBufferSize(bytes, srcLength); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return __pEncodingCore->GetCharCount(bytes.GetPointer(), srcLength, charCount); +} + +result +_EncodingImpl::GetCharCount(const ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + charCount = -1; + int inBufSize = bytes.GetLimit(); + result r = CheckBufferInput(inBufSize, byteIndex, byteCount); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return __pEncodingCore->GetCharCount((bytes.GetPointer() + byteIndex), byteCount, charCount); +} + +ByteBuffer* +_EncodingImpl::GetBytesN(const WcharBuffer& chars) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + ByteBuffer* pBuffer = null; + int srcLength = 0; + result r = GetBufferSize(chars, srcLength); + SysTryReturn(NID_TEXT, (!IsFailed(r)), null, r, "[%s] Input validation failed", GetErrorMessage(r)); + + r = Encode(chars.GetPointer(), srcLength, pBuffer, 0); + + SetLastResult(r); + return pBuffer; +} + +ByteBuffer* +_EncodingImpl::GetBytesN(const String& str) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + ByteBuffer* pBuffer = null; + int srcLength = str.GetLength(); + SysTryReturn(NID_TEXT, (srcLength > 0), null, E_INVALID_ARG, + "[%s] Invalid argument is used. Input string is empty.", GetErrorMessage(E_INVALID_ARG)); + + result r = Encode(str.GetPointer(), srcLength, pBuffer, 0); + + SetLastResult(r); + return pBuffer; +} + +result +_EncodingImpl::GetBytes(const WcharBuffer& chars, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + ByteBuffer* pBuffer = &bytes; + int srcLen = chars.GetLimit(); + int destLen = bytes.GetLimit(); + + result r = CheckBufferInput(srcLen, charIndex, charCount, destLen, byteIndex); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return Encode((chars.GetPointer() + charIndex), charCount, pBuffer, byteIndex); +} + +result +_EncodingImpl::GetBytes(const String& str, int charIndex, int charCount, ByteBuffer& bytes, int byteIndex) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + ByteBuffer* pBuffer = &bytes; + int srcLen = str.GetLength(); + int destLen = bytes.GetLimit(); + + result r = CheckBufferInput(srcLen, charIndex, charCount, destLen, byteIndex); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return Encode((str.GetPointer() + charIndex), charCount, pBuffer, byteIndex); +} + +WcharBuffer* +_EncodingImpl::GetCharsN(const ByteBuffer& bytes) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + WcharBuffer* pBuffer = null; + int srcLength = 0; + result r = GetBufferSize(bytes, srcLength); + SysTryReturn(NID_TEXT, (!IsFailed(r)), null, r, "[%s] Input validation failed", GetErrorMessage(r)); + + r = Decode(bytes.GetPointer(), srcLength, pBuffer, 0); + + SetLastResult(r); + return pBuffer; +} + +result +_EncodingImpl::GetChars(const ByteBuffer& bytes, int byteIndex, int byteCount, WcharBuffer& chars, int charIndex) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + WcharBuffer* pBuffer = &chars; + int srcLen = bytes.GetLimit(); + int destLen = chars.GetLimit(); + + result r = CheckBufferInput(srcLen, byteIndex, byteCount, destLen, charIndex); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return Decode((bytes.GetPointer() + byteIndex), byteCount, pBuffer, charIndex); +} + +result +_EncodingImpl::GetString(const ByteBuffer& bytes, Tizen::Base::String& str) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + int srcLength = 0; + result r = GetBufferSize(bytes, srcLength); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + return Decode(bytes.GetPointer(), srcLength, str, 0); +} + +result +_EncodingImpl::GetString(const ByteBuffer& bytes, int index, int count, String& str) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + + int srcLen = bytes.GetLimit(); + result r = CheckBufferInput(srcLen, index, count); + SysTryReturn(NID_TEXT, (!IsFailed(r)), r, r, "[%s] Input validation failed", GetErrorMessage(r)); + + if (count == 0) + { + str = ""; + return E_SUCCESS; + } + + return Decode((bytes.GetPointer() + index), count, str, 0); +} + +ByteBuffer* +_EncodingImpl::ConvertImplN(const Encoding& src, const Encoding& dst, const ByteBuffer& srcBytes) +{ + const _EncodingImpl* pSrcEncodingImpl = src._pEncodingImpl; + SysTryReturn(NID_TEXT, (pSrcEncodingImpl != null), null, E_INVALID_ARG, "[E_INVALID_ARG] Unable to get encoder object"); + + int inBufSize = -1; + result r = pSrcEncodingImpl->GetBufferSize(srcBytes, inBufSize); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Unable to get byte buffer size", GetErrorMessage(r)); + + return ConvertN(src, dst, srcBytes, 0, inBufSize); +} + +ByteBuffer* +_EncodingImpl::ConvertImplN(const Encoding& src, const Encoding& dst, const ByteBuffer& srcBytes, int index, int count) +{ + const _EncodingImpl* pSrcEncodingImpl = src._pEncodingImpl; + SysTryReturn(NID_TEXT, (pSrcEncodingImpl != null), null, E_INVALID_ARG, "[%s] Unable to get encoder object", GetErrorMessage(E_INVALID_ARG)); + + _EncodingCore* pSrcConverter = pSrcEncodingImpl->__pEncodingCore.get(); + SysTryReturn(NID_TEXT, (pSrcConverter != null), null, E_INVALID_ARG, "[%s] Unable to get encoder decoder object", GetErrorMessage(E_INVALID_ARG)); + + const _EncodingImpl* pDstEncodingImpl = dst._pEncodingImpl; + SysTryReturn(NID_TEXT, (pDstEncodingImpl != null), null, E_INVALID_ARG, "[%s] Unable to get encoder object", GetErrorMessage(E_INVALID_ARG)); + + _EncodingCore* pDstConverter = pDstEncodingImpl->__pEncodingCore.get(); + SysTryReturn(NID_TEXT, (pDstConverter != null), null, E_INVALID_ARG, "[%s] Unable to get encoder decoder object", GetErrorMessage(E_INVALID_ARG)); + + int inBufSize = srcBytes.GetLimit(); + + result r = pSrcEncodingImpl->CheckBufferInput(inBufSize, index, count); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Unable to get byte buffer size", GetErrorMessage(r)); + + int retLength = -1; + + std::unique_ptr pByte(pSrcConverter->ConvertN(pDstConverter, srcBytes.GetPointer() + index, count, retLength)); + r = GetLastResult(); + SysTryReturn(NID_TEXT, (pByte != null), null, r, "[%s] Unable to get encoder object", GetErrorMessage(r)); + + std::unique_ptr pOutBuffer(new (std::nothrow) ByteBuffer); + SysTryReturn(NID_TEXT, pOutBuffer != null, null, + E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pOutBuffer->Construct(retLength + 1); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Unable to Construct Byte buffer", GetErrorMessage(r)); + + r = pOutBuffer->SetArray(pByte.get(), 0, retLength); + SysTryReturn(NID_TEXT, (!IsFailed(r)), null, r, "[%s] Unable to fill Byte buffer", GetErrorMessage(r)); + + pOutBuffer->Rewind(); + + SetLastResult(E_SUCCESS); + return pOutBuffer.release(); +} + +int +_EncodingImpl::GetMaxByteCount(int charCount) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + return __pEncodingCore->GetMaxByteCount(charCount); +} + +int +_EncodingImpl::GetMaxCharCount(int byteCount) const +{ + SysAssertf(__pEncodingCore != null, "Not yet constructed! Construct() should be called before use."); + return __pEncodingCore->GetMaxCharCount(byteCount); +} + +Encoder* +_EncodingImpl::GetEncoderN(void) const +{ + return null; +} + +Decoder* +_EncodingImpl::GetDecoderN(void) const +{ + return null; +} + +IList* +_EncodingImpl::GetAvailableEncodingsImplN(void) +{ + ClearLastResult(); + result r = E_SUCCESS; + + std::unique_ptr pList(new (std::nothrow) LinkedList()); + + SysTryReturn(NID_TEXT, pList != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + for (int i = 0; i < AVAILABLE_ENCODING_COUNT; i++) + { + String* pEncodingStr = new (std::nothrow) String(availableEncodings[i]); + SysTryReturn(NID_TEXT, pEncodingStr, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pList->Add(*pEncodingStr); + if(IsFailed(r)) + { + delete pEncodingStr; + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Unable to add encoding to list", GetErrorMessage(r)); + } + } + + return pList.release(); +} + +result +_EncodingImpl::GetBufferSize(const WcharBuffer& chars, int& charBufSize) const +{ + charBufSize = StringUtil::GetStringLengthInMb(chars); + + // This check is to correct tmpSize if chars does not contain null char + if (charBufSize == -1) + { + charBufSize = chars.GetLimit(); + } + + SysTryReturnResult(NID_TEXT, (charBufSize > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. charBufSize(%d) is less than 0.", GetErrorMessage(E_INVALID_ARG), charBufSize); + return E_SUCCESS; +} + +result +_EncodingImpl::GetBufferSize(const ByteBuffer& bytes, int& byteBufSize) const +{ + // It is assumed that user has set limit properly + byteBufSize = bytes.GetLimit(); + + int minByteCountForEncoding = 1; + if (__pEncodingCore) + { + minByteCountForEncoding = 4 / __pEncodingCore->GetMaxCharCount(4); + } + + byte lastByte = '\0'; + bool nullAtTheEnd = false; + result r = bytes.GetByte(byteBufSize - 1, lastByte); + SysTryReturnResult(NID_TEXT, (!IsFailed(r)), E_INVALID_ARG, "[%s] Last byte check failed", GetErrorMessage(r)); + + if ((lastByte == '\0')and(byteBufSize > 1)) + { + nullAtTheEnd = true; + if ((byteBufSize % minByteCountForEncoding) == 0) + { + for (int i = 0; i < minByteCountForEncoding; i++) + { + byte lastByte = 0; + result r = bytes.GetByte(byteBufSize - i - 1, lastByte); + SysTryReturnResult(NID_TEXT, (!IsFailed(r)), E_INVALID_ARG, "[%s] Last byte check failed", GetErrorMessage(r)); + + if (lastByte != '\0') + { + nullAtTheEnd = false; + } + } + } + + if (nullAtTheEnd) + { + byteBufSize -= 1; + } + } + + SysTryReturnResult(NID_TEXT, (byteBufSize > 0), E_INVALID_ARG, "byteBufSize [%d] is invalid.", byteBufSize); + return E_SUCCESS; +} + +result +_EncodingImpl::CheckBufferInput(int inBufSize, int inIndex, int inCount) const +{ + SysTryReturnResult(NID_TEXT, (inIndex >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inIndex(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inIndex); + SysTryReturnResult(NID_TEXT, (inCount >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inCount(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inCount); + SysTryReturnResult(NID_TEXT, (inBufSize > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inBufSize(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inBufSize); + + SysTryReturnResult(NID_TEXT, (inBufSize > inIndex), E_OUT_OF_RANGE, + "[%s] inIndex(%d) is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE), inIndex); + SysTryReturnResult(NID_TEXT, (inBufSize >= inCount), E_OUT_OF_RANGE, + "[%s] inCount(%d) is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE), inCount); + SysTryReturnResult(NID_TEXT, (inBufSize >= (inIndex + inCount)), E_UNDERFLOW, + "[%s] sum of the length of the inIndex(%d) and inCount(%d) is greater than inBufSize(%d).", + GetErrorMessage(E_UNDERFLOW), inIndex, inCount, inBufSize); + + return E_SUCCESS; +} + +result +_EncodingImpl::CheckBufferInput(int inBufSize, int inIndex, int inCount, int outBufSize, int outIndex) const +{ + SysTryReturnResult(NID_TEXT, (inIndex >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inIndex(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inIndex); + SysTryReturnResult(NID_TEXT, (inCount >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inCount(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inCount); + SysTryReturnResult(NID_TEXT, (outIndex >= 0), E_INVALID_ARG, + "[%s] Invalid argument is used. outIndex(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), outIndex); + SysTryReturnResult(NID_TEXT, (inBufSize > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. inBufSize(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), inBufSize); + + SysTryReturnResult(NID_TEXT, (inBufSize > inIndex), E_OUT_OF_RANGE, + "[%s] inIndex(%d) is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE), inIndex); + SysTryReturnResult(NID_TEXT, (inBufSize >= inCount), E_OUT_OF_RANGE, + "[%s] inCount(%d) is outside the valid range.", GetErrorMessage(E_OUT_OF_RANGE), inCount); + SysTryReturnResult(NID_TEXT, (inBufSize >= (inIndex + inCount)), E_UNDERFLOW, + "[%s] sum of the length of the inIndex(%d) and inCount(%d) is greater than inBufSize(%d).", + GetErrorMessage(E_UNDERFLOW), inIndex, inCount, inBufSize); + + SysTryReturnResult(NID_TEXT, (outBufSize > 0), E_INVALID_ARG, + "[%s] Invalid argument is used. outBufSize(%d) cannot be negative.", GetErrorMessage(E_INVALID_ARG), outBufSize); + SysTryReturnResult(NID_TEXT, (outBufSize > outIndex), E_OVERFLOW, "[%s] outIndex [%d] is outside the valid range.", GetErrorMessage(E_OVERFLOW), outIndex); + + return E_SUCCESS; +} + +String +_EncodingImpl::GetEncodingType(void) const +{ + return __encodingType; +} + +bool +_EncodingImpl::IsEncodingSupported(const Tizen::Base::String& encodingStr) const +{ + SysTryReturn(NID_TEXT, !encodingStr.IsEmpty(), false, E_INVALID_ARG, "[%s] Invalid argument is used. Input string is empty", GetErrorMessage(E_INVALID_ARG)); + + bool retValue = false; + for (int i = 0; i < AVAILABLE_ENCODING_COUNT; i++) + { + if (encodingStr.Equals(availableEncodings[i], false)) + { + retValue = true; + break; + } + } + return retValue; +} + +} } // Tizen::Text diff --git a/src/text/FText_EncodingImpl.h b/src/text/FText_EncodingImpl.h new file mode 100644 index 0000000..c119ed0 --- /dev/null +++ b/src/text/FText_EncodingImpl.h @@ -0,0 +1,495 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_EncodingImpl.h + * @brief This is the header file for the _EncodingImpl class. + */ + +#ifndef _FTEXT_INTERNAL_ENCODING_IMPL_H_ +#define _FTEXT_INTERNAL_ENCODING_IMPL_H_ + +// Include +#include +#include +#include + + +namespace Tizen { namespace Text +{ + +class _EncodingCore; + +class _EncodingImpl + : public Encoding +{ +// Lifecycle +public: + /** + * This is the constructor for this class. + */ + _EncodingImpl(void); + + + /** + * This is the destructor for this class. + */ + virtual ~_EncodingImpl(void); + + + /** + * Constructs the instance of this class. + */ + result Construct(const Tizen::Base::String& encoding); + + +// Operations +public: + /** + * Calculates the number of bytes required to encode the specified string. + * + * @since 1.0 + * @return An error code + * @param[in] str The string to encode + * @param[out] byteCount The number of bytes required to encode @c str + * + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c str is an empty string. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds @n + * specified by the character encoding scheme. + * + * @remarks This method can be used to determine the exact number of bytes + * that are produced if the specified string is encoded. + * + * @see GetMaxByteCount() + */ + virtual result GetByteCount(const Tizen::Base::String& str, int& byteCount) const; + + /** + * Calculates the number of bytes required to encode the specified characters. + * + * @since 1.0 + * @return An error code + * @param[in] chars The buffer containing the character array to encode + * @param[out] byteCount The number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks This method can be used to determine the exact number of bytes + * that are produced if the specified array of characters is encoded. + * + * @see GetMaxByteCount(), GetByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int& byteCount) const; + + /** + * Calculates the number of bytes required to encode a range of characters in the specified WcharBuffer. + * + * @since 1.0 + * @return An error code + * @param[in] chars The buffer containing the character array to encode + * @param[in] charIndex The starting index of the WcharBuffer to encode + * @param[in] charCount The number of characters to encode + * @param[out] byteCount The number of bytes required to encode the specified range of characters + * @exception E_SUCCESS The method was successful. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c chars is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused an underflow. @n + * The sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks This method can be used to determine the exact number of bytes + * that are produced if the specified array of characters is encoded. + * + * @see GetMaxByteCount(), GetByteCount() + */ + virtual result GetByteCount(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, int& byteCount) const; + + /** + * Encodes the specified WcharBuffer into a ByteBuffer. + * + * @since 1.0 + * @return A new ByteBuffer where the resulting encoded string is stored @n + * @c null, if an exception occurs @n + * The buffer's limit is the position of the last encoded byte plus one in the buffer, and the position @c 0 + * @param[in] chars The WcharBuffer to encode + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c chars is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * @see GetCharsN(), GetBytesN() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::WcharBuffer& chars) const; + + /** + * Encodes the specified string into a ByteBuffer. + * + * @since 1.0 + * @return A new ByteBuffer where the resulting encoded string is stored @n + * @c null, if an exception occurs @n + * The buffer's limit is the position of the last encoded byte plus one in the buffer, and the position @c 0 + * @param[in] str The string to encode + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c str is an empty string. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * @see GetString() + */ + virtual Tizen::Base::ByteBuffer* GetBytesN(const Tizen::Base::String& str) const; + + /** + * Encodes a range of characters from the specified WcharBuffer into a ByteBuffer. + * The ByteBuffer's position and limit are not changed. + * + * @since 1.0 + * @return An error code + * @param[in] chars The buffer containing the character array to encode + * @param[in] charIndex The starting index of the WcharBuffer to encode + * @param[in] charCount The number of characters to encode + * @param[out] bytes The ByteBuffer where the resulting encoded string is stored + * @param[in] byteIndex The starting index of the resulting encoding in the ByteBuffer + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c chars or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c charIndex or @c charCount is greater than the length of the specified @c chars. + * @exception E_UNDERFLOW This operation has caused an underflow. @n + * The sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c chars. + * @exception E_OVERFLOW This operation has caused an overflow. @n + * The specified @c bytes do not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks This method encodes a range of characters in a WcharBuffer into a range of bytes in a ByteBuffer. + * + * @see GetChars() + */ + virtual result GetBytes(const Tizen::Base::WcharBuffer& chars, int charIndex, int charCount, Tizen::Base::ByteBuffer& bytes, int byteIndex) const; + + /** + * Encodes the specified range of a string into the specified range of a ByteBuffer. + * The ByteBuffer's position and limit are not changed. + * + * @since 1.0 + * @return An error code + * @param[in] str The string to encode + * @param[in] charIndex The starting index of the WcharBuffer to encode + * @param[in] charCount The number of characters to encode + * @param[out] bytes The ByteBuffer where the resulting encoded string is stored + * @param[in] byteIndex The starting index of the resulting encoding in the ByteBuffer + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c str or @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c charIndex or @c charCount is greater than the length of the specified @c str. + * @exception E_UNDERFLOW This operation has caused an underflow. @n + * The sum of the length of the specified @c charIndex and @c charCount is greater than the length of the specified @c str. + * @exception E_OVERFLOW This operation has caused an overflow. @n + * The specified @c bytes does not contain sufficient space to store the encoded characters. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * + * @see GetString() + */ + virtual result GetBytes(const Tizen::Base::String& str, int charIndex, int charCount, Tizen::Base::ByteBuffer& bytes, int byteIndex) const; + + /** + * Calculates the number of characters produced by decoding a ByteBuffer. + * + * @since 1.0 + * @return An error code + * @param[in] bytes The ByteBuffer to decode + * @param[out] charCount The number of characters produced by decoding a range of bytes in the specified ByteBuffer + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks This method can be used to determine the exact number of characters + * that are produced if the specified range of bytes is encoded. + * + * @see GetMaxCharCount(), GetCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int& charCount) const; + + /** + * Calculates the number of characters produced by decoding a specified range of elements in a ByteBuffer. + * + * @since 1.0 + * @return An error code + * @param[in] bytes The ByteBuffer to decode + * @param[in] byteIndex The starting index where decoding begins + * @param[in] byteCount The number of bytes to decode + * @param[out] charCount The number of characters produced by decoding a range of bytes in the specified ByteBuffer + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused an underflow. @n + * The sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks This method can be used to determine the exact number of characters + * that are produced if the specified range of bytes is encoded. + * + * @see GetMaxCharCount(), GetCharCount() + */ + virtual result GetCharCount(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, int& charCount) const; + + /** + * Decodes a ByteBuffer into a WcharBuffer. + * + * @since 1.0 + * @return A new WcharBuffer where the resulting decoded data is stored @n + * @c null, if an exception occurs @n + * The buffer's limit is the position of the last decoded byte plus one in the buffer, and the position is @c 0 + * @param[in] bytes The buffer containing ByteBuffer to decode + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * @see GetBytesN(), GetCharsN() + */ + virtual Tizen::Base::WcharBuffer* GetCharsN(const Tizen::Base::ByteBuffer& bytes) const; + + /** + * Decodes a range of bytes in ByteBuffer into a range of characters in WcharBuffer. + * The WcharBuffer's position and limit are not changed. + * + * @since 1.0 + * @return An error code + * @param[in] bytes The buffer containing the ByteBuffer to decode + * @param[in] byteIndex The starting index where decoding begins + * @param[in] byteCount The number of bytes to decode + * @param[out] chars The buffer containing WcharBuffer where the resulting decoded data is stored + * @param[in] charIndex The starting index of the resulting decoding in the WcharBuffer + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The length of the specified @c byteIndex or @c byteCount is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused an underflow. @n + * The sum of the length of the specified @c byteIndex and @c byteCount is greater than the length of the specified @c bytes. + * @exception E_OVERFLOW This operation has caused an overflow. @n + * The specified @c chars does not contain sufficient space to store the decoded bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * + * @see GetBytes(), GetChars() + */ + virtual result GetChars(const Tizen::Base::ByteBuffer& bytes, int byteIndex, int byteCount, Tizen::Base::WcharBuffer& chars, int charIndex) const; + + /** + * Gets a string containing the decoded representation of a range of bytes in the specified ByteBuffer. + * + * @since 1.0 + * @return An error code + * @param[in] bytes The ByteBuffer to decode + * @param[out] str A String containing the decoded representation of a range of bytes in the specified ByteBuffer + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * + * @see GetBytesN(), GetString() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, Tizen::Base::String& str) const; + + /** + * Gets a string containing the decoded representation of a range of bytes in the specified ByteBuffer. + * + * @since 1.0 + * @return An error code + * @param[in] bytes The buffer containing the ByteBuffer to decode + * @param[in] index The starting index where decoding begins + * @param[in] count The number of bytes to decode + * @param[out] str A String containing the decoded representation of a range of bytes in the specified ByteBuffer + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c bytes is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_UNDERFLOW This operation has caused an underflow. @n + * The sum of the length of the specified @c index and @c count is greater than the length of the specified @c bytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * + * @see GetBytes(), GetString() + */ + virtual result GetString(const Tizen::Base::ByteBuffer& bytes, int index, int count, Tizen::Base::String& str) const; + + /** + * Gets the maximum number of bytes required for encoding the specified number of characters. + * + * @since 1.0 + * @return The maximum number of bytes required for encoding a given number of characters + * @param[in] charCount The number of characters to encode + * @remarks This method can be used to determine an appropriate buffer size for the byte arrays passed to the GetBytes() method for encoding. + * + * @see GetByteCount(), GetBytes() + */ + virtual int GetMaxByteCount(int charCount) const; + + /** + * Gets the maximum number of characters produced by decoding the specified number of bytes. + * + * @since 1.0 + * @return The maximum number of characters produced by decoding the specified number of bytes + * @param[in] byteCount The number of bytes to encode + * @remarks This method can be used to determine an appropriate buffer size for character arrays passed to + * GetChars() or a decoder for encoding. + * + * @see GetCharCount(), GetChars() + */ + virtual int GetMaxCharCount(int byteCount) const; + + /** + * Gets the encoder for the current encoding. + * + * @since 1.0 + * @return A pointer to Encoder for the current encoding + * @remarks Contrary to GetBytes(), an Encoder can convert partial sequences of characters into + * partial sequences of bytes by maintaining an appropriate state between the conversions. @n + * Currently, only Utf8Encoding supports this method. Other classes return @c null. + * + * @see GetBytes() + */ + virtual Encoder* GetEncoderN(void) const; + + /** + * Gets the decoder for the current encoding. + * + * @since 1.0 + * @return A decoder for the current encoding + * @remarks Contrary to the GetChars() methods, a Decoder can convert partial sequences of bytes + * into partial sequences of characters by maintaining an appropriate state between the conversions. @n + * Currently, only Utf8Encoding supports this method. Other classes return @c null. + * + * @see GetChars() + */ + virtual Decoder* GetDecoderN(void) const; + + /** + * Gets the encoding type of the current instance. + * + * @since 2.1 + * @return An encoding type + */ + virtual Tizen::Base::String GetEncodingType(void) const; + + /** + * Gets a list of all the available encodings. + * + * @since 1.0 + * @return A list of String instances (ASCII, UTF-8, ISO-8859-1, ISO-8859-2, Windows-1254, ...) @n + * @c null, if the method fails + * @exception E_SUCCESS The method was successful. + * @exception E_SYSTEM A system error occurred. + * @remarks The specific error code can be accessed using the GetLastResult() method. + */ + static Tizen::Base::Collection::IList* GetAvailableEncodingsImplN(void); + + /** + * Converts a range of bytes in a ByteBuffer from one encoding to another. + * + * @since 1.0 + * @return A new buffer for storing result of the conversion @n + * @c null, if an exception occurs @n + * The buffer's limit is the position of the last converted byte plus one, and the position @c 0 + * @param[in] src The source of the encoding + * @param[in] dst The destination of the encoding + * @param[in] srcBytes The ByteBuffer where the resulting encoded string is stored + * @param[in] index The starting index of the resulting encoding in the ByteBuffer + * @param[in] count The number of bytes to convert + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c srcBytes is empty. + * @exception E_OUT_OF_RANGE The value of the argument is outside the valid range defined by the method. @n + * The @c index or @c count is greater than the length of @c srcBytes. + * @exception E_UNDERFLOW This operation has caused an underflow. @n + * The sum of the length of the specified @c index and @c count is greater than the length of the specified @c srcBytes. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * @see GetBytes(), GetChars() + */ + static Tizen::Base::ByteBuffer* ConvertImplN(const Encoding& src, const Encoding& dst, + const Tizen::Base::ByteBuffer& srcBytes, int index, int count); + + /** + * Converts a ByteBuffer from one encoding to another. + * + * @since 1.0 + * @return A new buffer for storing the result of the conversion @n + * @c null, if an exception occurs @n + * The buffer's limit is the position of the last converted byte plus one, and the position @c 0 + * @param[in] src The source of the encoding + * @param[in] dst The destination of the encoding + * @param[in] srcBytes The ByteBuffer where the resulting encoded string is stored + * @exception E_SUCCESS The method was successful. + * @exception E_OUT_OF_MEMORY Insufficient memory. + * @exception E_INVALID_ARG A specified input parameter is invalid. @n + * The specified @c srcBytes is empty. + * @exception E_INVALID_ENCODING_RANGE The specified string contains code points that are outside the bounds specified by the character encoding scheme. + * @remarks The specific error code can be accessed using the GetLastResult() method. + * + * @see GetBytes(), GetChars() + */ + static Tizen::Base::ByteBuffer* ConvertImplN(const Encoding& src, const Encoding& dst, + const Tizen::Base::ByteBuffer& srcBytes); + + +private: + result Encode(const wchar_t* pSrc, int srcLength, Tizen::Base::ByteBuffer*& pByteBuffer, int index) const; + result Decode(const byte* pSrc, int srcLength, Tizen::Base::WcharBuffer*& pWcharBuffer, int index) const; + result Decode(const byte* pSrc, int srcLength, Tizen::Base::String& outStr, int index) const; + + result GetBufferSize(const Tizen::Base::WcharBuffer& chars, int& charBufSize) const; + result GetBufferSize(const Tizen::Base::ByteBuffer& bytes, int& byteBufSize) const; + result CheckBufferInput(int inBufSize, int inIndex, int inCount) const; + result CheckBufferInput(int inBufSize, int inIndex, int inCount, int outBufSize, int outIndex) const; + + bool IsEncodingSupported(const Tizen::Base::String& encodingStr) const; + + _EncodingImpl(const _EncodingImpl& encodingImpl); + _EncodingImpl& operator =(const _EncodingImpl& encodingImpl); + + + Tizen::Base::String __encodingType; + std::unique_ptr<_EncodingCore> __pEncodingCore; + + friend class Encoding; + +}; // _EncodingImpl + +} } // Tizen::Text + +#endif //_FTEXT_INTERNAL_ENCODING_IMPL_H_ diff --git a/src/text/FText_GsmEncodingCore.cpp b/src/text/FText_GsmEncodingCore.cpp new file mode 100644 index 0000000..9bc152c --- /dev/null +++ b/src/text/FText_GsmEncodingCore.cpp @@ -0,0 +1,340 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_GsmEncodingCore.cpp + * @brief This is the implementation file for _GsmEncodingCore class. + */ + +// Includes +#include +#include +#include "FText_GsmEncodingCore.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + + +typedef struct +{ + byte gsm; + wchar_t unicode; +} GsmUniTable; + + +#define GSM_TABLE_UNI_LENGTH 0x80 +static const wchar_t GSM_UNICODE_TABLE[] = +{ + 0x0040, 0x00A3, 0x0024, 0x00A5, 0x00E8, 0x00E9, 0x00F9, 0x00EC, + 0x00F2, 0x00E7, 0x000A, 0x00D8, 0x00F8, 0x000D, 0x00C5, 0x00E5, + 0x0394, 0x005F, 0x03A6, 0x0393, 0x039B, 0x03A9, 0x03A0, 0x03A8, + 0x03A3, 0x0398, 0x039E, 0xFFFD, 0x00C6, 0x00E6, 0x00DF, 0x00C9, + 0x0020, 0x0021, 0x0022, 0x0023, 0x00A4, 0x0025, 0x0026, 0x0027, + 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, + 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, + 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, + 0x00A1, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, + 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, + 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, + 0x0058, 0x0059, 0x005A, 0x00C4, 0x00D6, 0x00D1, 0x00DC, 0x00A7, + 0x00BF, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, + 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, + 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, + 0x0078, 0x0079, 0x007A, 0x00E4, 0x00F6, 0x00F1, 0x00FC, 0x00E0 +}; + + +#define EXT_GSM_TABLE_1B_LENGTH 10 +static const GsmUniTable GSM_UNICODE_TABLE_EXTENSION[] = +{ + {0x0A, 0x000C}, {0x14, 0x005E}, {0x28, 0x007B}, {0x29, 0x007D}, {0x2F, 0x005C}, + {0x3C, 0x005B}, {0x3D, 0x007E}, {0x3E, 0x005D}, {0x40, 0x007C}, {0x65, 0x20AC} +}; + +_GsmEncodingCore::_GsmEncodingCore(void) +{ +} + + +_GsmEncodingCore::~_GsmEncodingCore(void) +{ +} + +_EncodingCore* +_GsmEncodingCore::GetEncodingCoreImplN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo) +{ + if (encodingFrom != L"GSM") + { + SetLastResult(E_UNSUPPORTED_TYPE); + return null; + } + + _GsmEncodingCore* pEncoderDecoder = new (std::nothrow) _GsmEncodingCore; + SysTryReturn(NID_TEXT, pEncoderDecoder, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + return pEncoderDecoder; +} + +result +_GsmEncodingCore::GetAvailableEncodingsN(Tizen::Base::Collection::IList* pEncodingList) +{ + SysTryReturnResult(NID_TEXT, pEncodingList, E_INVALID_ARG, + "[%s] Invalid argument is used. Input encoding list is null", GetErrorMessage(E_INVALID_ARG)); + + String* pEncodingStr = new (std::nothrow) String(L"GSM"); + SysTryReturnResult(NID_TEXT, pEncodingStr, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = pEncodingList->Add(*pEncodingStr); + if (IsFailed(r)) + { + delete pEncodingStr; + return r; + } + return E_SUCCESS; +} + +String +_GsmEncodingCore::GetName(void) +{ + return String(L"GSM"); +} + +result +_GsmEncodingCore::GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength) +{ + retLength = -1; + if (pSrc != null) + { + int gsmSize = 0; + int index = 0; + wchar_t* pUnicodeStr = (wchar_t*) pSrc; + while (srcLength > 0) + { + bool foundInExtTable = false; + SysTryReturnResult(NID_TEXT, (*pUnicodeStr != 0xFFFD), E_INVALID_ENCODING_RANGE, + "[%s] Encoding failed. pSrc(%ls) contains code(%x) pointing outside of bounds by GSM encdoing.", GetErrorMessage(E_INVALID_ENCODING_RANGE), pSrc, *pUnicodeStr); + SysTryReturnResult(NID_TEXT, (*pUnicodeStr <= 0x20AC), E_INVALID_ENCODING_RANGE, + "[%s] Encoding failed. pSrc(%ls) contains code(%x) pointing outside of bounds by GSM encdoing.", GetErrorMessage(E_INVALID_ENCODING_RANGE), pSrc, *pUnicodeStr); + + if (*pUnicodeStr == '\0') + { + gsmSize++; + break; + } + + for (index = 0; index < EXT_GSM_TABLE_1B_LENGTH; index++) + { + if (*pUnicodeStr == GSM_UNICODE_TABLE_EXTENSION[index].unicode) + { + gsmSize++; + foundInExtTable = true; + break; + } + } + if (!foundInExtTable) + { + bool foundInUniTable = false; + + // 0x0020 - 0x005F, 0x0061 - 0x007E + if (*pUnicodeStr < 0x0020 || *pUnicodeStr > 0x007E || *pUnicodeStr == 0x0060) + { + for (index = 0; index < GSM_TABLE_UNI_LENGTH; index++) + { + if (*pUnicodeStr == GSM_UNICODE_TABLE[index]) + { + foundInUniTable = true; + break; + } + } + + SysTryReturnResult(NID_TEXT, foundInUniTable, E_INVALID_ENCODING_RANGE, + "[%s] Encoding failed. String contains code pointing outside of bounds by GSM encdoing.", GetErrorMessage(E_INVALID_ENCODING_RANGE)); + } + } + + gsmSize++; + pUnicodeStr++; + srcLength--; + } + retLength = gsmSize; + return E_SUCCESS; + } + + return E_INVALID_ARG; +} + +result +_GsmEncodingCore::GetCharCount(const byte* pSrc, int srcLength, int& retLength) +{ + retLength = -1; + if (pSrc != null) + { + int uniSize = 0; + int index = 0; + byte* pGsmByte = (byte*) pSrc; + while (srcLength > 1) + { + SysTryReturnResult(NID_TEXT, not (*pGsmByte & 0x80), E_INVALID_ENCODING_RANGE, + "[%s] Encoding failed. String contains code pointing outside of bounds by GSM encdoing.", GetErrorMessage(E_INVALID_ENCODING_RANGE)); + if (*pGsmByte == 0x1B) + { + bool foundInExtTable = false; + + pGsmByte++; + srcLength--; + for (index = 0; index < EXT_GSM_TABLE_1B_LENGTH; index++) + { + if (*pGsmByte == GSM_UNICODE_TABLE_EXTENSION[index].gsm) + { + foundInExtTable = true; + break; + } + } + SysTryReturnResult(NID_TEXT, foundInExtTable, E_INVALID_ENCODING_RANGE, + "[%s] Encoding failed. String contains code pointing outside of bounds by GSM encdoing.", GetErrorMessage(E_INVALID_ENCODING_RANGE)); + } + uniSize++; + pGsmByte++; + srcLength--; + } + + if (srcLength) + { + SysTryReturnResult(NID_TEXT, not ((*pGsmByte & 0x80) || (*pGsmByte == 0x1B)), E_INVALID_ENCODING_RANGE, + "[%s] Encoding failed. String contains code pointing outside of bounds by GSM encdoing.", GetErrorMessage(E_INVALID_ENCODING_RANGE)); + uniSize++; + } + + retLength = uniSize; + return E_SUCCESS; + } + + return E_INVALID_ARG; +} + +byte* +_GsmEncodingCore::EncodeN(const wchar_t* pSrc, int srcLength, int& retLength) +{ + result r = GetByteCount(pSrc, srcLength, retLength); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Encoding failed", GetErrorMessage(r)); + + std::unique_ptr pDst(new (std::nothrow) byte[retLength + 1]); + SysTryReturn(NID_TEXT, pDst, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + wchar_t* pUnicodeStr = (wchar_t*) pSrc; + byte* pCurrPos = pDst.get(); + int index = 0; + while (srcLength > 0) + { + bool foundInUniTable = false; + if (*pUnicodeStr < GSM_TABLE_UNI_LENGTH) + { + if (*pUnicodeStr == GSM_UNICODE_TABLE[*pUnicodeStr]) + { + *pCurrPos = (byte) (*pUnicodeStr); + foundInUniTable = true; + } + } + if (!foundInUniTable) + { + for (index = 0; index < GSM_TABLE_UNI_LENGTH; index++) + { + if (*pUnicodeStr == GSM_UNICODE_TABLE[index]) + { + *pCurrPos = (byte) index; + foundInUniTable = true; + break; + } + } + if (!foundInUniTable) + { + for (index = 0; index < EXT_GSM_TABLE_1B_LENGTH; index++) + { + if (*pUnicodeStr == GSM_UNICODE_TABLE_EXTENSION[index].unicode) + { + *pCurrPos = 0x1B; + *(++pCurrPos) = GSM_UNICODE_TABLE_EXTENSION[index].gsm; + break; + } + } + } + } + + pCurrPos++; + pUnicodeStr++; + srcLength--; + } + + SetLastResult(E_SUCCESS); + return pDst.release(); +} + +wchar_t* +_GsmEncodingCore::DecodeN(const byte* pSrc, int srcLength, int& retLength) +{ + result r = GetCharCount(pSrc, srcLength, retLength); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Encoding failed", GetErrorMessage(r)); + + std::unique_ptr pDst( new (std::nothrow) wchar_t[retLength + 1]); + SysTryReturn(NID_TEXT, pDst, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + byte* pGsmByte = (byte*) pSrc; + wchar_t* pCurrPos = pDst.get(); + int index = 0; + while (srcLength > 0) + { + *pCurrPos = GSM_UNICODE_TABLE[*pGsmByte]; + if (*pGsmByte == 0x001B) + { + pGsmByte++; + srcLength--; + + for (index = 0; index < EXT_GSM_TABLE_1B_LENGTH; index++) + { + if (*pGsmByte == GSM_UNICODE_TABLE_EXTENSION[index].gsm) + { + *pCurrPos = GSM_UNICODE_TABLE_EXTENSION[index].unicode; + break; + } + } + } + pCurrPos++; + pGsmByte++; + srcLength--; + } + +// pDst[retLength] = '\0'; + SetLastResult(E_SUCCESS); + return pDst.release(); +} + +int +_GsmEncodingCore::GetMaxByteCount(int charCount) const +{ + return charCount * 2; +} + +int +_GsmEncodingCore::GetMaxCharCount(int byteCount) const +{ + return byteCount; +} + +} } // Tizen::Text diff --git a/src/text/FText_GsmEncodingCore.h b/src/text/FText_GsmEncodingCore.h new file mode 100644 index 0000000..969a109 --- /dev/null +++ b/src/text/FText_GsmEncodingCore.h @@ -0,0 +1,60 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_GsmEncodingCore.h + * @brief This is the header file for the _GsmEncodingCore class. + */ + +#ifndef _FTEXT_INTERNAL_GSM_ENCODING_CORE_H_ +#define _FTEXT_INTERNAL_GSM_ENCODING_CORE_H_ + +#include +#include "FText_EncodingCore.h" + + +namespace Tizen { namespace Text +{ + +class _GsmEncodingCore + : public _EncodingCore +{ +public: + _GsmEncodingCore(void); + ~_GsmEncodingCore(void); + + static _EncodingCore* GetEncodingCoreImplN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo); + virtual result GetAvailableEncodingsN(Tizen::Base::Collection::IList* pEncodingList); + + virtual result GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength); + virtual result GetCharCount(const byte* pSrc, int srcLength, int& retLength); + + virtual byte* EncodeN(const wchar_t* pSrc, int srcLength, int& retLength); + virtual wchar_t* DecodeN(const byte* pSrc, int srcLength, int& retLength); + + virtual int GetMaxByteCount(int charCount) const; + virtual int GetMaxCharCount(int byteCount) const; + + virtual Tizen::Base::String GetName(void); + +}; // _GsmEncodingCore + + +} } // Tizen::Text + + +#endif diff --git a/src/text/FText_IcuEncodingCore.cpp b/src/text/FText_IcuEncodingCore.cpp new file mode 100644 index 0000000..96910d7 --- /dev/null +++ b/src/text/FText_IcuEncodingCore.cpp @@ -0,0 +1,499 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_IcuEncodingCore.cpp + * @brief This is the implementation file for _IcuEncodingCore class. + */ + +// Includes +#include +#include +#include +#include +#include "FText_IcuEncodingCore.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Base::Utility; + +#define EXTRA_ENCODINGS_LENGTH 3 +static String extraEncodings[] = { +"UCS4", "UCS4BE", "UCS4LE" +}; + +namespace Tizen { namespace Text +{ + +_IcuEncodingCore::_IcuEncodingCore(void) + : __pEncoder(null) +{ +} + +_IcuEncodingCore::~_IcuEncodingCore(void) +{ + if (__pEncoder) + { + ucnv_close(__pEncoder); + __pEncoder = null; + } +} + +result +_IcuEncodingCore::__Encode(const wchar_t* pSrc, int srcLength, byte* pDst, int dstLength, int& retLength) +{ + SysTryReturnResult(NID_TEXT, pSrc, E_INVALID_ARG, + "[%s] Invalid argument is used. Input buffer pSrc is null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturnResult(NID_TEXT, srcLength >= 0, E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) can not be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + + UErrorCode err = U_ZERO_ERROR; + int outLen = 0; + int icuStrLen = srcLength * 2; + + result r = E_OUT_OF_MEMORY; + IcuUChar* pIcuStr = new (std::nothrow) IcuUChar[icuStrLen]; + if (pIcuStr) + { + IcuUChar* pIcuStr1 = u_strFromWCS(pIcuStr, icuStrLen, &outLen, pSrc, srcLength, &err); + if (U_SUCCESS(err)) + { + if (pDst) + { + retLength = ucnv_fromUChars(__pEncoder, (char*) pDst, dstLength, pIcuStr1, outLen, &err); + } + else + { + retLength = ucnv_fromUChars(__pEncoder, null, 0, pIcuStr1, outLen, &err); + if (err == U_BUFFER_OVERFLOW_ERROR) + { + err = U_ZERO_ERROR; + } + else + { + retLength = -1; + } + } + } + + r = GetResultFromIcuErrorCode(err); + } + + delete[] pIcuStr; + return r; +} + +result +_IcuEncodingCore::__Decode(const byte* pSrc, int srcLength, wchar_t* pDst, int dstLength, int& retLength) +{ + SysTryReturnResult(NID_TEXT, pSrc, E_INVALID_ARG, + "[%s] Invalid argument is used. Input buffer pSrc is null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturnResult(NID_TEXT, srcLength >= 0, E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) can not be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + + bool isCallForCharCount = (pDst == null); + if (isCallForCharCount) + { + dstLength = srcLength * 2; + pDst = new (std::nothrow) wchar_t[dstLength]; + SysTryReturnResult(NID_TEXT, pDst, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + } + + UErrorCode err = U_ZERO_ERROR; + int icuStrLen = dstLength * 2; + IcuUChar* pIcuStr = new (std::nothrow) IcuUChar[icuStrLen]; + if (pIcuStr) + { + retLength = ucnv_toUChars(__pEncoder, pIcuStr, icuStrLen, (const char*) pSrc, srcLength, &err); + if (U_SUCCESS(err)) + { + pDst = u_strToWCS(pDst, dstLength, &retLength, pIcuStr, retLength, &err); + } + } + delete[] pIcuStr; + + if (isCallForCharCount) + { + if (U_FAILURE(err)) + { + retLength = -1; + } + + delete[] pDst; + pDst = null; + } + + return GetResultFromIcuErrorCode(err); +} + +byte* +_IcuEncodingCore::EncodeExN(const wchar_t* pSrc, int srcLength, int& retLength, bool flush) +{ + SysTryReturn(NID_TEXT, pSrc, null, E_INVALID_ARG, + "[%s] Invalid argument is used. Input buffer pSrc is null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_TEXT, srcLength >= 0, null, E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) can not be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + + result r = E_SUCCESS; + UErrorCode err = U_ZERO_ERROR; + byte* pDst = null; + + int outLen = 0; + int icuStrLen = srcLength * 2; + IcuUChar* pIcuStr = new (std::nothrow) IcuUChar[icuStrLen]; + SysTryCatch(NID_TEXT, pIcuStr, , E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + pIcuStr = u_strFromWCS(pIcuStr, icuStrLen, &outLen, pSrc, srcLength, &err); + r = GetResultFromIcuErrorCode(err); + if (U_SUCCESS(err)) + { + int maxDestLen = UCNV_GET_MAX_BYTES_FOR_STRING(outLen, ucnv_getMaxCharSize(__pEncoder)); + pDst = new (std::nothrow) byte[maxDestLen]; + if (pDst) + { + char* pDstArray = (char*) pDst; + const char* pDstLimit = pDstArray + maxDestLen; + const IcuUChar* pSrcArray = pIcuStr; + const IcuUChar* pSrcLimit = pIcuStr + outLen; + + err = U_ZERO_ERROR; + ucnv_fromUnicode(__pEncoder, &pDstArray, pDstLimit, &pSrcArray, pSrcLimit, null, flush, &err); + r = GetResultFromIcuErrorCode(err); + if (U_SUCCESS(err)) + { + retLength = (byte*) pDstArray - pDst; + + delete[] pIcuStr; + SetLastResult(E_SUCCESS); + return pDst; + } + } + } + +CATCH: + delete[] pIcuStr; + delete[] pDst; + retLength = -1; + SetLastResult(r); + return null; +} + +wchar_t* +_IcuEncodingCore::DecodeExN(const byte* pSrc, int srcLength, int& retLength, bool flush) +{ + SysTryReturn(NID_TEXT, pSrc, null, E_INVALID_ARG, + "[%s] Invalid argument is used. Input buffer pSrc is null.", GetErrorMessage(E_INVALID_ARG)); + SysTryReturn(NID_TEXT, srcLength >= 0, null, E_INVALID_ARG, + "[%s] Invalid argument is used. srcLength(%d) can not be negative.", GetErrorMessage(E_INVALID_ARG), srcLength); + + UErrorCode err = U_ZERO_ERROR; + int icuStrLen = srcLength * 2; + IcuUChar* pIcuStr = new (std::nothrow) IcuUChar[icuStrLen]; + SysTryReturn(NID_TEXT, pIcuStr, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + IcuUChar* pDstArray = pIcuStr; + const IcuUChar* pDstLimit = pIcuStr + icuStrLen; + const char* pSrcArray = (const char*) pSrc; + const char* pSrcLimit = pSrcArray + srcLength; + + result r = E_SUCCESS; + wchar_t* pDst = null; + err = U_ZERO_ERROR; + + ucnv_toUnicode(__pEncoder, &pDstArray, pDstLimit, &pSrcArray, pSrcLimit, null, flush, &err); + r = GetResultFromIcuErrorCode(err); + + if (U_SUCCESS(err)) + { + int dstLength = pDstArray - pIcuStr; + pDst = new (std::nothrow) wchar_t[dstLength + 1]; + SysTryCatch(NID_TEXT, pDst, , E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + pDst[dstLength] = '\0'; + + pDst = u_strToWCS(pDst, dstLength, &retLength, pIcuStr, dstLength, &err); + r = GetResultFromIcuErrorCode(err); + SysTryCatch(NID_TEXT, !IsFailed(r), , r, "Decoding failed"); + + delete[] pIcuStr; + SetLastResult(E_SUCCESS); + return pDst; + } + +CATCH: + delete[] pIcuStr; + delete[] pDst; + retLength = -1; + SetLastResult(r); + return null; +} + +_EncodingCore* +_IcuEncodingCore::GetEncodingCoreImplN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo) +{ + result r = E_SUCCESS; + UErrorCode err = U_ZERO_ERROR; + std::unique_ptr<_IcuEncodingCore> pEncodingCore(null); + + int lenEncoding = encodingFrom.GetLength(); + std::unique_ptr pEncoding(new (std::nothrow) char[lenEncoding + 2]); + SysTryReturn(NID_TEXT, (pEncoding != null), null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + size_t retLength = wcstombs(pEncoding.get(), encodingFrom.GetPointer(), lenEncoding); + SysTryReturn(NID_TEXT, (retLength > 0), null, E_SYSTEM, "[%s] Unable to convert encoding string to multi byte char array", GetErrorMessage(E_SYSTEM)); + + *(pEncoding.get() + retLength) = '\0'; + + pEncodingCore.reset(new (std::nothrow) _IcuEncodingCore); + SysTryReturn(NID_TEXT, (pEncodingCore != null), null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + pEncodingCore->__pEncoder = ucnv_open(pEncoding.get(), &err); + if (U_FAILURE(err)) + { + String subsEncoding(encodingFrom); + subsEncoding.ToUpper(); + if (subsEncoding.StartsWith("UCS", 0)) + { + r = subsEncoding.Replace("UCS", "UTF"); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Unable to open ICU converter", GetErrorMessage(r)); + + r = subsEncoding.Replace("4", "32"); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Unable to open ICU converter", GetErrorMessage(r)); + + size_t retLength = wcstombs(pEncoding.get(), subsEncoding.GetPointer(), subsEncoding.GetLength()); + SysTryReturn(NID_TEXT, (retLength > 0), null, E_SYSTEM, "[%s] Unable to convert encoding string to multi byte char array", GetErrorMessage(E_SYSTEM)); + + pEncoding[retLength] = '\0'; + err = U_ZERO_ERROR; + pEncodingCore->__pEncoder = ucnv_open(pEncoding.get(), &err); + } + + } + r = pEncodingCore->GetResultFromIcuErrorCode(err); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Unable to open ICU converter", GetErrorMessage(r)); + + ucnv_setFromUCallBack(pEncodingCore->__pEncoder, UCNV_FROM_U_CALLBACK_STOP, NULL, NULL, NULL, &err); + ucnv_setToUCallBack(pEncodingCore->__pEncoder, UCNV_TO_U_CALLBACK_STOP, NULL, NULL, NULL, &err); + + pEncodingCore->_encodingFrom = encodingFrom; + pEncodingCore->_encodingTo = L"WCHAR_T"; + + SetLastResult(E_SUCCESS); + return pEncodingCore.release(); +} + +String +_IcuEncodingCore::GetName(void) +{ + UErrorCode err = U_ZERO_ERROR; + const char* pName = ucnv_getName(__pEncoder, &err); + if (U_SUCCESS(err)) + { + return String(pName); + } + + return String(); +} + +result +_IcuEncodingCore::GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength) +{ + return __Encode(pSrc, srcLength, null, 0, retLength); +} + +result +_IcuEncodingCore::GetCharCount(const byte* pSrc, int srcLength, int& retLength) +{ + return __Decode(pSrc, srcLength, null, 0, retLength); +} + +byte* +_IcuEncodingCore::EncodeN(const wchar_t* pSrc, int srcLength, int& retLength) +{ + int maxDestLen = UCNV_GET_MAX_BYTES_FOR_STRING(srcLength * 2, ucnv_getMaxCharSize(__pEncoder)); + std::unique_ptr pByte(new (std::nothrow) byte[maxDestLen]); + SysTryReturn(NID_TEXT, pByte, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = __Encode(pSrc, srcLength, pByte.get(), maxDestLen, retLength); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Encode operation failed", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return pByte.release(); +} + +wchar_t* +_IcuEncodingCore::DecodeN(const byte* pSrc, int srcLength, int& retLength) +{ + int maxDestLen = srcLength * 2; + std::unique_ptr pWchar(new (std::nothrow) wchar_t[maxDestLen]); + SysTryReturn(NID_TEXT, pWchar, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = __Decode(pSrc, srcLength, pWchar.get(), maxDestLen, retLength); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Encode operation failed", GetErrorMessage(r)); + + SetLastResult(E_SUCCESS); + return pWchar.release(); +} + +int +_IcuEncodingCore::GetMaxByteCount(int charCount) const +{ + return charCount * (ucnv_getMaxCharSize(__pEncoder)); +} + +int +_IcuEncodingCore::GetMaxCharCount(int byteCount) const +{ + return byteCount / (ucnv_getMinCharSize(__pEncoder)); +} + +result +_IcuEncodingCore::GetAvailableEncodingsN(IList* pEncodingList) +{ + SysTryReturnResult(NID_TEXT, pEncodingList, E_INVALID_ARG, "[%s] Invalid argument is used.Input encoding list is null", GetErrorMessage(E_INVALID_ARG)); + + result r = E_SUCCESS; + int count = ucnv_countAvailable(); + SysTryReturnResult(NID_TEXT, count > 0, E_SYSTEM, "[%s] Unable to get available encoding list count.", GetErrorMessage(E_SYSTEM)); + + String* pEncodingStr = null; + for (int i = 0; i < count; i++) + { + pEncodingStr = new (std::nothrow) String(ucnv_getAvailableName(i)); + SysTryReturnResult(NID_TEXT, pEncodingStr, E_OUT_OF_MEMORY, "[%s] Memory allocationfailed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pEncodingList->Add(*pEncodingStr); + if (IsFailed(r)) + { + delete pEncodingStr; + return r; + } + } + + for (int i = 0; i < EXTRA_ENCODINGS_LENGTH; i++) + { + pEncodingStr = new (std::nothrow) String(extraEncodings[i]); + SysTryReturnResult(NID_TEXT, pEncodingStr, E_OUT_OF_MEMORY, "[%s] Memory allocationfailed", GetErrorMessage(E_OUT_OF_MEMORY)); + + r = pEncodingList->Add(*pEncodingStr); + if (IsFailed(r)) + { + delete pEncodingStr; + return r; + } + } + + return E_SUCCESS; +} + +result +_IcuEncodingCore::GetResultFromIcuErrorCode(UErrorCode& err) +{ + result r = E_SUCCESS; + if (!U_SUCCESS(err)) + { + switch (err) + { + case U_MEMORY_ALLOCATION_ERROR: + { + r = E_OUT_OF_MEMORY; + break; + } + + case U_INDEX_OUTOFBOUNDS_ERROR: + { + r = E_INVALID_ARG; + break; + } + + case U_TRUNCATED_CHAR_FOUND: + // fall through to U_INVALID_CHAR_FOUND + case U_INVALID_CHAR_FOUND: + // fall through to U_ILLEGAL_CHAR_FOUND + case U_ILLEGAL_CHAR_FOUND: + { + r = E_INVALID_ENCODING_RANGE; + break; + } + + case U_INVALID_TABLE_FORMAT: + { + r = E_SYSTEM; + break; + } + + case U_BUFFER_OVERFLOW_ERROR: + { + r = E_OVERFLOW; + break; + } + + case U_STRING_NOT_TERMINATED_WARNING: + { + r = E_INVALID_ARG; + break; + } + + case U_ILLEGAL_ARGUMENT_ERROR: + { + r = E_INVALID_ARG; + break; + } + + case U_FILE_ACCESS_ERROR: + // fall through to U_AMBIGUOUS_ALIAS_WARNING + case U_AMBIGUOUS_ALIAS_WARNING: + { + r = E_UNSUPPORTED_TYPE; + break; + } + + default: + { + r = E_SYSTEM; + break; + } + } + } + return r; +} + +IcuUChar* +_IcuEncodingCore::GetIcuUcharN(const Tizen::Base::String& ospString, result& r) +{ + UErrorCode err = U_ZERO_ERROR; + int outLen = 0; + int srcLength = ospString.GetLength(); + std::unique_ptr pIcuStr(new (std::nothrow) IcuUChar(srcLength + 2)); + SysTryReturn(NID_TEXT, pIcuStr != null, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + pIcuStr.reset(u_strFromWCS( + pIcuStr.get(), + srcLength + 2, + &outLen, + ospString.GetPointer(), + srcLength, + &err + )); + + r = GetResultFromIcuErrorCode(err); + SysTryReturn(NID_TEXT, !IsFailed(r), null, r, "[%s] Error in converting osp string to ICU UChar", GetErrorMessage(r)); + + return pIcuStr.release(); +} + + +} } // Tizen::Text diff --git a/src/text/FText_IcuEncodingCore.h b/src/text/FText_IcuEncodingCore.h new file mode 100644 index 0000000..3412c2c --- /dev/null +++ b/src/text/FText_IcuEncodingCore.h @@ -0,0 +1,81 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_IcuEncodingCore.h + * @brief This is the header file for the _IcuEncodingCore class. + */ + +#ifndef _FTEXT_INTERNAL_ICU_ENCODING_CORE_H_ +#define _FTEXT_INTERNAL_ICU_ENCODING_CORE_H_ + +#include "unicode/utypes.h" +#include "unicode/ucnv.h" +#include +#include "FText_EncodingCore.h" + +typedef UChar IcuUChar; +typedef UConverter IcuUConverter; + +namespace Tizen { namespace Text +{ + +class _IcuEncodingCore + : public _EncodingCore +{ +public: + _IcuEncodingCore(void); + virtual ~_IcuEncodingCore(void); + + static _EncodingCore* GetEncodingCoreImplN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo); + result GetAvailableEncodingsN(Tizen::Base::Collection::IList* pEncodingList); + + virtual result GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength); + virtual result GetCharCount(const byte* pSrc, int srcLength, int& retLength); + + virtual byte* EncodeN(const wchar_t* pSrc, int srcLength, int& retLength); + virtual wchar_t* DecodeN(const byte* pSrc, int srcLength, int& retLength); + + virtual byte* EncodeExN(const wchar_t* pSrc, int srcLength, int& retLength, bool flush); + virtual wchar_t* DecodeExN(const byte* pSrc, int srcLength, int& retLength, bool flush); + + virtual int GetMaxByteCount(int charCount) const; + virtual int GetMaxCharCount(int byteCount) const; + + virtual Tizen::Base::String GetName(void); + +private: + result GetResultFromIcuErrorCode(UErrorCode& err); + IcuUChar* GetIcuUcharN(const Tizen::Base::String& ospString, result& r); + + result __Encode(const wchar_t* pSrc, int srcLength, byte* pDst, int dstLength, int& retLength); + result __Decode(const byte* pSrc, int srcLength, wchar_t* pDst, int dstLength, int& retLength); + + _IcuEncodingCore(const _IcuEncodingCore& icuEncodingCore); + _IcuEncodingCore& operator =(const _IcuEncodingCore& icuEncodingCore); + + +private: + IcuUConverter* __pEncoder; + +}; // _IcuEncodingCore + + +} } // Tizen::Text + + +#endif //_FTEXT_INTERNAL_ICU_ENCODING_CORE_H_ diff --git a/src/text/FText_Iso885916EncodingCore.cpp b/src/text/FText_Iso885916EncodingCore.cpp new file mode 100644 index 0000000..ffc758d --- /dev/null +++ b/src/text/FText_Iso885916EncodingCore.cpp @@ -0,0 +1,316 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_Iso885916EncodingCore.cpp + * @brief This is the implementation file for _Iso885916EncodingCore class. + */ + +// Includes +#include +#include +#include "FText_Iso885916EncodingCore.h" + + +using namespace Tizen::Base; + +namespace Tizen { namespace Text +{ + +static const wchar_t ISO_8859_16_UNICODE_TABLE[] = +{ + 0x00A0, 0x0104, 0x0105, 0x0141, 0x20AC, 0x201E, 0x0160, 0x00A7, + 0x0161, 0x00A9, 0x0218, 0x00AB, 0x0179, 0x00AD, 0x017A, 0x017B, + 0x00B0, 0x00B1, 0x010C, 0x0142, 0x017D, 0x201D, 0x00B6, 0x00B7, + 0x017E, 0x010D, 0x0219, 0x00BB, 0x0152, 0x0153, 0x0178, 0x017C, + 0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0106, 0x00C6, 0x00C7, + 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, + 0x0110, 0x0143, 0x00D2, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x015A, + 0x0170, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x0118, 0x021A, 0x00DF, + 0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x0107, 0x00E6, 0x00E7, + 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, + 0x0111, 0x0144, 0x00F2, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x015B, + 0x0171, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0119, 0x021B, 0x00FF +}; + + +_Iso885916EncodingCore::_Iso885916EncodingCore(void) +{ +} + + +_Iso885916EncodingCore::~_Iso885916EncodingCore(void) +{ +} + +_EncodingCore* +_Iso885916EncodingCore::GetEncodingCoreImplN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo) +{ + if (encodingFrom != L"ISO-8859-16") + { + SetLastResult(E_UNSUPPORTED_TYPE); + return null; + } + + _Iso885916EncodingCore* pEncodingCore = new (std::nothrow) _Iso885916EncodingCore; + SysTryReturn(NID_TEXT, pEncodingCore, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + return pEncodingCore; +} + +result +_Iso885916EncodingCore::GetAvailableEncodingsN(Tizen::Base::Collection::IList* pEncodingList) +{ + SysTryReturnResult(NID_TEXT, pEncodingList, E_INVALID_ARG, + "[%s] Invalid argument is used. Input encoding list is null", GetErrorMessage(E_INVALID_ARG)); + + String* pEncodingStr = new (std::nothrow) String(L"ISO-8859-16"); + SysTryReturnResult(NID_TEXT, pEncodingStr, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + result r = pEncodingList->Add(*pEncodingStr); + if (IsFailed(r)) + { + delete pEncodingStr; + return r; + } + return E_SUCCESS; +} + +String +_Iso885916EncodingCore::GetName(void) +{ + return String(L"ISO-8859-16"); +} + +result +_Iso885916EncodingCore::GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength) +{ + retLength = -1; + wchar_t* pUnicodeStr = (wchar_t*) pSrc; + if (pUnicodeStr) + { + int iso8859_16Size = srcLength; + while (srcLength > 0) + { + if ((*pUnicodeStr) > 0x00A0) + { + if (((*pUnicodeStr) > 0xFFFF)) + { + return E_INVALID_ENCODING_RANGE; + } + + if (!(*pUnicodeStr & 0xFF00)) + { + if (ISO_8859_16_UNICODE_TABLE[*pUnicodeStr - 0xA0] != *pUnicodeStr) + { + return E_INVALID_ENCODING_RANGE; + } + } + else if (!(*pUnicodeStr & 0xFE80)) + { + bool invalid = true; + for (int i = 0; i <= 0x5F; i++) + { + if (ISO_8859_16_UNICODE_TABLE[i] == *pUnicodeStr) + { + invalid = false; + break; + } + } + // check for invalid values + if (invalid) + { + return E_INVALID_ENCODING_RANGE; + } + } + else if (!(*pUnicodeStr & 0xFDE0)) + { + if ((*pUnicodeStr == 0x0218) || (*pUnicodeStr == 0x0219) || (*pUnicodeStr == 0x021A) || + (*pUnicodeStr == 0x021B)) + { + // empty statement + } + else + { + return E_INVALID_ENCODING_RANGE; + } + } + else if (!(*pUnicodeStr & 0xDF40)) + { + if ((*pUnicodeStr == 0x201D) || (*pUnicodeStr == 0x201E) || (*pUnicodeStr == 0x20AC)) + { + // empty statement + } + else + { + return E_INVALID_ENCODING_RANGE; + } + } + else + { + return E_INVALID_ENCODING_RANGE; + } + } + pUnicodeStr++; + srcLength--; + } + retLength = iso8859_16Size; + return E_SUCCESS; + } + + return E_INVALID_ARG; +} + +result +_Iso885916EncodingCore::GetCharCount(const byte* pSrc, int srcLength, int& retLength) +{ + retLength = -1; + SysTryReturnResult(NID_TEXT, pSrc, E_INVALID_ARG, + "[%s] Invalid argument is used. Input buffer pSrc is null.", GetErrorMessage(E_INVALID_ARG)); + retLength = srcLength; + return E_SUCCESS; +} + +byte* +_Iso885916EncodingCore::EncodeN(const wchar_t* pSrc, int srcLength, int& retLength) +{ + wchar_t* pUnicodeStr = (wchar_t*) pSrc; + result r = GetByteCount(pUnicodeStr, srcLength, retLength); + SysTryReturn(NID_TEXT, retLength > 0, null, r, "[%s] Encoding Failed", GetErrorMessage(r)); + + std::unique_ptr pIso8859_16Byte(new (std::nothrow) byte[retLength + 1]); + SysTryReturn(NID_TEXT, pIso8859_16Byte, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + byte* pCurrPos = pIso8859_16Byte.get(); + while (srcLength > 0) + { + if ((*pUnicodeStr) <= 0x00FF) + { + *pCurrPos = (byte) * pUnicodeStr; + } + else if (!(*pUnicodeStr & 0xFE80)) + { + for (int i = 0; i <= 0x5F; i++) + { + if (ISO_8859_16_UNICODE_TABLE[i] == *pUnicodeStr) + { + *pCurrPos = (byte) (i + 0xA0); + break; + } + } + } + else if (!(*pUnicodeStr & 0xFDE0)) + { + if (*pUnicodeStr == 0x0218) + { + *pCurrPos = 0xAA; + } + else if (*pUnicodeStr == 0x0219) + { + *pCurrPos = 0xBA; + } + else if (*pUnicodeStr == 0x021A) + { + *pCurrPos = 0xDE; + } + else if (*pUnicodeStr == 0x021B) + { + *pCurrPos = 0xFE; + } + else + { + return null; + } + } + else if (!(*pUnicodeStr & 0xDF40)) + { + if (*pUnicodeStr == 0x201D) + { + *pCurrPos = 0xB5; + } + else if (*pUnicodeStr == 0x201E) + { + *pCurrPos = 0xA5; + } + else if (*pUnicodeStr == 0x20AC) + { + *pCurrPos = 0xA4; + } + else + { + return null; + } + } + else + { + return null; + } + + pCurrPos++; + pUnicodeStr++; + srcLength--; + } + + SetLastResult(E_SUCCESS); + return pIso8859_16Byte.release(); +} + +wchar_t* +_Iso885916EncodingCore::DecodeN(const byte* pSrc, int srcLength, int& retLength) +{ + byte* pIso8859_16Byte = (byte*) pSrc; + result r = GetCharCount(pIso8859_16Byte, srcLength, retLength); + SysTryReturn(NID_TEXT, retLength > 0, null, r, "[%s] Encoding Failed", GetErrorMessage(r)); + + std::unique_ptr pUnicodeStr( new (std::nothrow) wchar_t[retLength + 1]); + SysTryReturn(NID_TEXT, pUnicodeStr, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + wchar_t* pCurrPos = pUnicodeStr.get(); + while (srcLength > 0) + { + if ((*pIso8859_16Byte) <= 0xA0) + { + *pCurrPos = (unsigned short) *pIso8859_16Byte; + } + // added following check to resolved c+=test issue, this check will always be true if the above condition is false + else if ((*pIso8859_16Byte) <= 0xFF) + { + *pCurrPos = ISO_8859_16_UNICODE_TABLE[*pIso8859_16Byte - 0xA0]; + } + pCurrPos++; + pIso8859_16Byte++; + srcLength--; + } + + pUnicodeStr[retLength] = '\0'; + SetLastResult(E_SUCCESS); + return pUnicodeStr.release(); +} + +int +_Iso885916EncodingCore::GetMaxByteCount(int charCount) const +{ + return charCount; +} + +int +_Iso885916EncodingCore::GetMaxCharCount(int byteCount) const +{ + return byteCount; +} + +} } // Tizen::Text diff --git a/src/text/FText_Iso885916EncodingCore.h b/src/text/FText_Iso885916EncodingCore.h new file mode 100644 index 0000000..b772a2f --- /dev/null +++ b/src/text/FText_Iso885916EncodingCore.h @@ -0,0 +1,60 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_Iso885916EncodingCore.h + * @brief This is the header file for the _Iso885916EncodingCore class. + */ + +#ifndef _FTEXT_INTERNAL_ISO885916_ENCODING_CORE_H_ +#define _FTEXT_INTERNAL_ISO885916_ENCODING_CORE_H_ + +#include +#include "FText_EncodingCore.h" + + +namespace Tizen { namespace Text +{ + +class _Iso885916EncodingCore + : public _EncodingCore +{ +public: + _Iso885916EncodingCore(void); + ~_Iso885916EncodingCore(void); + + static _EncodingCore* GetEncodingCoreImplN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo); + virtual result GetAvailableEncodingsN(Tizen::Base::Collection::IList* pEncodingList); + + virtual result GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength); + virtual result GetCharCount(const byte* pSrc, int srcLength, int& retLength); + + virtual byte* EncodeN(const wchar_t* pSrc, int srcLength, int& retLength); + virtual wchar_t* DecodeN(const byte* pSrc, int srcLength, int& retLength); + + virtual int GetMaxByteCount(int charCount) const; + virtual int GetMaxCharCount(int byteCount) const; + + virtual Tizen::Base::String GetName(void); + +}; // _Iso885916EncodingCore + + +} } // Tizen::Text + + +#endif //_FTEXT_INTERNAL_ISO885916_ENCODING_CORE_H_ diff --git a/src/text/FText_Ucs2EncodingCore.cpp b/src/text/FText_Ucs2EncodingCore.cpp new file mode 100644 index 0000000..1329274 --- /dev/null +++ b/src/text/FText_Ucs2EncodingCore.cpp @@ -0,0 +1,335 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_Ucs2EncodingCore.cpp + * @brief This is the implementation file for _Ucs2EncodingCore class. + */ + +// Includes +#include +#include +#include "FText_Ucs2EncodingCore.h" + + +using namespace Tizen::Base; + +#define UCS2_BOM_SIZE 2 +#define SUPPORTED_ENCODINGS_LENGTH 3 +static String supportedEncodings[] = { +"UCS2", "UCS2BE", "UCS2LE" +}; + +namespace Tizen { namespace Text +{ + +_Ucs2EncodingCore::_Ucs2EncodingCore(void) + : __encodingType(UCS2_ENCODING_BE) + , __bomType(UCS2_BOM_NONE) + , __encodingName("") +{ +} + + +_Ucs2EncodingCore::~_Ucs2EncodingCore(void) +{ +} + +_EncodingCore* +_Ucs2EncodingCore::GetEncodingCoreImplN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo) +{ + String encodingStr(encodingFrom); + encodingStr.ToUpper(); + + encodingStr.Replace(L"-", ""); + encodingStr.Replace("_", ""); + + if (!encodingStr.StartsWith(L"UCS2", 0)) + { + SetLastResult(E_UNSUPPORTED_TYPE); + return null; + } + + if ((encodingStr == "UCS2") || (encodingStr == "UCS2BE") || (encodingStr == "UCS2LE")) + { + std::unique_ptr<_Ucs2EncodingCore> pEncodingCore(new (std::nothrow) _Ucs2EncodingCore); + SysTryReturn(NID_TEXT, pEncodingCore, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + if (encodingStr == "UCS2") + { + pEncodingCore->__encodingType = UCS2_ENCODING_LE; //UCS2_ENCODING; + } + + if (encodingStr == "UCS2BE") + { + pEncodingCore->__encodingType = UCS2_ENCODING_BE; + } + + if (encodingStr == "UCS2LE") + { + pEncodingCore->__encodingType = UCS2_ENCODING_LE; + } + + pEncodingCore->__encodingName = encodingFrom; + + return pEncodingCore.release(); + } + + return null; +} + +result +_Ucs2EncodingCore::GetAvailableEncodingsN(Tizen::Base::Collection::IList* pEncodingList) +{ + SysTryReturnResult(NID_TEXT, pEncodingList, E_INVALID_ARG, + "[%s] Invalid argument is used. Input encoding list is null", GetErrorMessage(E_INVALID_ARG)); + + result r = E_SUCCESS; + String* pEncodingStr = null; + for (int i = 0; i < SUPPORTED_ENCODINGS_LENGTH; i++) + { + pEncodingStr = new (std::nothrow) String(supportedEncodings[i]); + SysTryReturnResult(NID_TEXT, pEncodingStr, E_OUT_OF_MEMORY, "Unable to allocate memory for encoding string."); + + r = pEncodingList->Add(*pEncodingStr); + if (IsFailed(r)) + { + delete pEncodingStr; + return r; + } + } + + return r; +} + +String +_Ucs2EncodingCore::GetName(void) +{ + return __encodingName; +} + +result +_Ucs2EncodingCore::GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength) +{ + retLength = -1; + wchar_t* pUnicodeStr = (wchar_t*) pSrc; + SysTryReturnResult(NID_TEXT, (pUnicodeStr != null), E_INVALID_ARG, + "[%s] Invalid argument is used. Input string pSrc is null.", GetErrorMessage(E_INVALID_ARG)); + + int ucs2Size = srcLength * 2; + while (srcLength > 0) + { + SysTryReturnResult(NID_TEXT, (*pUnicodeStr <= 0xFFFF), E_INVALID_ENCODING_RANGE, "[%s] Encoding failed. pSrc(%ls) contains code(%x) pointing outside of bounds by UCS2 encdoing.", GetErrorMessage(E_INVALID_ENCODING_RANGE), pSrc, *pUnicodeStr); + SysTryReturnResult(NID_TEXT, (*pUnicodeStr < 0xD800 || *pUnicodeStr > 0xDFFF), + E_INVALID_ENCODING_RANGE, + "[%s] Encoding failed. pSrc(%ls) contains code(%x) pointing outside of bounds by GSM encdoing.", GetErrorMessage(E_INVALID_ENCODING_RANGE), pSrc, *pUnicodeStr); + + srcLength--; + pUnicodeStr++; + } + + if (__encodingType == UCS2_ENCODING) + { + ucs2Size += UCS2_BOM_SIZE; + } + + retLength = ucs2Size; + return E_SUCCESS; +} + +result +_Ucs2EncodingCore::GetCharCount(const byte* pSrc, int srcLength, int& retLength) +{ + retLength = -1; + byte* pUcs2Byte = (byte*) pSrc; + if (pUcs2Byte != null) + { + if (__encodingType == UCS2_ENCODING && srcLength > 2) + { + if ((pUcs2Byte[0] == 0xFE) && (pUcs2Byte[1] == 0xFF)) + { + __bomType = UCS2_BOM_BE; + srcLength -= 2; + pUcs2Byte += 2; + } + else if ((pUcs2Byte[0] == 0xFF) && (pUcs2Byte[1] == 0xFE)) + { + __bomType = UCS2_BOM_LE; + srcLength -= 2; + pUcs2Byte += 2; + } + else + { + __bomType = UCS2_BOM_NONE; + } + } + + if ((srcLength == 0x01) && (pUcs2Byte[srcLength - 1] == '\0')) + { + retLength = 1; + return E_SUCCESS; + } + + if ((srcLength & 0x01) && (pUcs2Byte[srcLength - 1] != '\0')) + { + return E_INVALID_ENCODING_RANGE; + } + + int uniSize = srcLength >> 1; + while (srcLength > 0) + { + if (__encodingType == UCS2_ENCODING_BE || __bomType == UCS2_BOM_BE) + { + if (!(*pUcs2Byte < 0xD8 || *pUcs2Byte > 0xDF)) + { + return E_INVALID_ENCODING_RANGE; + } + pUcs2Byte += 2; + } + else + { + pUcs2Byte++; + if (!(*pUcs2Byte < 0xD8 || *pUcs2Byte > 0xDF)) + { + return E_INVALID_ENCODING_RANGE; + } + pUcs2Byte++; + } + srcLength -= 2; + } + + retLength = uniSize; + return E_SUCCESS; + } + + return E_INVALID_ARG; +} + +byte* +_Ucs2EncodingCore::EncodeN(const wchar_t* pSrc, int srcLength, int& retLength) +{ + result r = GetByteCount(pSrc, srcLength, retLength); + SysTryReturn(NID_TEXT, retLength >= 0, null, r, + "[%s] Encoding Failed. retLength(%d) can not be negative", GetErrorMessage(r), retLength); + + std::unique_ptrpUcs2Byte(new (std::nothrow) byte[retLength + 1]); + SysTryReturn(NID_TEXT, pUcs2Byte, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + wchar_t* pUnicodeStr = (wchar_t*) pSrc; + byte* pCurrPos = pUcs2Byte.get(); + if (__encodingType == UCS2_ENCODING) + { + *pCurrPos = 0xFF; + pCurrPos++; + *pCurrPos = 0xFE; + pCurrPos++; + } + + if (__encodingType == UCS2_ENCODING_BE) + { + while (srcLength > 0) + { + *pCurrPos = (byte) ((*pUnicodeStr & 0xFF00) >> 8); + *(++pCurrPos) = (byte) (*pUnicodeStr & 0x00FF); + + pCurrPos++; + pUnicodeStr++; + srcLength--; + } + } + else + { + while (srcLength > 0) + { + *pCurrPos = (byte) (*pUnicodeStr & 0x00FF); + *(++pCurrPos) = (byte) ((*pUnicodeStr & 0xFF00) >> 8); + + pCurrPos++; + pUnicodeStr++; + srcLength--; + } + } + + SetLastResult(E_SUCCESS); + return pUcs2Byte.release(); +} + +wchar_t* +_Ucs2EncodingCore::DecodeN(const byte* pSrc, int srcLength, int& retLength) +{ + result r = GetCharCount(pSrc, srcLength, retLength); + SysTryReturn(NID_TEXT, retLength >= 0, null, r, "[%s] Encoding Failed", GetErrorMessage(r)); + + byte* pUcs2Byte = (byte*) pSrc; + std::unique_ptr pUnicodeStr( new (std::nothrow) wchar_t[retLength + 1]); + + SysTryReturn(NID_TEXT, pUnicodeStr, null, E_OUT_OF_MEMORY, "[%s] Memory allocation failed", GetErrorMessage(E_OUT_OF_MEMORY)); + + if (__encodingType == UCS2_ENCODING) + { + if (__bomType != UCS2_BOM_NONE) + { + pUcs2Byte += 2; + srcLength -= 2; + } + } + + wchar_t* pCurrPos = pUnicodeStr.get(); + if (__encodingType == UCS2_ENCODING_BE || __bomType == UCS2_BOM_BE) + { + while (srcLength > 0) + { + *pCurrPos = (((wchar_t) *pUcs2Byte) << 8); + *pCurrPos = *pCurrPos | ((wchar_t) *(++pUcs2Byte)); + + pCurrPos++; + pUcs2Byte++; + srcLength -= 2; + } + } + else + { + while (srcLength > 0) + { + *pCurrPos = ((wchar_t) *pUcs2Byte); + *pCurrPos = *pCurrPos | (((wchar_t) *(++pUcs2Byte)) << 8); + + pCurrPos++; + pUcs2Byte++; + srcLength -= 2; + } + } + + pUnicodeStr[retLength] = '\0'; + SetLastResult(E_SUCCESS); + __bomType = UCS2_BOM_NONE; + return pUnicodeStr.release(); +} + +int +_Ucs2EncodingCore::GetMaxByteCount(int charCount) const +{ + return charCount * 2; +} + +int +_Ucs2EncodingCore::GetMaxCharCount(int byteCount) const +{ + return byteCount; +} + +} } // Tizen::Text diff --git a/src/text/FText_Ucs2EncodingCore.h b/src/text/FText_Ucs2EncodingCore.h new file mode 100644 index 0000000..47c4b41 --- /dev/null +++ b/src/text/FText_Ucs2EncodingCore.h @@ -0,0 +1,79 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_Ucs2EncodingCore.h + * @brief This is the header file for the _Ucs2EncodingCore class. + */ + +#ifndef _FTEXT_INTERNAL_UCS2_ENCODING_CORE_H_ +#define _FTEXT_INTERNAL_UCS2_ENCODING_CORE_H_ + +#include +#include "FText_EncodingCore.h" + + +namespace Tizen { namespace Text +{ + +enum Ucs2EncodingType +{ + UCS2_ENCODING, + UCS2_ENCODING_BE, + UCS2_ENCODING_LE +}; + +enum Ucs2BomType +{ + UCS2_BOM_NONE, + UCS2_BOM_BE, + UCS2_BOM_LE +}; + +class _Ucs2EncodingCore + : public _EncodingCore +{ +public: + _Ucs2EncodingCore(void); + ~_Ucs2EncodingCore(void); + + static _EncodingCore* GetEncodingCoreImplN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo); + virtual result GetAvailableEncodingsN(Tizen::Base::Collection::IList* pEncodingList); + + virtual result GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength); + virtual result GetCharCount(const byte* pSrc, int srcLength, int& retLength); + + virtual byte* EncodeN(const wchar_t* pSrc, int srcLength, int& retLength); + virtual wchar_t* DecodeN(const byte* pSrc, int srcLength, int& retLength); + + virtual int GetMaxByteCount(int charCount) const; + virtual int GetMaxCharCount(int byteCount) const; + + virtual Tizen::Base::String GetName(void); + +private: + Ucs2EncodingType __encodingType; + Ucs2BomType __bomType; + Tizen::Base::String __encodingName; + +}; // _Ucs2EncodingCore + + +} } // Tizen::Text + + +#endif //_FTEXT_INTERNAL_UCS2_ENCODING_CORE_H_ diff --git a/src/text/inc/FText_EncodingCore.h b/src/text/inc/FText_EncodingCore.h new file mode 100644 index 0000000..93e96d9 --- /dev/null +++ b/src/text/inc/FText_EncodingCore.h @@ -0,0 +1,77 @@ +// +// Open Service Platform +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +/** + * @file FText_EncodingCore.h + * @brief This is the header file for the _EncodingCore class. + */ + +#ifndef _FTEXT_INTERNAL_ENCODING_CORE_H_ +#define _FTEXT_INTERNAL_ENCODING_CORE_H_ + +#include +#include +#include +#include + + +namespace Tizen { namespace Text +{ + +class _EncodingCore + : public Tizen::Base::Object +{ +public: + virtual ~_EncodingCore(void); + + static _EncodingCore* GetEncodingCoreN(const Tizen::Base::String& encodingFrom, const Tizen::Base::String& encodingTo); + + static Tizen::Base::Collection::IList* GetAvailableEncodingsN(void); + + virtual result GetAvailableEncodingsN(Tizen::Base::Collection::IList* pEncodingList) = 0; + + virtual result GetByteCount(const wchar_t* pSrc, int srcLength, int& retLength) = 0; + virtual result GetCharCount(const byte* pSrc, int srcLength, int& retLength) = 0; + + virtual byte* EncodeN(const wchar_t* pSrc, int srcLength, int& retLength) = 0; + virtual wchar_t* DecodeN(const byte* pSrc, int srcLength, int& retLength) = 0; + + virtual byte* EncodeExN(const wchar_t* pSrc, int srcLength, int& retLength, bool flush); + virtual wchar_t* DecodeExN(const byte* pSrc, int srcLength, int& retLength, bool flush); + + virtual byte* ConvertN(_EncodingCore* pDstConverter, const byte* pSrc, int srcLength, int& retLength); + + virtual int GetMaxByteCount(int charCount) const = 0; + virtual int GetMaxCharCount(int byteCount) const = 0; + + virtual Tizen::Base::String GetName(void) = 0; + +protected: + _EncodingCore(void); + +protected: + Tizen::Base::String _encodingTo; + Tizen::Base::String _encodingFrom; + + +}; // _EncodingCore + + +} } // Tizen::Text + + +#endif // _FTEXT_INTERNAL_ENCODING_CORE_H_ -- 2.7.4